@getchomp/mcp 0.0.0-stage → 0.2.43
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/LICENSE +21 -0
- package/README.md +15 -2
- package/dist/conventionsReference.d.ts +84 -0
- package/dist/conventionsReference.js +313 -0
- package/dist/designSystem/astScanner.d.ts +153 -0
- package/dist/designSystem/astScanner.js +2014 -0
- package/dist/designSystem/baseline.d.ts +65 -0
- package/dist/designSystem/baseline.js +136 -0
- package/dist/designSystem/color.d.ts +35 -0
- package/dist/designSystem/color.js +265 -0
- package/dist/designSystem/config.d.ts +183 -0
- package/dist/designSystem/config.js +469 -0
- package/dist/designSystem/contrast.d.ts +55 -0
- package/dist/designSystem/contrast.js +377 -0
- package/dist/designSystem/cssParser.d.ts +63 -0
- package/dist/designSystem/cssParser.js +469 -0
- package/dist/designSystem/merges.d.ts +57 -0
- package/dist/designSystem/merges.js +94 -0
- package/dist/designSystem/preprocessors.d.ts +46 -0
- package/dist/designSystem/preprocessors.js +1108 -0
- package/dist/designSystem/presentation.d.ts +45 -0
- package/dist/designSystem/presentation.js +796 -0
- package/dist/designSystem/styleVectors.d.ts +27 -0
- package/dist/designSystem/styleVectors.js +484 -0
- package/dist/designSystem/tokens.d.ts +39 -0
- package/dist/designSystem/tokens.js +409 -0
- package/dist/designSystem/topology.d.ts +64 -0
- package/dist/designSystem/topology.js +254 -0
- package/dist/designSystem/types.d.ts +857 -0
- package/dist/designSystem/types.js +113 -0
- package/dist/designSystem/typography.d.ts +25 -0
- package/dist/designSystem/typography.js +244 -0
- package/dist/designSystem/uiShapes.d.ts +74 -0
- package/dist/designSystem/uiShapes.js +285 -0
- package/dist/designSystem/valueClusters.d.ts +76 -0
- package/dist/designSystem/valueClusters.js +281 -0
- package/dist/designSystemPlugin.d.ts +321 -0
- package/dist/designSystemPlugin.js +4730 -0
- package/dist/enrichNodesPlugin.d.ts +160 -0
- package/dist/enrichNodesPlugin.js +957 -0
- package/dist/index.d.ts +65 -0
- package/dist/index.js +1298 -0
- package/dist/intelligence.d.ts +502 -0
- package/dist/intelligence.js +3058 -0
- package/dist/pluginRunner.d.ts +364 -0
- package/dist/pluginRunner.js +1096 -0
- package/dist/plugins/design-system/index.d.ts +14 -0
- package/dist/plugins/design-system/index.js +241 -0
- package/dist/plugins/enrich-nodes/index.d.ts +388 -0
- package/dist/plugins/enrich-nodes/index.js +697 -0
- package/dist/plugins/index.d.ts +15 -0
- package/dist/plugins/index.js +20 -0
- package/dist/plugins/local-shims/index.d.ts +121 -0
- package/dist/plugins/local-shims/index.js +237 -0
- package/dist/shimsPlugin.d.ts +134 -0
- package/dist/shimsPlugin.js +1392 -0
- package/package.json +39 -3
|
@@ -0,0 +1,3058 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* packages/mcp/src/intelligence.ts
|
|
3
|
+
*
|
|
4
|
+
* Architectural Intelligence, Pre-Edit Blast Radius & Pattern Alignment Engine
|
|
5
|
+
* Enforces [PAT-MCP-08] and [PAT-MCP-09].
|
|
6
|
+
*
|
|
7
|
+
* Operates purely on the deterministic RepresentationGraph from @getchomp/core
|
|
8
|
+
* with zero external runtime dependencies so every helper resolves cleanly
|
|
9
|
+
* on the Layer 0 structural graph.
|
|
10
|
+
*/
|
|
11
|
+
import { existsSync, readFileSync } from "node:fs";
|
|
12
|
+
import { resolve } from "node:path";
|
|
13
|
+
import { clusterSignalInstances, computeActionableUnresolvedCallsByNode, computeStructuralHealthMetrics, findDarkFiles, mergeContractPortValves, orphanShapeKey, } from "@getchomp/core";
|
|
14
|
+
const CONTAINER_ENTITY_TYPES = new Set(["DEPLOYMENT_UNIT"]);
|
|
15
|
+
const PACKAGE_CONNECTOR_ENTITY_TYPES = new Set([
|
|
16
|
+
"EXTERNAL_PACKAGE",
|
|
17
|
+
"NODE_BUILTIN",
|
|
18
|
+
]);
|
|
19
|
+
const INGRESS_ENTITY_TYPES = new Set([
|
|
20
|
+
"API_ENDPOINT",
|
|
21
|
+
"HTTP_ENDPOINT",
|
|
22
|
+
"NEXTJS_PAGE",
|
|
23
|
+
"NEXTJS_LAYOUT",
|
|
24
|
+
"NEXTJS_MIDDLEWARE",
|
|
25
|
+
"EVENT_LISTENER",
|
|
26
|
+
]);
|
|
27
|
+
const INIT_BLOCK_ENTITY_TYPE = "INIT_BLOCK";
|
|
28
|
+
const FLOW_EDGE_ENTITY_TYPES = new Set([
|
|
29
|
+
"CALL",
|
|
30
|
+
"HTTP_FETCH",
|
|
31
|
+
"REQUESTS",
|
|
32
|
+
"DB_QUERY",
|
|
33
|
+
"DB_OPERATION",
|
|
34
|
+
"LOCAL_API_CALL",
|
|
35
|
+
"EVENT_EMIT",
|
|
36
|
+
"RENDERS",
|
|
37
|
+
"REGISTERS",
|
|
38
|
+
"BINDS_ROUTE",
|
|
39
|
+
"INTERCEPTS",
|
|
40
|
+
"INHERITS",
|
|
41
|
+
"MIXES",
|
|
42
|
+
]);
|
|
43
|
+
const CONNECTOR_LEAK_ENTITY_TYPES = new Set([
|
|
44
|
+
"DB_QUERY",
|
|
45
|
+
"DB_OPERATION",
|
|
46
|
+
"DB_TRANSACTION",
|
|
47
|
+
"HTTP_FETCH",
|
|
48
|
+
"HTTP_REQUEST",
|
|
49
|
+
]);
|
|
50
|
+
const HTTP_INVOCATION_EDGE_TYPES = new Set([
|
|
51
|
+
"HTTP_FETCH",
|
|
52
|
+
"REQUESTS",
|
|
53
|
+
"CALL",
|
|
54
|
+
"LOCAL_API_CALL",
|
|
55
|
+
]);
|
|
56
|
+
const NON_HTTP_ROUTE_PATTERN_IDS = new Set([
|
|
57
|
+
"contract.mcp-tool",
|
|
58
|
+
"contract.express-route-parameter",
|
|
59
|
+
"contract.express-content-negotiation",
|
|
60
|
+
"contract.express-dynamic-methods",
|
|
61
|
+
]);
|
|
62
|
+
const CONNECTIVITY_TARGET_TYPES = new Set([
|
|
63
|
+
"CALL",
|
|
64
|
+
"INHERITS",
|
|
65
|
+
"MIXES",
|
|
66
|
+
"RENDERS",
|
|
67
|
+
"BINDS_ROUTE",
|
|
68
|
+
"INTERCEPTS",
|
|
69
|
+
]);
|
|
70
|
+
const NON_EXECUTABLE_CONTRACT_ENTITY_TYPES = new Set([
|
|
71
|
+
"EXPORTED_TYPE",
|
|
72
|
+
"TYPE_DEFINITION",
|
|
73
|
+
"DB_SCHEMA",
|
|
74
|
+
"VALIDATOR_SCHEMA",
|
|
75
|
+
"COLLECTION_CONFIG",
|
|
76
|
+
"SERVER_GUARD",
|
|
77
|
+
"ROUTE_CONFIG",
|
|
78
|
+
"NEXTJS_METADATA",
|
|
79
|
+
"NEXTJS_ROUTE_CONFIG",
|
|
80
|
+
"EXPRESS_ROUTE_PARAM",
|
|
81
|
+
]);
|
|
82
|
+
const LABEL_PREFIX_RE = /^(Exported Function|Class|HTTP Endpoint|API Endpoint|Exported Type|Exported Module|CJS Export|Express Mount|Express Route|Middleware|DB Call|HTTP Call|Socket Call|Call|Public Method|Namespace|Deployment Unit|Package|MCP Tool|Next\.js Page|Next\.js Layout|Next\.js Lifecycle|Next\.js Middleware|Next\.js Config|Next\.js Cache|Route Handler|Server Action):\s*/i;
|
|
83
|
+
function round1(val) {
|
|
84
|
+
return Math.round(val * 10) / 10;
|
|
85
|
+
}
|
|
86
|
+
function deploymentUnitLabel(name) {
|
|
87
|
+
const withoutPrefix = name.replace(/^Deployment Unit:\s*/i, "");
|
|
88
|
+
return withoutPrefix.split("/").pop() || withoutPrefix;
|
|
89
|
+
}
|
|
90
|
+
function cleanNodeLabel(name) {
|
|
91
|
+
const stripped = name.replace(LABEL_PREFIX_RE, "");
|
|
92
|
+
if (/^(GET|POST|PUT|DELETE|PATCH|HEAD|OPTIONS)\s/i.test(stripped) ||
|
|
93
|
+
stripped.startsWith("/") ||
|
|
94
|
+
/^(generateMetadata|generateStaticParams)\s*\(/.test(stripped)) {
|
|
95
|
+
return stripped;
|
|
96
|
+
}
|
|
97
|
+
if (/^Init:\s+/i.test(stripped)) {
|
|
98
|
+
const unitPart = stripped.replace(/^Init:\s+/i, "");
|
|
99
|
+
return `Init: ${unitPart.split("/").pop() || unitPart}`;
|
|
100
|
+
}
|
|
101
|
+
return stripped.split("/").pop() || stripped;
|
|
102
|
+
}
|
|
103
|
+
function isHiddenNode(node) {
|
|
104
|
+
return (CONTAINER_ENTITY_TYPES.has(node.entityType) ||
|
|
105
|
+
PACKAGE_CONNECTOR_ENTITY_TYPES.has(node.entityType));
|
|
106
|
+
}
|
|
107
|
+
function isUnprovableFallback(edge) {
|
|
108
|
+
return (edge.patternId === "relationship.invoke-returned-function" && !edge.targetId);
|
|
109
|
+
}
|
|
110
|
+
function parseNodeMeta(node) {
|
|
111
|
+
if (!node.metadata)
|
|
112
|
+
return {};
|
|
113
|
+
if (typeof node.metadata === "string") {
|
|
114
|
+
try {
|
|
115
|
+
return JSON.parse(node.metadata) ?? {};
|
|
116
|
+
}
|
|
117
|
+
catch {
|
|
118
|
+
return {};
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
return typeof node.metadata === "object" ? node.metadata : {};
|
|
122
|
+
}
|
|
123
|
+
function getPrimaryEvidence(entity) {
|
|
124
|
+
const ev = entity.evidence;
|
|
125
|
+
if (!ev)
|
|
126
|
+
return {};
|
|
127
|
+
if (Array.isArray(ev)) {
|
|
128
|
+
const syntaxEv = ev.find((r) => r?.evidenceRole === "syntax-call" && r?.filePath) ??
|
|
129
|
+
ev.find((r) => Boolean(r?.filePath)) ??
|
|
130
|
+
ev[0];
|
|
131
|
+
return {
|
|
132
|
+
filePath: syntaxEv?.filePath,
|
|
133
|
+
lineNumber: syntaxEv?.lineNumber,
|
|
134
|
+
snippet: syntaxEv?.snippet,
|
|
135
|
+
};
|
|
136
|
+
}
|
|
137
|
+
return {
|
|
138
|
+
filePath: ev.filePath,
|
|
139
|
+
lineNumber: ev.lineNumber,
|
|
140
|
+
snippet: ev.snippet,
|
|
141
|
+
};
|
|
142
|
+
}
|
|
143
|
+
function normalizePackageQuery(rawPkg) {
|
|
144
|
+
return rawPkg
|
|
145
|
+
.trim()
|
|
146
|
+
.toLowerCase()
|
|
147
|
+
.replace(/^deployment unit:\s*/i, "")
|
|
148
|
+
.replace(/^@[^/]+\//, "")
|
|
149
|
+
.replace(/^(packages|apps)\//, "")
|
|
150
|
+
.replace(/\/+$/, "");
|
|
151
|
+
}
|
|
152
|
+
/**
|
|
153
|
+
* Matches a node's resolved owning package (and optional path) against a user/agent
|
|
154
|
+
* `packageName` filter without leaking mid-word file-path substrings across packages
|
|
155
|
+
* (e.g., `"db"` must never match `apps/web/.../adapterSandbox.ts`).
|
|
156
|
+
*/
|
|
157
|
+
export function packageMatchesFilter(nodePkg, nodePath, rawFilter) {
|
|
158
|
+
const rawLower = rawFilter
|
|
159
|
+
.trim()
|
|
160
|
+
.toLowerCase()
|
|
161
|
+
.replace(/^deployment unit:\s*/i, "")
|
|
162
|
+
.replace(/\/+$/, "");
|
|
163
|
+
const normFilter = normalizePackageQuery(rawFilter);
|
|
164
|
+
if (!normFilter && !rawLower)
|
|
165
|
+
return true;
|
|
166
|
+
const pkgClean = nodePkg
|
|
167
|
+
.trim()
|
|
168
|
+
.toLowerCase()
|
|
169
|
+
.replace(/^deployment unit:\s*/i, "");
|
|
170
|
+
const pkgShort = pkgClean.replace(/^@[^/]+\//, "");
|
|
171
|
+
if (pkgClean) {
|
|
172
|
+
if (rawLower.startsWith("@") && pkgClean.startsWith("@")) {
|
|
173
|
+
if (pkgClean === rawLower)
|
|
174
|
+
return true;
|
|
175
|
+
}
|
|
176
|
+
else if (pkgClean === rawLower ||
|
|
177
|
+
pkgClean === normFilter ||
|
|
178
|
+
pkgShort === rawLower ||
|
|
179
|
+
pkgShort === normFilter) {
|
|
180
|
+
return true;
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
const posixPath = (nodePath ?? "")
|
|
184
|
+
.replace(/\\/g, "/")
|
|
185
|
+
.replace(/^\.\//, "")
|
|
186
|
+
.replace(/\/+$/, "")
|
|
187
|
+
.toLowerCase();
|
|
188
|
+
if (!posixPath)
|
|
189
|
+
return false;
|
|
190
|
+
if (rawLower.includes("/") && !rawLower.startsWith("@")) {
|
|
191
|
+
const pathQuery = rawLower.replace(/^\.\//, "");
|
|
192
|
+
if (posixPath === pathQuery ||
|
|
193
|
+
posixPath.startsWith(`${pathQuery}/`) ||
|
|
194
|
+
posixPath.includes(`/${pathQuery}/`) ||
|
|
195
|
+
posixPath.endsWith(`/${pathQuery}`)) {
|
|
196
|
+
return true;
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
if (!pkgClean || pkgClean === "root") {
|
|
200
|
+
const segments = posixPath.split("/");
|
|
201
|
+
if (segments.includes(rawLower) || (Boolean(normFilter) && segments.includes(normFilter))) {
|
|
202
|
+
return true;
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
return false;
|
|
206
|
+
}
|
|
207
|
+
function toNodeSummaryRef(node, resolveNodePkg) {
|
|
208
|
+
const ev = getPrimaryEvidence(node);
|
|
209
|
+
return {
|
|
210
|
+
id: node.id,
|
|
211
|
+
name: node.name,
|
|
212
|
+
label: cleanNodeLabel(node.name),
|
|
213
|
+
type: node.type,
|
|
214
|
+
entityType: node.entityType,
|
|
215
|
+
packageName: resolveNodePkg(node.id) || "root",
|
|
216
|
+
...(ev.filePath ? { filePath: ev.filePath } : {}),
|
|
217
|
+
...(ev.lineNumber !== undefined ? { lineNumber: ev.lineNumber } : {}),
|
|
218
|
+
};
|
|
219
|
+
}
|
|
220
|
+
function computeUnresolvedCallsMap(graph, nodeById, flowOutTargetsBySource) {
|
|
221
|
+
return computeActionableUnresolvedCallsByNode(graph, nodeById, flowOutTargetsBySource, isHiddenNode);
|
|
222
|
+
}
|
|
223
|
+
function buildGraphIndex(graph) {
|
|
224
|
+
const nodeById = new Map();
|
|
225
|
+
for (const n of graph.nodes) {
|
|
226
|
+
if (!nodeById.has(n.id))
|
|
227
|
+
nodeById.set(n.id, n);
|
|
228
|
+
}
|
|
229
|
+
const deploymentUnitsByPkg = new Map();
|
|
230
|
+
const pathPrefixByPkg = new Map();
|
|
231
|
+
for (const n of nodeById.values()) {
|
|
232
|
+
if (n.entityType === "DEPLOYMENT_UNIT") {
|
|
233
|
+
const pkg = deploymentUnitLabel(n.name);
|
|
234
|
+
if (pkg) {
|
|
235
|
+
deploymentUnitsByPkg.set(pkg, n);
|
|
236
|
+
const ev = getPrimaryEvidence(n);
|
|
237
|
+
if (ev.filePath && ev.filePath !== ".") {
|
|
238
|
+
pathPrefixByPkg.set(pkg, ev.filePath.replace(/\/+$/, ""));
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
const pkgCache = new Map();
|
|
244
|
+
const resolveNodePkg = (nodeId) => {
|
|
245
|
+
const cached = pkgCache.get(nodeId);
|
|
246
|
+
if (cached !== undefined)
|
|
247
|
+
return cached;
|
|
248
|
+
let label = "";
|
|
249
|
+
const seen = new Set();
|
|
250
|
+
let cursor = nodeById.get(nodeId);
|
|
251
|
+
while (cursor && !seen.has(cursor.id)) {
|
|
252
|
+
seen.add(cursor.id);
|
|
253
|
+
if (cursor.entityType === "DEPLOYMENT_UNIT") {
|
|
254
|
+
label = deploymentUnitLabel(cursor.name);
|
|
255
|
+
break;
|
|
256
|
+
}
|
|
257
|
+
cursor = cursor.parentBoundaryId
|
|
258
|
+
? nodeById.get(cursor.parentBoundaryId)
|
|
259
|
+
: undefined;
|
|
260
|
+
}
|
|
261
|
+
if (!label) {
|
|
262
|
+
const rawNode = nodeById.get(nodeId);
|
|
263
|
+
const ev = rawNode ? getPrimaryEvidence(rawNode) : {};
|
|
264
|
+
if (ev.filePath) {
|
|
265
|
+
for (const [pkg, prefix] of pathPrefixByPkg.entries()) {
|
|
266
|
+
if (ev.filePath === prefix || ev.filePath.startsWith(`${prefix}/`)) {
|
|
267
|
+
label = pkg;
|
|
268
|
+
break;
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
if (!label && rawNode?.entityType === INIT_BLOCK_ENTITY_TYPE) {
|
|
273
|
+
const initUnit = deploymentUnitLabel(rawNode.name.replace(/^Init:\s*/i, ""));
|
|
274
|
+
if (initUnit) {
|
|
275
|
+
label = initUnit;
|
|
276
|
+
}
|
|
277
|
+
}
|
|
278
|
+
}
|
|
279
|
+
pkgCache.set(nodeId, label);
|
|
280
|
+
return label;
|
|
281
|
+
};
|
|
282
|
+
const outEdgesBySource = new Map();
|
|
283
|
+
const inEdgesByTarget = new Map();
|
|
284
|
+
const flowOutTargetsBySource = new Map();
|
|
285
|
+
const flowInSourcesByTarget = new Map();
|
|
286
|
+
for (const edge of graph.edges) {
|
|
287
|
+
if (!outEdgesBySource.has(edge.sourceId)) {
|
|
288
|
+
outEdgesBySource.set(edge.sourceId, []);
|
|
289
|
+
}
|
|
290
|
+
outEdgesBySource.get(edge.sourceId).push(edge);
|
|
291
|
+
if (!edge.targetId)
|
|
292
|
+
continue;
|
|
293
|
+
if (!inEdgesByTarget.has(edge.targetId)) {
|
|
294
|
+
inEdgesByTarget.set(edge.targetId, []);
|
|
295
|
+
}
|
|
296
|
+
inEdgesByTarget.get(edge.targetId).push(edge);
|
|
297
|
+
if (!FLOW_EDGE_ENTITY_TYPES.has(edge.entityType))
|
|
298
|
+
continue;
|
|
299
|
+
const src = nodeById.get(edge.sourceId);
|
|
300
|
+
const tgt = nodeById.get(edge.targetId);
|
|
301
|
+
if (!src || !tgt)
|
|
302
|
+
continue;
|
|
303
|
+
if (isHiddenNode(src) || isHiddenNode(tgt))
|
|
304
|
+
continue;
|
|
305
|
+
if (src.id === tgt.id)
|
|
306
|
+
continue;
|
|
307
|
+
let outList = flowOutTargetsBySource.get(src.id);
|
|
308
|
+
if (!outList) {
|
|
309
|
+
outList = [];
|
|
310
|
+
flowOutTargetsBySource.set(src.id, outList);
|
|
311
|
+
}
|
|
312
|
+
if (!outList.includes(tgt.id)) {
|
|
313
|
+
outList.push(tgt.id);
|
|
314
|
+
}
|
|
315
|
+
let inList = flowInSourcesByTarget.get(tgt.id);
|
|
316
|
+
if (!inList) {
|
|
317
|
+
inList = [];
|
|
318
|
+
flowInSourcesByTarget.set(tgt.id, inList);
|
|
319
|
+
}
|
|
320
|
+
if (!inList.includes(src.id)) {
|
|
321
|
+
inList.push(src.id);
|
|
322
|
+
}
|
|
323
|
+
}
|
|
324
|
+
const unresolvedCallsByNodeId = computeUnresolvedCallsMap(graph, nodeById, flowOutTargetsBySource);
|
|
325
|
+
return {
|
|
326
|
+
nodeById,
|
|
327
|
+
deploymentUnitsByPkg,
|
|
328
|
+
pathPrefixByPkg,
|
|
329
|
+
resolveNodePkg,
|
|
330
|
+
outEdgesBySource,
|
|
331
|
+
inEdgesByTarget,
|
|
332
|
+
flowOutTargetsBySource,
|
|
333
|
+
flowInSourcesByTarget,
|
|
334
|
+
unresolvedCallsByNodeId,
|
|
335
|
+
};
|
|
336
|
+
}
|
|
337
|
+
function getAllEvidenceRecords(entity) {
|
|
338
|
+
if (!entity || !entity.evidence)
|
|
339
|
+
return [];
|
|
340
|
+
const ev = entity.evidence;
|
|
341
|
+
if (Array.isArray(ev)) {
|
|
342
|
+
return ev.map((r) => ({
|
|
343
|
+
filePath: r?.filePath,
|
|
344
|
+
lineNumber: r?.lineNumber,
|
|
345
|
+
snippet: r?.snippet,
|
|
346
|
+
}));
|
|
347
|
+
}
|
|
348
|
+
return [
|
|
349
|
+
{
|
|
350
|
+
filePath: ev.filePath,
|
|
351
|
+
lineNumber: ev.lineNumber,
|
|
352
|
+
snippet: ev.snippet,
|
|
353
|
+
},
|
|
354
|
+
];
|
|
355
|
+
}
|
|
356
|
+
function normalizeUrlToPathname(raw) {
|
|
357
|
+
let s = raw.trim();
|
|
358
|
+
if (!s)
|
|
359
|
+
return null;
|
|
360
|
+
s = s.replace(/\$\{[^}]+\}/g, ":param");
|
|
361
|
+
if (/^https?:\/\//i.test(s)) {
|
|
362
|
+
try {
|
|
363
|
+
const parsed = new URL(s.replace(/:param/g, "__param__"));
|
|
364
|
+
s = parsed.pathname.replace(/__param__/g, ":param");
|
|
365
|
+
}
|
|
366
|
+
catch {
|
|
367
|
+
const slashIdx = s.indexOf("/", s.indexOf("//") + 2);
|
|
368
|
+
s = slashIdx >= 0 ? s.slice(slashIdx) : "/";
|
|
369
|
+
}
|
|
370
|
+
}
|
|
371
|
+
else if (s.startsWith(":param/")) {
|
|
372
|
+
s = s.slice(":param".length);
|
|
373
|
+
}
|
|
374
|
+
if (!s.startsWith("/"))
|
|
375
|
+
return null;
|
|
376
|
+
s = s.split("?")[0].split("#")[0];
|
|
377
|
+
s = s.replace(/\/{2,}/g, "/");
|
|
378
|
+
if (s.length > 1 && s.endsWith("/")) {
|
|
379
|
+
s = s.slice(0, -1);
|
|
380
|
+
}
|
|
381
|
+
return s;
|
|
382
|
+
}
|
|
383
|
+
function extractStaticRoutePrefix(rawPath) {
|
|
384
|
+
const pathname = normalizeUrlToPathname(rawPath);
|
|
385
|
+
if (!pathname)
|
|
386
|
+
return null;
|
|
387
|
+
let cleaned = pathname
|
|
388
|
+
.replace(/\/:param\b.*$/, "")
|
|
389
|
+
.replace(/:param\b.*$/, "")
|
|
390
|
+
.replace(/\/:[A-Za-z0-9_]+\*?.*$/, "")
|
|
391
|
+
.replace(/\/\[[^\]]+\].*$/, "")
|
|
392
|
+
.replace(/\/\*.*$/, "");
|
|
393
|
+
if (cleaned.length > 1 && cleaned.endsWith("/")) {
|
|
394
|
+
cleaned = cleaned.slice(0, -1);
|
|
395
|
+
}
|
|
396
|
+
return cleaned || "/";
|
|
397
|
+
}
|
|
398
|
+
function canonicalizeRoutePattern(rawPath) {
|
|
399
|
+
const pathname = normalizeUrlToPathname(rawPath);
|
|
400
|
+
if (!pathname)
|
|
401
|
+
return null;
|
|
402
|
+
const expanded = pathname.replace(/([^/]):param\b/g, "$1/:param");
|
|
403
|
+
const segments = expanded
|
|
404
|
+
.split("/")
|
|
405
|
+
.filter((seg, idx) => idx === 0 || seg.length > 0)
|
|
406
|
+
.map((seg) => {
|
|
407
|
+
if (seg === ":param" || seg === "*")
|
|
408
|
+
return ":param";
|
|
409
|
+
if (seg.startsWith(":") && seg.length > 1)
|
|
410
|
+
return ":param";
|
|
411
|
+
if (seg.startsWith("[") && seg.endsWith("]") && seg.length > 2)
|
|
412
|
+
return ":param";
|
|
413
|
+
return seg;
|
|
414
|
+
});
|
|
415
|
+
const joined = segments.join("/") || "/";
|
|
416
|
+
return joined.startsWith("/") ? joined : `/${joined}`;
|
|
417
|
+
}
|
|
418
|
+
function joinMountAndRoute(mountPrefix, declaredPath) {
|
|
419
|
+
const normMount = extractStaticRoutePrefix(mountPrefix) ?? "/";
|
|
420
|
+
const normRoute = normalizeUrlToPathname(declaredPath) ?? "/";
|
|
421
|
+
if (normMount === "/")
|
|
422
|
+
return normRoute;
|
|
423
|
+
if (normRoute === "/")
|
|
424
|
+
return normMount;
|
|
425
|
+
if (normRoute === normMount || normRoute.startsWith(`${normMount}/`)) {
|
|
426
|
+
return normRoute;
|
|
427
|
+
}
|
|
428
|
+
return `${normMount}${normRoute.startsWith("/") ? normRoute : `/${normRoute}`}`;
|
|
429
|
+
}
|
|
430
|
+
function extractRewriteRulesFromText(text, filePath) {
|
|
431
|
+
const rules = [];
|
|
432
|
+
const seen = new Set();
|
|
433
|
+
const addRule = (source, destination) => {
|
|
434
|
+
const s = source.trim();
|
|
435
|
+
const d = destination.trim();
|
|
436
|
+
if (!s || !d)
|
|
437
|
+
return;
|
|
438
|
+
const key = `${s}->${d}`;
|
|
439
|
+
if (!seen.has(key)) {
|
|
440
|
+
seen.add(key);
|
|
441
|
+
rules.push({ source: s, destination: d, ...(filePath ? { filePath } : {}) });
|
|
442
|
+
}
|
|
443
|
+
};
|
|
444
|
+
const rewritePairRe = /source\s*:\s*['"`]([^'"`]+)['"`]\s*,\s*destination\s*:\s*['"`]([^'"`]+)['"`]/g;
|
|
445
|
+
let m;
|
|
446
|
+
while ((m = rewritePairRe.exec(text)) !== null) {
|
|
447
|
+
addRule(m[1], m[2]);
|
|
448
|
+
}
|
|
449
|
+
const proxyTargetRe = /['"`](\/[^'"`]+)['"`]\s*:\s*(?:\{[^}]*target\s*:\s*['"`]([^'"`]+)['"`]|['"`](https?:\/\/[^'"`]+)['"`])/g;
|
|
450
|
+
while ((m = proxyTargetRe.exec(text)) !== null) {
|
|
451
|
+
addRule(m[1], m[2] ?? m[3]);
|
|
452
|
+
}
|
|
453
|
+
if (rules.length === 0 && /\b(?:rewrites|proxies|proxy)\b/i.test(text)) {
|
|
454
|
+
const pathMatch = text.match(/['"`](\/[A-Za-z0-9_/:*-]+)['"`]/);
|
|
455
|
+
const destMatch = text.match(/['"`](https?:\/\/[^'"`]+)['"`]/);
|
|
456
|
+
if (pathMatch) {
|
|
457
|
+
addRule(pathMatch[1], destMatch ? destMatch[1] : "backend");
|
|
458
|
+
}
|
|
459
|
+
}
|
|
460
|
+
return rules;
|
|
461
|
+
}
|
|
462
|
+
function parseServerEndpointMethodAndPath(node) {
|
|
463
|
+
const meta = parseNodeMeta(node);
|
|
464
|
+
const ev = getPrimaryEvidence(node);
|
|
465
|
+
const expressMatch = node.name.match(/^(?:Express Route|HTTP Endpoint|API Endpoint|Route):\s*(GET|POST|PUT|DELETE|PATCH|HEAD|OPTIONS|ALL)?\s*(\/.*)$/i);
|
|
466
|
+
if (expressMatch) {
|
|
467
|
+
const method = (expressMatch[1] ?? meta.method ?? "ANY").toUpperCase();
|
|
468
|
+
const norm = normalizeUrlToPathname(expressMatch[2]);
|
|
469
|
+
if (norm)
|
|
470
|
+
return { method, declaredPath: norm };
|
|
471
|
+
}
|
|
472
|
+
if (typeof meta.routePath === "string" && meta.routePath.trim()) {
|
|
473
|
+
const norm = normalizeUrlToPathname(meta.routePath);
|
|
474
|
+
if (norm) {
|
|
475
|
+
const method = typeof meta.method === "string"
|
|
476
|
+
? meta.method.toUpperCase()
|
|
477
|
+
: node.name.match(/\b(GET|POST|PUT|DELETE|PATCH|HEAD|OPTIONS|ALL)\b/i)?.[1]?.toUpperCase() ??
|
|
478
|
+
"ANY";
|
|
479
|
+
return { method, declaredPath: norm };
|
|
480
|
+
}
|
|
481
|
+
}
|
|
482
|
+
const nextRouteHandlerMatch = node.name.match(/^Route Handler:\s*(GET|POST|PUT|DELETE|PATCH|HEAD|OPTIONS|ALL)\b/i);
|
|
483
|
+
if (nextRouteHandlerMatch && ev.filePath) {
|
|
484
|
+
const method = nextRouteHandlerMatch[1].toUpperCase();
|
|
485
|
+
const normFp = ev.filePath.replace(/\\/g, "/");
|
|
486
|
+
const afterApp = normFp.replace(/^.*?app\//, "");
|
|
487
|
+
const withoutRoute = afterApp
|
|
488
|
+
.replace(/\/?route(?:\.[A-Za-z0-9]+)+$/, "")
|
|
489
|
+
.replace(/\([^)]+\)\//g, "")
|
|
490
|
+
.replace(/\([^)]+\)$/, "");
|
|
491
|
+
const routePath = !withoutRoute || withoutRoute === "/"
|
|
492
|
+
? "/"
|
|
493
|
+
: `/${withoutRoute.replace(/^\/+|\/+$/g, "")}`;
|
|
494
|
+
return { method, declaredPath: routePath };
|
|
495
|
+
}
|
|
496
|
+
const stripped = cleanNodeLabel(node.name);
|
|
497
|
+
const bareMatch = stripped.match(/^(?:(GET|POST|PUT|DELETE|PATCH|HEAD|OPTIONS|ALL)\s+)?(\/.*)$/i);
|
|
498
|
+
if (bareMatch) {
|
|
499
|
+
const method = (bareMatch[1] ?? "ANY").toUpperCase();
|
|
500
|
+
const norm = normalizeUrlToPathname(bareMatch[2]);
|
|
501
|
+
if (norm)
|
|
502
|
+
return { method, declaredPath: norm };
|
|
503
|
+
}
|
|
504
|
+
return null;
|
|
505
|
+
}
|
|
506
|
+
/**
|
|
507
|
+
* Correlates unstitched client HTTP egress (`OPEN_CONNECTOR` `HTTP_FETCH` nodes with `0` outgoing
|
|
508
|
+
* `REQUESTS` edges, parameterized wrapper URLs like `/api:param`, `axios.create({ baseURL })`, and
|
|
509
|
+
* `next.config.*` `rewrites`/`proxies`) against uncalled server `HTTP_ENDPOINT` ingress contracts
|
|
510
|
+
* (`inDegree === 0` and `app.use('/api/...', router)` mount prefixes) across packages to report
|
|
511
|
+
* candidate protocol bridges (`UNSTITCHED_PROTOCOL_SEAM`, `[PAT-MCP-08]`, `[PAT-MCP-09]`).
|
|
512
|
+
*/
|
|
513
|
+
function detectUnstitchedProtocolSeams(graph, index, options) {
|
|
514
|
+
const pkgFilter = options?.packageName?.trim();
|
|
515
|
+
const clientBuckets = new Map();
|
|
516
|
+
const ensureClientBucket = (pkg) => {
|
|
517
|
+
let b = clientBuckets.get(pkg);
|
|
518
|
+
if (!b) {
|
|
519
|
+
b = {
|
|
520
|
+
pkg,
|
|
521
|
+
connectors: [],
|
|
522
|
+
wrappers: new Map(),
|
|
523
|
+
urlPatterns: new Set(),
|
|
524
|
+
baseUrls: new Set(),
|
|
525
|
+
proxyRewrites: [],
|
|
526
|
+
};
|
|
527
|
+
clientBuckets.set(pkg, b);
|
|
528
|
+
}
|
|
529
|
+
return b;
|
|
530
|
+
};
|
|
531
|
+
// 1. Find unstitched HTTP_FETCH / HTTP_REQUEST OPEN_CONNECTOR nodes (0 outgoing REQUESTS/flow edges)
|
|
532
|
+
for (const node of graph.nodes) {
|
|
533
|
+
if ((node.scope ?? "USER") !== "USER")
|
|
534
|
+
continue;
|
|
535
|
+
if (node.type !== "OPEN_CONNECTOR")
|
|
536
|
+
continue;
|
|
537
|
+
if (node.entityType !== "HTTP_FETCH" &&
|
|
538
|
+
node.entityType !== "HTTP_REQUEST" &&
|
|
539
|
+
node.patternId !== "open-connector.http-call") {
|
|
540
|
+
continue;
|
|
541
|
+
}
|
|
542
|
+
const outEdges = index.outEdgesBySource.get(node.id) ?? [];
|
|
543
|
+
const hasOutgoingRequests = outEdges.some((e) => e.entityType === "REQUESTS" ||
|
|
544
|
+
(Boolean(e.targetId) && FLOW_EDGE_ENTITY_TYPES.has(e.entityType)));
|
|
545
|
+
if (hasOutgoingRequests)
|
|
546
|
+
continue;
|
|
547
|
+
const inEdges = index.inEdgesByTarget.get(node.id) ?? [];
|
|
548
|
+
let pkg = index.resolveNodePkg(node.id);
|
|
549
|
+
if (!pkg) {
|
|
550
|
+
for (const e of inEdges) {
|
|
551
|
+
const callerPkg = index.resolveNodePkg(e.sourceId);
|
|
552
|
+
if (callerPkg) {
|
|
553
|
+
pkg = callerPkg;
|
|
554
|
+
break;
|
|
555
|
+
}
|
|
556
|
+
}
|
|
557
|
+
}
|
|
558
|
+
if (!pkg)
|
|
559
|
+
continue;
|
|
560
|
+
const bucket = ensureClientBucket(pkg);
|
|
561
|
+
bucket.connectors.push(node);
|
|
562
|
+
const meta = parseNodeMeta(node);
|
|
563
|
+
if (typeof meta.urlPath === "string" && meta.urlPath.trim()) {
|
|
564
|
+
bucket.urlPatterns.add(meta.urlPath.trim());
|
|
565
|
+
}
|
|
566
|
+
if (typeof meta.baseURL === "string" && meta.baseURL.trim()) {
|
|
567
|
+
bucket.baseUrls.add(meta.baseURL.trim());
|
|
568
|
+
}
|
|
569
|
+
if (Array.isArray(meta.payload)) {
|
|
570
|
+
for (const rawArg of meta.payload) {
|
|
571
|
+
if (typeof rawArg !== "string")
|
|
572
|
+
continue;
|
|
573
|
+
const baseMatch = rawArg.match(/baseURL\s*:\s*(?:['"]([^'"]+)['"]|`([^`]+)`)/i);
|
|
574
|
+
if (baseMatch) {
|
|
575
|
+
bucket.baseUrls.add((baseMatch[1] ?? baseMatch[2]).trim());
|
|
576
|
+
}
|
|
577
|
+
const pathLitMatch = rawArg.match(/['"`](\/[^'"`]+)['"`]/);
|
|
578
|
+
if (pathLitMatch && !baseMatch) {
|
|
579
|
+
const norm = normalizeUrlToPathname(pathLitMatch[1]);
|
|
580
|
+
if (norm)
|
|
581
|
+
bucket.urlPatterns.add(norm);
|
|
582
|
+
}
|
|
583
|
+
}
|
|
584
|
+
}
|
|
585
|
+
for (const ev of getAllEvidenceRecords(node)) {
|
|
586
|
+
const snip = ev.snippet ?? "";
|
|
587
|
+
const baseMatch = snip.match(/baseURL\s*:\s*(?:['"]([^'"]+)['"]|`([^`]+)`)/i);
|
|
588
|
+
if (baseMatch) {
|
|
589
|
+
bucket.baseUrls.add((baseMatch[1] ?? baseMatch[2]).trim());
|
|
590
|
+
}
|
|
591
|
+
const tmplMatch = snip.match(/`(\/[^`]+)`|['"](\/[^'"]+)['"]/);
|
|
592
|
+
if (tmplMatch && !baseMatch) {
|
|
593
|
+
const rawUrl = tmplMatch[1] ?? tmplMatch[2];
|
|
594
|
+
const norm = normalizeUrlToPathname(rawUrl);
|
|
595
|
+
if (norm)
|
|
596
|
+
bucket.urlPatterns.add(norm);
|
|
597
|
+
}
|
|
598
|
+
}
|
|
599
|
+
for (const e of inEdges) {
|
|
600
|
+
const edgeMeta = e.metadata && typeof e.metadata === "object"
|
|
601
|
+
? e.metadata
|
|
602
|
+
: undefined;
|
|
603
|
+
if (typeof edgeMeta?.urlPath === "string" && edgeMeta.urlPath.trim()) {
|
|
604
|
+
bucket.urlPatterns.add(edgeMeta.urlPath.trim());
|
|
605
|
+
}
|
|
606
|
+
if (typeof edgeMeta?.baseURL === "string" && edgeMeta.baseURL.trim()) {
|
|
607
|
+
bucket.baseUrls.add(edgeMeta.baseURL.trim());
|
|
608
|
+
}
|
|
609
|
+
for (const ev of getAllEvidenceRecords(e)) {
|
|
610
|
+
const snip = ev.snippet ?? "";
|
|
611
|
+
const baseMatch = snip.match(/baseURL\s*:\s*(?:['"]([^'"]+)['"]|`([^`]+)`)/i);
|
|
612
|
+
if (baseMatch) {
|
|
613
|
+
bucket.baseUrls.add((baseMatch[1] ?? baseMatch[2]).trim());
|
|
614
|
+
}
|
|
615
|
+
const tmplMatch = snip.match(/`(\/[^`]+)`|['"](\/[^'"]+)['"]/);
|
|
616
|
+
if (tmplMatch && !baseMatch) {
|
|
617
|
+
const norm = normalizeUrlToPathname(tmplMatch[1] ?? tmplMatch[2]);
|
|
618
|
+
if (norm)
|
|
619
|
+
bucket.urlPatterns.add(norm);
|
|
620
|
+
}
|
|
621
|
+
}
|
|
622
|
+
const caller = index.nodeById.get(e.sourceId);
|
|
623
|
+
if (caller && caller.type === "CONTRACT" && !isHiddenNode(caller)) {
|
|
624
|
+
bucket.wrappers.set(caller.id, caller);
|
|
625
|
+
}
|
|
626
|
+
else if (caller && caller.entityType === INIT_BLOCK_ENTITY_TYPE) {
|
|
627
|
+
const evFp = getPrimaryEvidence(e).filePath ?? getPrimaryEvidence(node).filePath;
|
|
628
|
+
let foundFileContract = false;
|
|
629
|
+
if (evFp) {
|
|
630
|
+
for (const cand of graph.nodes) {
|
|
631
|
+
if (cand.type === "CONTRACT" &&
|
|
632
|
+
!NON_EXECUTABLE_CONTRACT_ENTITY_TYPES.has(cand.entityType) &&
|
|
633
|
+
getPrimaryEvidence(cand).filePath === evFp) {
|
|
634
|
+
bucket.wrappers.set(cand.id, cand);
|
|
635
|
+
foundFileContract = true;
|
|
636
|
+
}
|
|
637
|
+
}
|
|
638
|
+
}
|
|
639
|
+
if (!foundFileContract) {
|
|
640
|
+
bucket.wrappers.set(caller.id, caller);
|
|
641
|
+
}
|
|
642
|
+
}
|
|
643
|
+
}
|
|
644
|
+
if (bucket.wrappers.size === 0) {
|
|
645
|
+
const connFp = getPrimaryEvidence(node).filePath;
|
|
646
|
+
if (connFp) {
|
|
647
|
+
for (const cand of graph.nodes) {
|
|
648
|
+
if (cand.type === "CONTRACT" &&
|
|
649
|
+
!NON_EXECUTABLE_CONTRACT_ENTITY_TYPES.has(cand.entityType) &&
|
|
650
|
+
getPrimaryEvidence(cand).filePath === connFp) {
|
|
651
|
+
bucket.wrappers.set(cand.id, cand);
|
|
652
|
+
}
|
|
653
|
+
}
|
|
654
|
+
}
|
|
655
|
+
}
|
|
656
|
+
}
|
|
657
|
+
if (clientBuckets.size === 0)
|
|
658
|
+
return [];
|
|
659
|
+
// 2. Enrich client buckets with package-level axios.create({ baseURL }) and next.config.* rewrites/proxies
|
|
660
|
+
for (const [clientPkg, bucket] of clientBuckets.entries()) {
|
|
661
|
+
const addRewrite = (rule) => {
|
|
662
|
+
if (!bucket.proxyRewrites.some((r) => r.source === rule.source && r.destination === rule.destination)) {
|
|
663
|
+
bucket.proxyRewrites.push(rule);
|
|
664
|
+
}
|
|
665
|
+
};
|
|
666
|
+
for (const n of graph.nodes) {
|
|
667
|
+
const nPkg = index.resolveNodePkg(n.id);
|
|
668
|
+
const ev = getPrimaryEvidence(n);
|
|
669
|
+
const isConfigNode = ev.filePath &&
|
|
670
|
+
/(?:^|\/)(?:next|vite)\.config\.[A-Za-z0-9]+$/i.test(ev.filePath);
|
|
671
|
+
if (nPkg !== clientPkg && !(isConfigNode && (!nPkg || nPkg === "root"))) {
|
|
672
|
+
continue;
|
|
673
|
+
}
|
|
674
|
+
const meta = parseNodeMeta(n);
|
|
675
|
+
if (typeof meta.baseURL === "string" && meta.baseURL.trim()) {
|
|
676
|
+
bucket.baseUrls.add(meta.baseURL.trim());
|
|
677
|
+
}
|
|
678
|
+
for (const rwArr of [meta.rewrites, meta.proxies, meta.proxyRewrites]) {
|
|
679
|
+
if (Array.isArray(rwArr)) {
|
|
680
|
+
for (const r of rwArr) {
|
|
681
|
+
if (r && typeof r.source === "string" && typeof r.destination === "string") {
|
|
682
|
+
addRewrite({
|
|
683
|
+
source: r.source,
|
|
684
|
+
destination: r.destination,
|
|
685
|
+
filePath: r.filePath ?? r.configFilePath ?? ev.filePath,
|
|
686
|
+
});
|
|
687
|
+
}
|
|
688
|
+
}
|
|
689
|
+
}
|
|
690
|
+
}
|
|
691
|
+
if (meta.proxy && typeof meta.proxy === "object" && !Array.isArray(meta.proxy)) {
|
|
692
|
+
for (const [src, target] of Object.entries(meta.proxy)) {
|
|
693
|
+
const dest = typeof target === "string"
|
|
694
|
+
? target
|
|
695
|
+
: typeof target?.target === "string"
|
|
696
|
+
? target.target
|
|
697
|
+
: "";
|
|
698
|
+
if (dest)
|
|
699
|
+
addRewrite({ source: src, destination: dest, filePath: ev.filePath });
|
|
700
|
+
}
|
|
701
|
+
}
|
|
702
|
+
for (const rec of getAllEvidenceRecords(n)) {
|
|
703
|
+
const snip = rec.snippet ?? "";
|
|
704
|
+
const baseMatch = snip.match(/baseURL\s*:\s*(?:['"]([^'"]+)['"]|`([^`]+)`)/i);
|
|
705
|
+
if (baseMatch) {
|
|
706
|
+
bucket.baseUrls.add((baseMatch[1] ?? baseMatch[2]).trim());
|
|
707
|
+
}
|
|
708
|
+
if ((rec.filePath &&
|
|
709
|
+
/(?:^|\/)(?:next|vite)\.config\.[A-Za-z0-9]+$/i.test(rec.filePath)) ||
|
|
710
|
+
/\b(?:rewrites|proxies|proxy)\b/i.test(n.name) ||
|
|
711
|
+
/\b(?:rewrites|destination)\b/i.test(snip)) {
|
|
712
|
+
for (const rule of extractRewriteRulesFromText(snip, rec.filePath)) {
|
|
713
|
+
addRewrite(rule);
|
|
714
|
+
}
|
|
715
|
+
}
|
|
716
|
+
}
|
|
717
|
+
}
|
|
718
|
+
// Check next.config.* on disk when repoPath is provided
|
|
719
|
+
if (options?.repoPath) {
|
|
720
|
+
const pkgPrefix = index.pathPrefixByPkg.get(clientPkg);
|
|
721
|
+
const candidateDirs = [
|
|
722
|
+
...(pkgPrefix ? [resolve(options.repoPath, pkgPrefix)] : []),
|
|
723
|
+
resolve(options.repoPath),
|
|
724
|
+
];
|
|
725
|
+
const configNames = [
|
|
726
|
+
"next.config.ts",
|
|
727
|
+
"next.config.mjs",
|
|
728
|
+
"next.config.js",
|
|
729
|
+
"next.config.cjs",
|
|
730
|
+
"vite.config.ts",
|
|
731
|
+
"vite.config.js",
|
|
732
|
+
];
|
|
733
|
+
for (const dir of candidateDirs) {
|
|
734
|
+
for (const cfgName of configNames) {
|
|
735
|
+
const absCfg = resolve(dir, cfgName);
|
|
736
|
+
if (existsSync(absCfg)) {
|
|
737
|
+
try {
|
|
738
|
+
const content = readFileSync(absCfg, "utf8");
|
|
739
|
+
const relCfg = pkgPrefix ? `${pkgPrefix}/${cfgName}` : cfgName;
|
|
740
|
+
for (const rule of extractRewriteRulesFromText(content, relCfg)) {
|
|
741
|
+
addRewrite(rule);
|
|
742
|
+
}
|
|
743
|
+
}
|
|
744
|
+
catch {
|
|
745
|
+
// ignore unreadable config
|
|
746
|
+
}
|
|
747
|
+
}
|
|
748
|
+
}
|
|
749
|
+
}
|
|
750
|
+
}
|
|
751
|
+
}
|
|
752
|
+
const mountsByServerPkg = new Map();
|
|
753
|
+
const recordServerMount = (pkg, entry) => {
|
|
754
|
+
if (!pkg || !entry.prefix.startsWith("/"))
|
|
755
|
+
return;
|
|
756
|
+
let list = mountsByServerPkg.get(pkg);
|
|
757
|
+
if (!list) {
|
|
758
|
+
list = [];
|
|
759
|
+
mountsByServerPkg.set(pkg, list);
|
|
760
|
+
}
|
|
761
|
+
if (!list.some((m) => m.prefix === entry.prefix && m.targetHint === entry.targetHint)) {
|
|
762
|
+
list.push(entry);
|
|
763
|
+
}
|
|
764
|
+
};
|
|
765
|
+
for (const edge of graph.edges) {
|
|
766
|
+
if ((edge.scope ?? "USER") !== "USER")
|
|
767
|
+
continue;
|
|
768
|
+
const pkg = index.resolveNodePkg(edge.sourceId) ||
|
|
769
|
+
(edge.targetId ? index.resolveNodePkg(edge.targetId) : "");
|
|
770
|
+
if (!pkg)
|
|
771
|
+
continue;
|
|
772
|
+
const mountMatch = edge.name.match(/^Express Mount:\s*(\/[^\s]*)\s*->\s*(.+)$/i);
|
|
773
|
+
if (mountMatch) {
|
|
774
|
+
const prefix = normalizeUrlToPathname(mountMatch[1]);
|
|
775
|
+
const targetHint = mountMatch[2].trim();
|
|
776
|
+
if (prefix) {
|
|
777
|
+
recordServerMount(pkg, {
|
|
778
|
+
prefix,
|
|
779
|
+
targetHint,
|
|
780
|
+
targetNodeId: edge.targetId,
|
|
781
|
+
filePath: getPrimaryEvidence(edge).filePath,
|
|
782
|
+
});
|
|
783
|
+
}
|
|
784
|
+
}
|
|
785
|
+
for (const ev of getAllEvidenceRecords(edge)) {
|
|
786
|
+
const snip = ev.snippet ?? "";
|
|
787
|
+
const useRe = /\b(?:app|router|server)\.use\(\s*['"`](\/[^'"`]+)['"`](?:\s*,\s*([^)]+))?\)/g;
|
|
788
|
+
let m;
|
|
789
|
+
while ((m = useRe.exec(snip)) !== null) {
|
|
790
|
+
const prefix = normalizeUrlToPathname(m[1]);
|
|
791
|
+
if (prefix) {
|
|
792
|
+
recordServerMount(pkg, {
|
|
793
|
+
prefix,
|
|
794
|
+
targetHint: (m[2] ?? "router").trim(),
|
|
795
|
+
targetNodeId: edge.targetId,
|
|
796
|
+
filePath: ev.filePath,
|
|
797
|
+
});
|
|
798
|
+
}
|
|
799
|
+
}
|
|
800
|
+
}
|
|
801
|
+
}
|
|
802
|
+
for (const node of graph.nodes) {
|
|
803
|
+
if ((node.scope ?? "USER") !== "USER")
|
|
804
|
+
continue;
|
|
805
|
+
const pkg = index.resolveNodePkg(node.id);
|
|
806
|
+
if (!pkg)
|
|
807
|
+
continue;
|
|
808
|
+
const meta = parseNodeMeta(node);
|
|
809
|
+
if (typeof meta.mountPrefix === "string" && meta.mountPrefix.startsWith("/")) {
|
|
810
|
+
const prefix = normalizeUrlToPathname(meta.mountPrefix);
|
|
811
|
+
if (prefix) {
|
|
812
|
+
recordServerMount(pkg, {
|
|
813
|
+
prefix,
|
|
814
|
+
targetHint: cleanNodeLabel(node.name),
|
|
815
|
+
targetNodeId: node.id,
|
|
816
|
+
filePath: getPrimaryEvidence(node).filePath,
|
|
817
|
+
});
|
|
818
|
+
}
|
|
819
|
+
}
|
|
820
|
+
for (const ev of getAllEvidenceRecords(node)) {
|
|
821
|
+
const snip = ev.snippet ?? "";
|
|
822
|
+
const useRe = /\b(?:app|router|server)\.use\(\s*['"`](\/[^'"`]+)['"`](?:\s*,\s*([^)]+))?\)/g;
|
|
823
|
+
let m;
|
|
824
|
+
while ((m = useRe.exec(snip)) !== null) {
|
|
825
|
+
const prefix = normalizeUrlToPathname(m[1]);
|
|
826
|
+
if (prefix) {
|
|
827
|
+
recordServerMount(pkg, {
|
|
828
|
+
prefix,
|
|
829
|
+
targetHint: (m[2] ?? "router").trim(),
|
|
830
|
+
targetNodeId: node.id,
|
|
831
|
+
filePath: ev.filePath,
|
|
832
|
+
});
|
|
833
|
+
}
|
|
834
|
+
}
|
|
835
|
+
}
|
|
836
|
+
}
|
|
837
|
+
const uncalledRoutesByServerPkg = new Map();
|
|
838
|
+
for (const node of graph.nodes) {
|
|
839
|
+
if ((node.scope ?? "USER") !== "USER")
|
|
840
|
+
continue;
|
|
841
|
+
if (node.type !== "CONTRACT")
|
|
842
|
+
continue;
|
|
843
|
+
if (node.entityType !== "HTTP_ENDPOINT" &&
|
|
844
|
+
node.entityType !== "API_ENDPOINT") {
|
|
845
|
+
continue;
|
|
846
|
+
}
|
|
847
|
+
if (NON_HTTP_ROUTE_PATTERN_IDS.has(node.patternId))
|
|
848
|
+
continue;
|
|
849
|
+
// Must be uncalled (inDegree === 0 from HTTP / call invocation edges)
|
|
850
|
+
const inEdges = index.inEdgesByTarget.get(node.id) ?? [];
|
|
851
|
+
const isCalled = inEdges.some((e) => HTTP_INVOCATION_EDGE_TYPES.has(e.entityType) &&
|
|
852
|
+
e.sourceId !== node.id);
|
|
853
|
+
if (isCalled)
|
|
854
|
+
continue;
|
|
855
|
+
const serverPkg = index.resolveNodePkg(node.id);
|
|
856
|
+
if (!serverPkg)
|
|
857
|
+
continue;
|
|
858
|
+
const parsed = parseServerEndpointMethodAndPath(node);
|
|
859
|
+
if (!parsed)
|
|
860
|
+
continue;
|
|
861
|
+
const pkgMounts = mountsByServerPkg.get(serverPkg) ?? [];
|
|
862
|
+
const nodeEv = getPrimaryEvidence(node);
|
|
863
|
+
const nodeFileStem = nodeEv.filePath
|
|
864
|
+
? (nodeEv.filePath.split("/").pop() ?? "").replace(/\.[A-Za-z0-9]+$/, "").toLowerCase()
|
|
865
|
+
: "";
|
|
866
|
+
let matchedMountPrefix;
|
|
867
|
+
const meta = parseNodeMeta(node);
|
|
868
|
+
if (typeof meta.mountPrefix === "string" && meta.mountPrefix.startsWith("/")) {
|
|
869
|
+
matchedMountPrefix = normalizeUrlToPathname(meta.mountPrefix) ?? undefined;
|
|
870
|
+
}
|
|
871
|
+
if (!matchedMountPrefix && pkgMounts.length > 0) {
|
|
872
|
+
const specificMount = pkgMounts.find((m) => {
|
|
873
|
+
if (m.targetNodeId === node.id)
|
|
874
|
+
return true;
|
|
875
|
+
if (m.targetNodeId) {
|
|
876
|
+
const tNode = index.nodeById.get(m.targetNodeId);
|
|
877
|
+
const tFp = tNode ? getPrimaryEvidence(tNode).filePath : undefined;
|
|
878
|
+
if (tFp && nodeEv.filePath && tFp === nodeEv.filePath)
|
|
879
|
+
return true;
|
|
880
|
+
}
|
|
881
|
+
if (nodeFileStem && nodeFileStem !== "index" && nodeFileStem !== "routes") {
|
|
882
|
+
const hintLower = m.targetHint.toLowerCase();
|
|
883
|
+
return hintLower.includes(nodeFileStem);
|
|
884
|
+
}
|
|
885
|
+
return false;
|
|
886
|
+
});
|
|
887
|
+
if (specificMount) {
|
|
888
|
+
matchedMountPrefix = specificMount.prefix;
|
|
889
|
+
}
|
|
890
|
+
else if (!parsed.declaredPath.startsWith(pkgMounts[0].prefix) ||
|
|
891
|
+
parsed.declaredPath === "/") {
|
|
892
|
+
matchedMountPrefix = pkgMounts[0].prefix;
|
|
893
|
+
}
|
|
894
|
+
}
|
|
895
|
+
const effectivePath = matchedMountPrefix
|
|
896
|
+
? joinMountAndRoute(matchedMountPrefix, parsed.declaredPath)
|
|
897
|
+
: parsed.declaredPath;
|
|
898
|
+
let list = uncalledRoutesByServerPkg.get(serverPkg);
|
|
899
|
+
if (!list) {
|
|
900
|
+
list = [];
|
|
901
|
+
uncalledRoutesByServerPkg.set(serverPkg, list);
|
|
902
|
+
}
|
|
903
|
+
list.push({
|
|
904
|
+
node: toNodeSummaryRef(node, index.resolveNodePkg),
|
|
905
|
+
method: parsed.method,
|
|
906
|
+
httpMethod: parsed.method,
|
|
907
|
+
declaredPath: parsed.declaredPath,
|
|
908
|
+
effectivePath,
|
|
909
|
+
...(matchedMountPrefix ? { mountPrefix: matchedMountPrefix } : {}),
|
|
910
|
+
});
|
|
911
|
+
}
|
|
912
|
+
// 4. Correlate Client Buckets with Server Uncalled Routes across packages
|
|
913
|
+
const seams = [];
|
|
914
|
+
for (const [clientPkg, bucket] of clientBuckets.entries()) {
|
|
915
|
+
for (const [serverPkg, serverRoutes] of uncalledRoutesByServerPkg.entries()) {
|
|
916
|
+
if (clientPkg === serverPkg)
|
|
917
|
+
continue;
|
|
918
|
+
if (pkgFilter &&
|
|
919
|
+
!packageMatchesFilter(clientPkg, index.pathPrefixByPkg.get(clientPkg), pkgFilter) &&
|
|
920
|
+
!packageMatchesFilter(serverPkg, index.pathPrefixByPkg.get(serverPkg), pkgFilter)) {
|
|
921
|
+
continue;
|
|
922
|
+
}
|
|
923
|
+
const basePrefixes = [...bucket.baseUrls]
|
|
924
|
+
.map((b) => extractStaticRoutePrefix(b))
|
|
925
|
+
.filter((p) => Boolean(p));
|
|
926
|
+
const rewritePrefixes = [];
|
|
927
|
+
for (const rw of bucket.proxyRewrites) {
|
|
928
|
+
const srcPrefix = extractStaticRoutePrefix(rw.source);
|
|
929
|
+
if (srcPrefix)
|
|
930
|
+
rewritePrefixes.push(srcPrefix);
|
|
931
|
+
const dstPrefix = extractStaticRoutePrefix(rw.destination);
|
|
932
|
+
if (dstPrefix)
|
|
933
|
+
rewritePrefixes.push(dstPrefix);
|
|
934
|
+
}
|
|
935
|
+
const candidatePrefixes = new Set([
|
|
936
|
+
...basePrefixes,
|
|
937
|
+
...rewritePrefixes,
|
|
938
|
+
]);
|
|
939
|
+
const candidateCanonicalPaths = new Set();
|
|
940
|
+
for (const pat of bucket.urlPatterns) {
|
|
941
|
+
const pref = extractStaticRoutePrefix(pat);
|
|
942
|
+
if (pref && pref !== "/")
|
|
943
|
+
candidatePrefixes.add(pref);
|
|
944
|
+
const canon = canonicalizeRoutePattern(pat);
|
|
945
|
+
if (canon) {
|
|
946
|
+
candidateCanonicalPaths.add(canon);
|
|
947
|
+
for (const bp of basePrefixes) {
|
|
948
|
+
const joined = canonicalizeRoutePattern(joinMountAndRoute(bp, pat));
|
|
949
|
+
if (joined)
|
|
950
|
+
candidateCanonicalPaths.add(joined);
|
|
951
|
+
}
|
|
952
|
+
}
|
|
953
|
+
}
|
|
954
|
+
const matchedRoutes = serverRoutes.filter((route) => {
|
|
955
|
+
const canonEffective = canonicalizeRoutePattern(route.effectivePath);
|
|
956
|
+
const canonDeclared = canonicalizeRoutePattern(route.declaredPath);
|
|
957
|
+
if (canonEffective && candidateCanonicalPaths.has(canonEffective)) {
|
|
958
|
+
return true;
|
|
959
|
+
}
|
|
960
|
+
if (canonDeclared && candidateCanonicalPaths.has(canonDeclared)) {
|
|
961
|
+
return true;
|
|
962
|
+
}
|
|
963
|
+
for (const prefix of candidatePrefixes) {
|
|
964
|
+
if (prefix === "/")
|
|
965
|
+
continue;
|
|
966
|
+
if (route.effectivePath === prefix ||
|
|
967
|
+
route.effectivePath.startsWith(`${prefix}/`) ||
|
|
968
|
+
route.declaredPath === prefix ||
|
|
969
|
+
route.declaredPath.startsWith(`${prefix}/`) ||
|
|
970
|
+
route.mountPrefix === prefix ||
|
|
971
|
+
(route.mountPrefix && route.mountPrefix.startsWith(`${prefix}/`))) {
|
|
972
|
+
return true;
|
|
973
|
+
}
|
|
974
|
+
}
|
|
975
|
+
return false;
|
|
976
|
+
});
|
|
977
|
+
const hasGenericDynamicClient = bucket.urlPatterns.size === 0 ||
|
|
978
|
+
[...bucket.urlPatterns].some((p) => p === ":param" || p === "/:param") ||
|
|
979
|
+
bucket.baseUrls.size > 0 ||
|
|
980
|
+
bucket.proxyRewrites.length > 0;
|
|
981
|
+
const finalRoutes = matchedRoutes.length > 0
|
|
982
|
+
? matchedRoutes
|
|
983
|
+
: hasGenericDynamicClient
|
|
984
|
+
? serverRoutes
|
|
985
|
+
: [];
|
|
986
|
+
if (finalRoutes.length === 0)
|
|
987
|
+
continue;
|
|
988
|
+
// Sort connectors so request connectors (`fetch`, `api.get`) precede factory `axios.create`
|
|
989
|
+
const sortedConnectors = [...bucket.connectors].sort((a, b) => {
|
|
990
|
+
const aIsCreate = /create$/i.test(a.name) ? 1 : 0;
|
|
991
|
+
const bIsCreate = /create$/i.test(b.name) ? 1 : 0;
|
|
992
|
+
return aIsCreate - bIsCreate;
|
|
993
|
+
});
|
|
994
|
+
const connectorRefs = sortedConnectors.map((c) => toNodeSummaryRef(c, index.resolveNodePkg));
|
|
995
|
+
const primaryConnector = connectorRefs[0];
|
|
996
|
+
const wrapperRefs = [...bucket.wrappers.values()].map((w) => toNodeSummaryRef(w, index.resolveNodePkg));
|
|
997
|
+
const primaryWrapper = wrapperRefs[0];
|
|
998
|
+
const serverMountPrefixes = [
|
|
999
|
+
...new Set([
|
|
1000
|
+
...(mountsByServerPkg.get(serverPkg)?.map((m) => m.prefix) ?? []),
|
|
1001
|
+
...finalRoutes
|
|
1002
|
+
.map((r) => r.mountPrefix)
|
|
1003
|
+
.filter((m) => Boolean(m)),
|
|
1004
|
+
]),
|
|
1005
|
+
];
|
|
1006
|
+
const clientUrlPatterns = [...bucket.urlPatterns];
|
|
1007
|
+
const detectedClientBaseUrls = [...bucket.baseUrls];
|
|
1008
|
+
const detectedProxyRewrites = bucket.proxyRewrites;
|
|
1009
|
+
const clientCallerLabel = primaryWrapper
|
|
1010
|
+
? `${clientPkg}:${primaryWrapper.label}`
|
|
1011
|
+
: `${clientPkg}:${primaryConnector.label}`;
|
|
1012
|
+
const clientSignals = [];
|
|
1013
|
+
if (clientUrlPatterns.length > 0) {
|
|
1014
|
+
clientSignals.push(clientUrlPatterns.slice(0, 3).join(", "));
|
|
1015
|
+
}
|
|
1016
|
+
if (detectedClientBaseUrls.length > 0) {
|
|
1017
|
+
clientSignals.push(`baseURL: ${detectedClientBaseUrls.join(", ")}`);
|
|
1018
|
+
}
|
|
1019
|
+
if (detectedProxyRewrites.length > 0) {
|
|
1020
|
+
clientSignals.push(`rewrite: ${detectedProxyRewrites.map((r) => `${r.source} -> ${r.destination}`).join(", ")}`);
|
|
1021
|
+
}
|
|
1022
|
+
const clientSignalStr = clientSignals.length > 0 ? ` [${clientSignals.join(" | ")}]` : "";
|
|
1023
|
+
const routeLabels = finalRoutes
|
|
1024
|
+
.slice(0, 5)
|
|
1025
|
+
.map((r) => r.mountPrefix && r.effectivePath !== r.declaredPath
|
|
1026
|
+
? `${r.method} ${r.effectivePath} (declared ${r.declaredPath} under mount ${r.mountPrefix})`
|
|
1027
|
+
: `${r.method} ${r.effectivePath}`)
|
|
1028
|
+
.join(", ");
|
|
1029
|
+
const candidateBridge = `${clientCallerLabel}${clientSignalStr} <-> ${serverPkg}:${routeLabels}`;
|
|
1030
|
+
const description = `Unstitched HTTP protocol seam between '${clientPkg}' and '${serverPkg}': ` +
|
|
1031
|
+
`client HTTP egress '${primaryConnector.name}'${primaryWrapper ? ` (wrapped by '${primaryWrapper.label}')` : ""}${clientSignalStr} has 0 outgoing REQUESTS/stitched edges, ` +
|
|
1032
|
+
`while '${serverPkg}' exposes ${finalRoutes.length} uncalled HTTP_ENDPOINT ingress contract(s) (${routeLabels}) with inDegree === 0.`;
|
|
1033
|
+
const guidance = `Protocol Seam Opportunity ([PAT-MCP-09]): Candidate bridge ${candidateBridge}. ` +
|
|
1034
|
+
`To stitch '${clientPkg}' to '${serverPkg}' on the Chomp map, pass static or canonical parameterized route paths (e.g. '/api/...') directly to the HTTP client or declare a convention rule in chomp.config.json, then verify with chomp_get_diff.`;
|
|
1035
|
+
const detectedMechanisms = [];
|
|
1036
|
+
if (clientUrlPatterns.some((p) => p.includes(":param") || p.includes(":") || p.includes("${"))) {
|
|
1037
|
+
detectedMechanisms.push("parameterized-fetch-wrapper");
|
|
1038
|
+
}
|
|
1039
|
+
else if (clientUrlPatterns.length > 0) {
|
|
1040
|
+
detectedMechanisms.push("http-fetch-egress");
|
|
1041
|
+
}
|
|
1042
|
+
if (detectedClientBaseUrls.length > 0) {
|
|
1043
|
+
detectedMechanisms.push("axios-base-url");
|
|
1044
|
+
}
|
|
1045
|
+
if (serverMountPrefixes.length > 0) {
|
|
1046
|
+
detectedMechanisms.push("express-router-mount");
|
|
1047
|
+
}
|
|
1048
|
+
if (detectedProxyRewrites.length > 0) {
|
|
1049
|
+
detectedMechanisms.push("nextjs-rewrite-proxy");
|
|
1050
|
+
}
|
|
1051
|
+
seams.push({
|
|
1052
|
+
kind: "UNSTITCHED_PROTOCOL_SEAM",
|
|
1053
|
+
ruleId: "UNSTITCHED_PROTOCOL_SEAM",
|
|
1054
|
+
severity: "ADVISORY",
|
|
1055
|
+
clientPackage: clientPkg,
|
|
1056
|
+
serverPackage: serverPkg,
|
|
1057
|
+
clientConnector: primaryConnector,
|
|
1058
|
+
clientConnectors: connectorRefs,
|
|
1059
|
+
...(primaryWrapper ? { clientWrapper: primaryWrapper } : {}),
|
|
1060
|
+
clientWrappers: wrapperRefs,
|
|
1061
|
+
clientCallers: wrapperRefs,
|
|
1062
|
+
clientUrlPattern: clientUrlPatterns[0] ??
|
|
1063
|
+
detectedClientBaseUrls[0] ??
|
|
1064
|
+
detectedProxyRewrites[0]?.source ??
|
|
1065
|
+
"/",
|
|
1066
|
+
clientUrlPatterns,
|
|
1067
|
+
detectedClientBaseUrls,
|
|
1068
|
+
detectedProxyRewrites,
|
|
1069
|
+
detectedServerMountPrefixes: serverMountPrefixes,
|
|
1070
|
+
detectedMechanisms,
|
|
1071
|
+
serverRoutes: finalRoutes,
|
|
1072
|
+
uncalledServerRoutes: finalRoutes,
|
|
1073
|
+
candidateServerRoutes: finalRoutes,
|
|
1074
|
+
candidateBridge,
|
|
1075
|
+
description,
|
|
1076
|
+
agentReadinessOpportunity: guidance,
|
|
1077
|
+
agentReadinessGuidance: guidance,
|
|
1078
|
+
});
|
|
1079
|
+
}
|
|
1080
|
+
}
|
|
1081
|
+
return seams;
|
|
1082
|
+
}
|
|
1083
|
+
/**
|
|
1084
|
+
* Flags when a package's `Init: <pkg>` boundary owns the majority of `OPEN_CONNECTOR` edges
|
|
1085
|
+
* (`DB_QUERY`, `HTTP_FETCH`) while its `HTTP_ENDPOINT` / `EXPORTED_MODULE` contracts are dead-end
|
|
1086
|
+
* ingress (`resolvedOutDegree === 0`), pinpointing the exact files where contract scope ownership
|
|
1087
|
+
* failed to propagate (`INIT_BLOCK_CONNECTOR_LEAK`, `[PAT-MCP-08]`, `[PAT-MCP-09]`, `[PAT-VIS-15]`).
|
|
1088
|
+
*/
|
|
1089
|
+
function detectInitBlockConnectorLeaks(graph, index, options) {
|
|
1090
|
+
const pkgFilter = options?.packageName?.trim();
|
|
1091
|
+
const leaks = [];
|
|
1092
|
+
for (const [pkg, duNode] of index.deploymentUnitsByPkg.entries()) {
|
|
1093
|
+
if (pkgFilter &&
|
|
1094
|
+
!packageMatchesFilter(pkg, index.pathPrefixByPkg.get(pkg), pkgFilter)) {
|
|
1095
|
+
continue;
|
|
1096
|
+
}
|
|
1097
|
+
const initNode = graph.nodes.find((n) => (n.scope ?? "USER") === "USER" &&
|
|
1098
|
+
n.entityType === INIT_BLOCK_ENTITY_TYPE &&
|
|
1099
|
+
(n.parentBoundaryId === duNode.id || index.resolveNodePkg(n.id) === pkg));
|
|
1100
|
+
if (!initNode)
|
|
1101
|
+
continue;
|
|
1102
|
+
const pkgConnectorEdges = graph.edges.filter((e) => {
|
|
1103
|
+
if ((e.scope ?? "USER") !== "USER")
|
|
1104
|
+
return false;
|
|
1105
|
+
if (index.resolveNodePkg(e.sourceId) !== pkg)
|
|
1106
|
+
return false;
|
|
1107
|
+
if (CONNECTOR_LEAK_ENTITY_TYPES.has(e.entityType))
|
|
1108
|
+
return true;
|
|
1109
|
+
if (!e.targetId)
|
|
1110
|
+
return false;
|
|
1111
|
+
const tgt = index.nodeById.get(e.targetId);
|
|
1112
|
+
return Boolean(tgt &&
|
|
1113
|
+
tgt.type === "OPEN_CONNECTOR" &&
|
|
1114
|
+
CONNECTOR_LEAK_ENTITY_TYPES.has(tgt.entityType));
|
|
1115
|
+
});
|
|
1116
|
+
if (pkgConnectorEdges.length === 0)
|
|
1117
|
+
continue;
|
|
1118
|
+
const initConnectorEdges = pkgConnectorEdges.filter((e) => e.sourceId === initNode.id);
|
|
1119
|
+
// Must own the majority (> 50%) of OPEN_CONNECTOR (DB_QUERY / HTTP_FETCH) edges in the package
|
|
1120
|
+
if (initConnectorEdges.length <= pkgConnectorEdges.length / 2)
|
|
1121
|
+
continue;
|
|
1122
|
+
// Identify HTTP_ENDPOINT / API_ENDPOINT / EXPORTED_MODULE contracts in the package
|
|
1123
|
+
const candidateContracts = graph.nodes.filter((n) => {
|
|
1124
|
+
if ((n.scope ?? "USER") !== "USER")
|
|
1125
|
+
return false;
|
|
1126
|
+
if (n.type !== "CONTRACT")
|
|
1127
|
+
return false;
|
|
1128
|
+
if (index.resolveNodePkg(n.id) !== pkg)
|
|
1129
|
+
return false;
|
|
1130
|
+
if (NON_HTTP_ROUTE_PATTERN_IDS.has(n.patternId))
|
|
1131
|
+
return false;
|
|
1132
|
+
return (n.entityType === "HTTP_ENDPOINT" ||
|
|
1133
|
+
n.entityType === "API_ENDPOINT" ||
|
|
1134
|
+
n.entityType === "EXPORTED_MODULE");
|
|
1135
|
+
});
|
|
1136
|
+
if (candidateContracts.length === 0)
|
|
1137
|
+
continue;
|
|
1138
|
+
const deadEndContracts = candidateContracts.filter((c) => (index.flowOutTargetsBySource.get(c.id)?.length ?? 0) === 0);
|
|
1139
|
+
if (deadEndContracts.length === 0)
|
|
1140
|
+
continue;
|
|
1141
|
+
// Track non-init contract call evidence keys so deduplicated OPEN_CONNECTOR nodes don't mix
|
|
1142
|
+
// resolved contract call sites into the leaked file breakdown
|
|
1143
|
+
const contractOwnedEvKeys = new Set();
|
|
1144
|
+
for (const e of pkgConnectorEdges) {
|
|
1145
|
+
if (e.sourceId === initNode.id)
|
|
1146
|
+
continue;
|
|
1147
|
+
for (const ev of getAllEvidenceRecords(e)) {
|
|
1148
|
+
if (ev.filePath) {
|
|
1149
|
+
contractOwnedEvKeys.add(`${ev.filePath}:${ev.lineNumber ?? ""}`);
|
|
1150
|
+
}
|
|
1151
|
+
}
|
|
1152
|
+
}
|
|
1153
|
+
const leakedConnectorsMap = new Map();
|
|
1154
|
+
const leakedCallsByFile = new Map();
|
|
1155
|
+
const recordLeakedCall = (filePath, call) => {
|
|
1156
|
+
let list = leakedCallsByFile.get(filePath);
|
|
1157
|
+
if (!list) {
|
|
1158
|
+
list = [];
|
|
1159
|
+
leakedCallsByFile.set(filePath, list);
|
|
1160
|
+
}
|
|
1161
|
+
if (!list.some((c) => c.connectorId === call.connectorId &&
|
|
1162
|
+
c.lineNumber === call.lineNumber &&
|
|
1163
|
+
c.name === call.name)) {
|
|
1164
|
+
list.push(call);
|
|
1165
|
+
}
|
|
1166
|
+
};
|
|
1167
|
+
for (const edge of initConnectorEdges) {
|
|
1168
|
+
const tgt = edge.targetId ? index.nodeById.get(edge.targetId) : undefined;
|
|
1169
|
+
if (tgt && !leakedConnectorsMap.has(tgt.id)) {
|
|
1170
|
+
leakedConnectorsMap.set(tgt.id, toNodeSummaryRef(tgt, index.resolveNodePkg));
|
|
1171
|
+
}
|
|
1172
|
+
const connId = tgt?.id ?? edge.id;
|
|
1173
|
+
const connName = tgt ? cleanNodeLabel(tgt.name) : cleanNodeLabel(edge.name);
|
|
1174
|
+
const connEntityType = tgt?.entityType ?? edge.entityType;
|
|
1175
|
+
const edgeEvs = getAllEvidenceRecords(edge).filter((ev) => Boolean(ev.filePath));
|
|
1176
|
+
const tgtEvs = tgt
|
|
1177
|
+
? getAllEvidenceRecords(tgt).filter((ev) => Boolean(ev.filePath) &&
|
|
1178
|
+
!contractOwnedEvKeys.has(`${ev.filePath}:${ev.lineNumber ?? ""}`))
|
|
1179
|
+
: [];
|
|
1180
|
+
const combinedEvs = [...edgeEvs, ...tgtEvs];
|
|
1181
|
+
if (combinedEvs.length > 0) {
|
|
1182
|
+
for (const ev of combinedEvs) {
|
|
1183
|
+
if (!ev.filePath)
|
|
1184
|
+
continue;
|
|
1185
|
+
recordLeakedCall(ev.filePath, {
|
|
1186
|
+
connectorId: connId,
|
|
1187
|
+
name: connName,
|
|
1188
|
+
entityType: connEntityType,
|
|
1189
|
+
lineNumber: ev.lineNumber,
|
|
1190
|
+
snippet: ev.snippet,
|
|
1191
|
+
});
|
|
1192
|
+
}
|
|
1193
|
+
}
|
|
1194
|
+
else {
|
|
1195
|
+
const fallbackFp = getPrimaryEvidence(initNode).filePath;
|
|
1196
|
+
if (fallbackFp) {
|
|
1197
|
+
recordLeakedCall(fallbackFp, {
|
|
1198
|
+
connectorId: connId,
|
|
1199
|
+
name: connName,
|
|
1200
|
+
entityType: connEntityType,
|
|
1201
|
+
});
|
|
1202
|
+
}
|
|
1203
|
+
}
|
|
1204
|
+
}
|
|
1205
|
+
const deadEndRefs = deadEndContracts.map((c) => toNodeSummaryRef(c, index.resolveNodePkg));
|
|
1206
|
+
const deadEndByFile = new Map();
|
|
1207
|
+
for (const ref of deadEndRefs) {
|
|
1208
|
+
if (!ref.filePath)
|
|
1209
|
+
continue;
|
|
1210
|
+
let list = deadEndByFile.get(ref.filePath);
|
|
1211
|
+
if (!list) {
|
|
1212
|
+
list = [];
|
|
1213
|
+
deadEndByFile.set(ref.filePath, list);
|
|
1214
|
+
}
|
|
1215
|
+
list.push(ref);
|
|
1216
|
+
}
|
|
1217
|
+
const candidateFiles = new Set([
|
|
1218
|
+
...leakedCallsByFile.keys(),
|
|
1219
|
+
...(leakedCallsByFile.size === 0 ? deadEndByFile.keys() : []),
|
|
1220
|
+
]);
|
|
1221
|
+
// Also include files with dead-end contracts if they share the package and had leaked calls
|
|
1222
|
+
for (const fp of deadEndByFile.keys()) {
|
|
1223
|
+
if (leakedCallsByFile.has(fp)) {
|
|
1224
|
+
candidateFiles.add(fp);
|
|
1225
|
+
}
|
|
1226
|
+
}
|
|
1227
|
+
const fileBreakdown = [...candidateFiles]
|
|
1228
|
+
.map((filePath) => ({
|
|
1229
|
+
filePath,
|
|
1230
|
+
deadEndContracts: deadEndByFile.get(filePath) ?? [],
|
|
1231
|
+
leakedCalls: leakedCallsByFile.get(filePath) ?? [],
|
|
1232
|
+
}))
|
|
1233
|
+
.sort((a, b) => {
|
|
1234
|
+
const aBoth = a.deadEndContracts.length > 0 && a.leakedCalls.length > 0 ? 1 : 0;
|
|
1235
|
+
const bBoth = b.deadEndContracts.length > 0 && b.leakedCalls.length > 0 ? 1 : 0;
|
|
1236
|
+
if (aBoth !== bBoth)
|
|
1237
|
+
return bBoth - aBoth;
|
|
1238
|
+
if (b.leakedCalls.length !== a.leakedCalls.length) {
|
|
1239
|
+
return b.leakedCalls.length - a.leakedCalls.length;
|
|
1240
|
+
}
|
|
1241
|
+
return a.filePath.localeCompare(b.filePath);
|
|
1242
|
+
});
|
|
1243
|
+
const affectedFiles = fileBreakdown.map((f) => f.filePath);
|
|
1244
|
+
const sharePercent = round1((initConnectorEdges.length / pkgConnectorEdges.length) * 100);
|
|
1245
|
+
const initSummary = toNodeSummaryRef(initNode, index.resolveNodePkg);
|
|
1246
|
+
const leakedConnectors = [...leakedConnectorsMap.values()];
|
|
1247
|
+
const description = `'${initSummary.label}' in package '${pkg}' owns ${initConnectorEdges.length}/${pkgConnectorEdges.length} (${sharePercent}%) of OPEN_CONNECTOR edges (${leakedConnectors.map((c) => c.label).join(", ") || "DB_QUERY/HTTP_FETCH"}) ` +
|
|
1248
|
+
`while ${deadEndRefs.length} HTTP_ENDPOINT/EXPORTED_MODULE contract(s) (${deadEndRefs.slice(0, 4).map((c) => c.label).join(", ")}) are dead-end ingress (resolvedOutDegree === 0). ` +
|
|
1249
|
+
`Scope ownership failed to propagate in: ${affectedFiles.join(", ") || pkg}.`;
|
|
1250
|
+
const guidance = `Module-Scope Call Leak: In [${affectedFiles.join(", ") || pkg}], ` +
|
|
1251
|
+
`deferred calls to [${leakedConnectors.map((c) => c.label).join(", ")}] fell back to '${initSummary.label}' instead of binding to [${deadEndRefs.slice(0, 4).map((c) => c.label).join(", ")}]. ` +
|
|
1252
|
+
`Connect route or module handlers via chomp.config.json conventions or chomp_local_shims bridges, then verify with chomp_get_diff.`;
|
|
1253
|
+
leaks.push({
|
|
1254
|
+
kind: "INIT_BLOCK_CONNECTOR_LEAK",
|
|
1255
|
+
ruleId: "INIT_BLOCK_CONNECTOR_LEAK",
|
|
1256
|
+
severity: "ADVISORY",
|
|
1257
|
+
packageName: pkg,
|
|
1258
|
+
initBlockNode: initSummary,
|
|
1259
|
+
initConnectorEdgeCount: initConnectorEdges.length,
|
|
1260
|
+
totalPackageConnectorEdgeCount: pkgConnectorEdges.length,
|
|
1261
|
+
initConnectorSharePercent: sharePercent,
|
|
1262
|
+
deadEndContractCount: deadEndRefs.length,
|
|
1263
|
+
deadEndContracts: deadEndRefs,
|
|
1264
|
+
leakedConnectors,
|
|
1265
|
+
affectedFiles,
|
|
1266
|
+
fileBreakdown,
|
|
1267
|
+
description,
|
|
1268
|
+
agentReadinessOpportunity: guidance,
|
|
1269
|
+
agentReadinessGuidance: guidance,
|
|
1270
|
+
});
|
|
1271
|
+
}
|
|
1272
|
+
return leaks;
|
|
1273
|
+
}
|
|
1274
|
+
const KNOWN_DB_DRIVER_RECEPTORS = new Map([
|
|
1275
|
+
["pg", "Database: PostgreSQL"],
|
|
1276
|
+
["pg-pool", "Database: PostgreSQL"],
|
|
1277
|
+
["postgres", "Database: PostgreSQL"],
|
|
1278
|
+
["@neondatabase/serverless", "Database: PostgreSQL"],
|
|
1279
|
+
["@vercel/postgres", "Database: PostgreSQL"],
|
|
1280
|
+
["@electric-sql/pglite", "Database: PostgreSQL"],
|
|
1281
|
+
["mysql", "Database: MySQL"],
|
|
1282
|
+
["mysql2", "Database: MySQL"],
|
|
1283
|
+
["@planetscale/database", "Database: MySQL"],
|
|
1284
|
+
["better-sqlite3", "Database: SQLite"],
|
|
1285
|
+
["sqlite3", "Database: SQLite"],
|
|
1286
|
+
["@libsql/client", "Database: SQLite"],
|
|
1287
|
+
["sql.js", "Database: SQLite"],
|
|
1288
|
+
["mongodb", "Database: MongoDB"],
|
|
1289
|
+
["mongoose", "Database: MongoDB"],
|
|
1290
|
+
["redis", "Cache: Redis"],
|
|
1291
|
+
["ioredis", "Cache: Redis"],
|
|
1292
|
+
["@upstash/redis", "Cache: Redis"],
|
|
1293
|
+
]);
|
|
1294
|
+
/**
|
|
1295
|
+
* Flags when a package invokes a known database driver (`Package: pg`, `Package: mysql2`, etc.)
|
|
1296
|
+
* via generic `EXTERNAL_PACKAGE` `CALL` edges (`● pg` micro-node) while emitting 0 `DB_QUERY` /
|
|
1297
|
+
* `DB_OPERATION` Open Connectors for the Database Receptor Box (`SHADOWED_DB_RECEPTOR`).
|
|
1298
|
+
*/
|
|
1299
|
+
function detectShadowedDbReceptors(graph, index, options) {
|
|
1300
|
+
const pkgFilter = options?.packageName?.trim();
|
|
1301
|
+
const diagnostics = [];
|
|
1302
|
+
for (const [pkg] of index.deploymentUnitsByPkg.entries()) {
|
|
1303
|
+
if (pkgFilter &&
|
|
1304
|
+
!packageMatchesFilter(pkg, index.pathPrefixByPkg.get(pkg), pkgFilter)) {
|
|
1305
|
+
continue;
|
|
1306
|
+
}
|
|
1307
|
+
const pkgDbConnectors = graph.nodes.filter((n) => (n.scope ?? "USER") === "USER" &&
|
|
1308
|
+
n.type === "OPEN_CONNECTOR" &&
|
|
1309
|
+
(n.entityType === "DB_QUERY" ||
|
|
1310
|
+
n.entityType === "DB_OPERATION" ||
|
|
1311
|
+
n.entityType === "DB_TRANSACTION") &&
|
|
1312
|
+
index.resolveNodePkg(n.id) === pkg);
|
|
1313
|
+
if (pkgDbConnectors.length > 0)
|
|
1314
|
+
continue;
|
|
1315
|
+
for (const node of graph.nodes) {
|
|
1316
|
+
if (node.type !== "OPEN_CONNECTOR" ||
|
|
1317
|
+
node.entityType !== "EXTERNAL_PACKAGE") {
|
|
1318
|
+
continue;
|
|
1319
|
+
}
|
|
1320
|
+
const depName = node.name.replace(/^Package:\s*/i, "").trim();
|
|
1321
|
+
const expectedReceptorLabel = KNOWN_DB_DRIVER_RECEPTORS.get(depName);
|
|
1322
|
+
if (!expectedReceptorLabel)
|
|
1323
|
+
continue;
|
|
1324
|
+
const inEdges = (index.inEdgesByTarget.get(node.id) ?? []).filter((e) => (e.scope ?? "USER") === "USER" &&
|
|
1325
|
+
index.resolveNodePkg(e.sourceId) === pkg);
|
|
1326
|
+
if (inEdges.length === 0)
|
|
1327
|
+
continue;
|
|
1328
|
+
const callersMap = new Map();
|
|
1329
|
+
for (const e of inEdges) {
|
|
1330
|
+
const caller = index.nodeById.get(e.sourceId);
|
|
1331
|
+
if (caller && !callersMap.has(caller.id)) {
|
|
1332
|
+
callersMap.set(caller.id, toNodeSummaryRef(caller, index.resolveNodePkg));
|
|
1333
|
+
}
|
|
1334
|
+
}
|
|
1335
|
+
const shadowedCallers = [...callersMap.values()];
|
|
1336
|
+
const driverRef = toNodeSummaryRef(node, index.resolveNodePkg);
|
|
1337
|
+
const description = `Package '${pkg}' has ${inEdges.length} call edge(s) targeting '${node.name}' (EXTERNAL_PACKAGE micro-node) from [${shadowedCallers.map((c) => c.label).join(", ")}], ` +
|
|
1338
|
+
`but emitted 0 DB_QUERY/DB_OPERATION Open Connectors (${expectedReceptorLabel} receptor box is missing).`;
|
|
1339
|
+
const guidance = `Shadowed DB Receptor: Database calls in '${pkg}' collapsed into the '${node.name}' package micro-node instead of connecting to '${expectedReceptorLabel}'. ` +
|
|
1340
|
+
`Bridge custom DB client wrappers via chomp.config.json conventions or chomp_local_shims, then verify with chomp_get_diff.`;
|
|
1341
|
+
diagnostics.push({
|
|
1342
|
+
kind: "SHADOWED_DB_RECEPTOR",
|
|
1343
|
+
ruleId: "SHADOWED_DB_RECEPTOR",
|
|
1344
|
+
severity: "ADVISORY",
|
|
1345
|
+
packageName: pkg,
|
|
1346
|
+
driverPackageNode: driverRef,
|
|
1347
|
+
expectedReceptorLabel,
|
|
1348
|
+
shadowedCallEdgeCount: inEdges.length,
|
|
1349
|
+
shadowedCallers,
|
|
1350
|
+
description,
|
|
1351
|
+
agentReadinessOpportunity: guidance,
|
|
1352
|
+
agentReadinessGuidance: guidance,
|
|
1353
|
+
});
|
|
1354
|
+
}
|
|
1355
|
+
}
|
|
1356
|
+
return diagnostics;
|
|
1357
|
+
}
|
|
1358
|
+
/**
|
|
1359
|
+
* Filters nodes in `chomp_get_nodes` with support for `search_term` and `packageName`
|
|
1360
|
+
* fast-path resolution ([PAT-MCP-08]).
|
|
1361
|
+
*/
|
|
1362
|
+
export function filterNodesForMcp(graph, filters) {
|
|
1363
|
+
const index = buildGraphIndex(graph);
|
|
1364
|
+
const nameFilter = filters.name?.toLowerCase();
|
|
1365
|
+
const filePathFilter = filters.filePath?.toLowerCase();
|
|
1366
|
+
const searchTermFilter = filters.searchTerm?.toLowerCase();
|
|
1367
|
+
const packageFilter = filters.packageName?.trim();
|
|
1368
|
+
let filteredNodes = graph.nodes;
|
|
1369
|
+
if (filters.type) {
|
|
1370
|
+
filteredNodes = filteredNodes.filter((n) => n.type === filters.type);
|
|
1371
|
+
}
|
|
1372
|
+
if (filters.entityType) {
|
|
1373
|
+
filteredNodes = filteredNodes.filter((n) => n.entityType === filters.entityType);
|
|
1374
|
+
}
|
|
1375
|
+
if (filters.parentBoundaryId) {
|
|
1376
|
+
filteredNodes = filteredNodes.filter((n) => n.parentBoundaryId === filters.parentBoundaryId);
|
|
1377
|
+
}
|
|
1378
|
+
if (packageFilter) {
|
|
1379
|
+
filteredNodes = filteredNodes.filter((n) => {
|
|
1380
|
+
const pkg = index.resolveNodePkg(n.id);
|
|
1381
|
+
const ev = getPrimaryEvidence(n);
|
|
1382
|
+
return packageMatchesFilter(pkg, ev.filePath, packageFilter);
|
|
1383
|
+
});
|
|
1384
|
+
}
|
|
1385
|
+
if (nameFilter) {
|
|
1386
|
+
filteredNodes = filteredNodes.filter((n) => typeof n.name === "string" && n.name.toLowerCase().includes(nameFilter));
|
|
1387
|
+
}
|
|
1388
|
+
if (filePathFilter) {
|
|
1389
|
+
filteredNodes = filteredNodes.filter((n) => {
|
|
1390
|
+
const ev = n.evidence;
|
|
1391
|
+
if (!ev)
|
|
1392
|
+
return false;
|
|
1393
|
+
if (Array.isArray(ev)) {
|
|
1394
|
+
return ev.some((r) => typeof r?.filePath === "string" &&
|
|
1395
|
+
r.filePath.toLowerCase().includes(filePathFilter));
|
|
1396
|
+
}
|
|
1397
|
+
return (typeof ev.filePath === "string" &&
|
|
1398
|
+
ev.filePath.toLowerCase().includes(filePathFilter));
|
|
1399
|
+
});
|
|
1400
|
+
}
|
|
1401
|
+
if (searchTermFilter) {
|
|
1402
|
+
filteredNodes = filteredNodes.filter((n) => {
|
|
1403
|
+
if (n.id.toLowerCase().includes(searchTermFilter))
|
|
1404
|
+
return true;
|
|
1405
|
+
if (n.name.toLowerCase().includes(searchTermFilter))
|
|
1406
|
+
return true;
|
|
1407
|
+
if (n.entityType.toLowerCase().includes(searchTermFilter))
|
|
1408
|
+
return true;
|
|
1409
|
+
const meta = parseNodeMeta(n);
|
|
1410
|
+
if (typeof meta.humanLabel === "string" &&
|
|
1411
|
+
meta.humanLabel.toLowerCase().includes(searchTermFilter)) {
|
|
1412
|
+
return true;
|
|
1413
|
+
}
|
|
1414
|
+
if (typeof meta.domain === "string" &&
|
|
1415
|
+
meta.domain.toLowerCase().includes(searchTermFilter)) {
|
|
1416
|
+
return true;
|
|
1417
|
+
}
|
|
1418
|
+
if (typeof meta.summary === "string" &&
|
|
1419
|
+
meta.summary.toLowerCase().includes(searchTermFilter)) {
|
|
1420
|
+
return true;
|
|
1421
|
+
}
|
|
1422
|
+
const nodeOverlays = filters.overlaysByEntityId?.get(n.id);
|
|
1423
|
+
if (nodeOverlays) {
|
|
1424
|
+
for (const ov of nodeOverlays) {
|
|
1425
|
+
const p = ov.payload;
|
|
1426
|
+
if (!p || typeof p !== "object")
|
|
1427
|
+
continue;
|
|
1428
|
+
if (typeof p.humanLabel === "string" &&
|
|
1429
|
+
p.humanLabel.toLowerCase().includes(searchTermFilter)) {
|
|
1430
|
+
return true;
|
|
1431
|
+
}
|
|
1432
|
+
if (typeof p.domain === "string" &&
|
|
1433
|
+
p.domain.toLowerCase().includes(searchTermFilter)) {
|
|
1434
|
+
return true;
|
|
1435
|
+
}
|
|
1436
|
+
if (typeof p.summary === "string" &&
|
|
1437
|
+
p.summary.toLowerCase().includes(searchTermFilter)) {
|
|
1438
|
+
return true;
|
|
1439
|
+
}
|
|
1440
|
+
}
|
|
1441
|
+
}
|
|
1442
|
+
const ev = n.evidence;
|
|
1443
|
+
if (Array.isArray(ev)) {
|
|
1444
|
+
return ev.some((r) => typeof r?.filePath === "string" &&
|
|
1445
|
+
r.filePath.toLowerCase().includes(searchTermFilter));
|
|
1446
|
+
}
|
|
1447
|
+
return (typeof ev?.filePath === "string" &&
|
|
1448
|
+
ev.filePath.toLowerCase().includes(searchTermFilter));
|
|
1449
|
+
});
|
|
1450
|
+
}
|
|
1451
|
+
return filteredNodes;
|
|
1452
|
+
}
|
|
1453
|
+
/**
|
|
1454
|
+
* Selective MCP overlay hydration (`[PAT-DB-05]`).
|
|
1455
|
+
* Prevents multi-plugin stores from bloating structural queries in `chomp_get_nodes`:
|
|
1456
|
+
* - By default (`includeOverlays` omitted and `layers` omitted), returns pure structural nodes without `overlays`.
|
|
1457
|
+
* - When `includeOverlays: true` or `layers` is specified, attaches matching `overlays` onto each node.
|
|
1458
|
+
*/
|
|
1459
|
+
export function hydrateNodeOverlays(nodes, overlays, options) {
|
|
1460
|
+
const requestedLayers = (options?.layers ?? [])
|
|
1461
|
+
.map((l) => l.trim())
|
|
1462
|
+
.filter(Boolean);
|
|
1463
|
+
const layerSet = requestedLayers.length > 0 ? new Set(requestedLayers) : null;
|
|
1464
|
+
const shouldInclude = options?.includeOverlays ?? (layerSet !== null);
|
|
1465
|
+
if (!shouldInclude) {
|
|
1466
|
+
return nodes.map((n) => ({ ...n }));
|
|
1467
|
+
}
|
|
1468
|
+
const overlaysByEntityId = new Map();
|
|
1469
|
+
for (const ov of overlays) {
|
|
1470
|
+
if (layerSet && !layerSet.has(ov.layer))
|
|
1471
|
+
continue;
|
|
1472
|
+
let list = overlaysByEntityId.get(ov.entityId);
|
|
1473
|
+
if (!list) {
|
|
1474
|
+
list = [];
|
|
1475
|
+
overlaysByEntityId.set(ov.entityId, list);
|
|
1476
|
+
}
|
|
1477
|
+
list.push(ov);
|
|
1478
|
+
}
|
|
1479
|
+
return nodes.map((n) => {
|
|
1480
|
+
const nodeOverlays = overlaysByEntityId.get(n.id);
|
|
1481
|
+
return nodeOverlays && nodeOverlays.length > 0
|
|
1482
|
+
? { ...n, overlays: nodeOverlays }
|
|
1483
|
+
: { ...n };
|
|
1484
|
+
});
|
|
1485
|
+
}
|
|
1486
|
+
/**
|
|
1487
|
+
* Formats per-layer write counts for `chomp_enrich_nodes` (`[PAT-DB-05]`).
|
|
1488
|
+
*/
|
|
1489
|
+
export function formatEnrichNodesSummary(layerCounts, rulesAddedOrUpdated) {
|
|
1490
|
+
const entries = Object.entries(layerCounts).filter(([, count]) => count > 0);
|
|
1491
|
+
const totalUpdated = entries.reduce((acc, [, count]) => acc + count, 0);
|
|
1492
|
+
const layerBreakdown = entries.length > 0
|
|
1493
|
+
? ` (${entries.map(([layer, count]) => `${layer}: ${count}`).join(", ")})`
|
|
1494
|
+
: "";
|
|
1495
|
+
return `Successfully enriched ${totalUpdated} node(s)${layerBreakdown} and saved ${rulesAddedOrUpdated} classification rule(s) to .chomp/rules.json.`;
|
|
1496
|
+
}
|
|
1497
|
+
/**
|
|
1498
|
+
* Resolves target node IDs for `chomp_create_view` combining explicit `highlightNodeIds`
|
|
1499
|
+
* with optional `search_term` / `packageName` fast-path filters ([PAT-MCP-08]).
|
|
1500
|
+
*/
|
|
1501
|
+
export function resolveViewNodeIds(graph, explicitIds, searchTerm, packageName) {
|
|
1502
|
+
const result = [];
|
|
1503
|
+
const seen = new Set();
|
|
1504
|
+
for (const id of explicitIds) {
|
|
1505
|
+
if (id && !seen.has(id)) {
|
|
1506
|
+
seen.add(id);
|
|
1507
|
+
result.push(id);
|
|
1508
|
+
}
|
|
1509
|
+
}
|
|
1510
|
+
if (graph && (searchTerm || packageName)) {
|
|
1511
|
+
const matches = filterNodesForMcp(graph, {
|
|
1512
|
+
searchTerm,
|
|
1513
|
+
packageName,
|
|
1514
|
+
});
|
|
1515
|
+
const visualMatches = matches.filter((n) => !isHiddenNode(n));
|
|
1516
|
+
const chosen = visualMatches.length > 0 ? visualMatches : matches;
|
|
1517
|
+
for (const node of chosen.slice(0, 40)) {
|
|
1518
|
+
if (!seen.has(node.id)) {
|
|
1519
|
+
seen.add(node.id);
|
|
1520
|
+
result.push(node.id);
|
|
1521
|
+
}
|
|
1522
|
+
}
|
|
1523
|
+
}
|
|
1524
|
+
return result;
|
|
1525
|
+
}
|
|
1526
|
+
/**
|
|
1527
|
+
* Determines the topological height (`"system"` Bird's-Eye Macro View vs `"package"`
|
|
1528
|
+
* Circuit-Board View) and primary package for `chomp_create_view` ([PAT-MCP-03], [PAT-VIS-28]).
|
|
1529
|
+
*
|
|
1530
|
+
* - If `explicitViewLevel` is provided (`"system"` or `"package"`), honors it directly.
|
|
1531
|
+
* - Otherwise defaults to `"system"` when highlighted nodes span multiple packages (or 0 packages),
|
|
1532
|
+
* and `"package"` when all highlighted nodes reside within a single package.
|
|
1533
|
+
*/
|
|
1534
|
+
export function resolveViewTargetAltitude(graph, highlightNodeIds, explicitViewLevel, explicitPackageName) {
|
|
1535
|
+
const affectedPackages = [];
|
|
1536
|
+
const seenPkgs = new Set();
|
|
1537
|
+
if (graph && highlightNodeIds.length > 0) {
|
|
1538
|
+
const index = buildGraphIndex(graph);
|
|
1539
|
+
for (const rawId of highlightNodeIds) {
|
|
1540
|
+
const baseId = String(rawId).split("::")[0].split("@")[0];
|
|
1541
|
+
if (!baseId)
|
|
1542
|
+
continue;
|
|
1543
|
+
const pkg = index.resolveNodePkg(baseId);
|
|
1544
|
+
if (pkg && !seenPkgs.has(pkg)) {
|
|
1545
|
+
seenPkgs.add(pkg);
|
|
1546
|
+
affectedPackages.push(pkg);
|
|
1547
|
+
}
|
|
1548
|
+
}
|
|
1549
|
+
}
|
|
1550
|
+
let resolvedPkg;
|
|
1551
|
+
if (explicitPackageName && explicitPackageName.trim()) {
|
|
1552
|
+
const normExplicit = normalizePackageQuery(explicitPackageName);
|
|
1553
|
+
const matchedFromGraph = affectedPackages.find((p) => normalizePackageQuery(p) === normExplicit);
|
|
1554
|
+
resolvedPkg = matchedFromGraph ?? (normExplicit || explicitPackageName.trim());
|
|
1555
|
+
if (resolvedPkg && !seenPkgs.has(resolvedPkg)) {
|
|
1556
|
+
seenPkgs.add(resolvedPkg);
|
|
1557
|
+
affectedPackages.unshift(resolvedPkg);
|
|
1558
|
+
}
|
|
1559
|
+
}
|
|
1560
|
+
else if (affectedPackages.length === 1) {
|
|
1561
|
+
resolvedPkg = affectedPackages[0];
|
|
1562
|
+
}
|
|
1563
|
+
const viewLevel = explicitViewLevel === "system" || explicitViewLevel === "package"
|
|
1564
|
+
? explicitViewLevel
|
|
1565
|
+
: affectedPackages.length === 1
|
|
1566
|
+
? "package"
|
|
1567
|
+
: "system";
|
|
1568
|
+
const targetPkg = viewLevel === "package"
|
|
1569
|
+
? (resolvedPkg ?? affectedPackages[0])
|
|
1570
|
+
: resolvedPkg;
|
|
1571
|
+
return {
|
|
1572
|
+
viewLevel,
|
|
1573
|
+
...(targetPkg ? { packageName: targetPkg } : {}),
|
|
1574
|
+
affectedPackages,
|
|
1575
|
+
};
|
|
1576
|
+
}
|
|
1577
|
+
/**
|
|
1578
|
+
* Builds a one-click local deep-link URL for opening the Visualizer directly in
|
|
1579
|
+
* Agent Spotlight mode at the selected topological height (`[PAT-MCP-03]`, `[PAT-VIS-28]`).
|
|
1580
|
+
*/
|
|
1581
|
+
export function buildActiveViewUrl(options) {
|
|
1582
|
+
const rawBase = (options.baseUrl || "http://localhost:5555")
|
|
1583
|
+
.trim()
|
|
1584
|
+
.replace(/\/+$/, "");
|
|
1585
|
+
const params = [
|
|
1586
|
+
"view=active",
|
|
1587
|
+
`level=${encodeURIComponent(options.viewLevel)}`,
|
|
1588
|
+
];
|
|
1589
|
+
if (options.viewLevel === "package" &&
|
|
1590
|
+
options.packageName &&
|
|
1591
|
+
options.packageName.trim()) {
|
|
1592
|
+
const cleanPkg = encodeURIComponent(options.packageName.trim())
|
|
1593
|
+
.replace(/%40/g, "@")
|
|
1594
|
+
.replace(/%2F/gi, "/");
|
|
1595
|
+
params.push(`pkg=${cleanPkg}`);
|
|
1596
|
+
}
|
|
1597
|
+
return `${rawBase}/?${params.join("&")}`;
|
|
1598
|
+
}
|
|
1599
|
+
/**
|
|
1600
|
+
* `chomp_audit_health` implementation ([PAT-MCP-08], [PAT-MCP-09]).
|
|
1601
|
+
*
|
|
1602
|
+
* Synthesizes system & per-package health metrics, unreachable orphan contracts,
|
|
1603
|
+
* dead-end ingress nodes, opaque contract bodies (`astCallCount > 0 && resolvedOutDegree === 0`),
|
|
1604
|
+
* inter-package seam & "missing glue" diagnostics (`ISOLATED_DEPLOYMENT_UNITS`,
|
|
1605
|
+
* `UNSTITCHED_PROTOCOL_SEAM`, `INIT_BLOCK_CONNECTOR_LEAK`),
|
|
1606
|
+
* and unresolved call hotspots framed as Agent-Readiness / Map Visibility opportunities.
|
|
1607
|
+
*/
|
|
1608
|
+
export function auditGraphHealth(graph, options) {
|
|
1609
|
+
const index = buildGraphIndex(graph);
|
|
1610
|
+
const maxItems = Math.max(1, Math.min(options?.limit ?? 25, 100));
|
|
1611
|
+
const pkgFilter = options?.packageName?.trim();
|
|
1612
|
+
const matchesPkg = (nodeId) => {
|
|
1613
|
+
if (!pkgFilter)
|
|
1614
|
+
return true;
|
|
1615
|
+
const pkg = index.resolveNodePkg(nodeId);
|
|
1616
|
+
const node = index.nodeById.get(nodeId);
|
|
1617
|
+
const ev = node ? getPrimaryEvidence(node) : {};
|
|
1618
|
+
return packageMatchesFilter(pkg, ev.filePath, pkgFilter);
|
|
1619
|
+
};
|
|
1620
|
+
// 1. Reachability from INGRESS & INIT_BLOCK roots (and cross-package entries)
|
|
1621
|
+
const entryIds = [];
|
|
1622
|
+
const entrySet = new Set();
|
|
1623
|
+
const foldedIds = new Set();
|
|
1624
|
+
for (const n of index.nodeById.values()) {
|
|
1625
|
+
if (isHiddenNode(n))
|
|
1626
|
+
continue;
|
|
1627
|
+
const outTargets = index.flowOutTargetsBySource.get(n.id) ?? [];
|
|
1628
|
+
if (INGRESS_ENTITY_TYPES.has(n.entityType)) {
|
|
1629
|
+
if (n.entityType === "NEXTJS_LAYOUT" && outTargets.length === 0) {
|
|
1630
|
+
foldedIds.add(n.id);
|
|
1631
|
+
continue;
|
|
1632
|
+
}
|
|
1633
|
+
entrySet.add(n.id);
|
|
1634
|
+
entryIds.push(n.id);
|
|
1635
|
+
}
|
|
1636
|
+
else if (n.entityType === INIT_BLOCK_ENTITY_TYPE &&
|
|
1637
|
+
outTargets.length > 0) {
|
|
1638
|
+
entrySet.add(n.id);
|
|
1639
|
+
entryIds.push(n.id);
|
|
1640
|
+
}
|
|
1641
|
+
}
|
|
1642
|
+
for (const [srcId, tgts] of index.flowOutTargetsBySource.entries()) {
|
|
1643
|
+
const srcPkg = index.resolveNodePkg(srcId);
|
|
1644
|
+
for (const tgtId of tgts) {
|
|
1645
|
+
const tgtPkg = index.resolveNodePkg(tgtId) || srcPkg;
|
|
1646
|
+
const tgtNode = index.nodeById.get(tgtId);
|
|
1647
|
+
if (srcPkg !== tgtPkg && tgtNode && !isHiddenNode(tgtNode)) {
|
|
1648
|
+
if (!entrySet.has(tgtId)) {
|
|
1649
|
+
entrySet.add(tgtId);
|
|
1650
|
+
entryIds.push(tgtId);
|
|
1651
|
+
}
|
|
1652
|
+
}
|
|
1653
|
+
}
|
|
1654
|
+
}
|
|
1655
|
+
// Leaf middlewares & presentational components folded by [PAT-VIS-12] / [PAT-VIS-13]
|
|
1656
|
+
for (const edge of graph.edges) {
|
|
1657
|
+
if (!edge.targetId)
|
|
1658
|
+
continue;
|
|
1659
|
+
const tgt = index.nodeById.get(edge.targetId);
|
|
1660
|
+
if (!tgt || isHiddenNode(tgt))
|
|
1661
|
+
continue;
|
|
1662
|
+
const tgtOut = index.flowOutTargetsBySource.get(tgt.id)?.length ?? 0;
|
|
1663
|
+
if (edge.entityType === "INTERCEPTS" &&
|
|
1664
|
+
tgt.entityType === "MIDDLEWARE" &&
|
|
1665
|
+
tgtOut === 0) {
|
|
1666
|
+
foldedIds.add(tgt.id);
|
|
1667
|
+
}
|
|
1668
|
+
if (edge.entityType === "RENDERS" && tgtOut === 0) {
|
|
1669
|
+
foldedIds.add(tgt.id);
|
|
1670
|
+
}
|
|
1671
|
+
}
|
|
1672
|
+
const reachableFromEntry = new Set();
|
|
1673
|
+
const queue = [...entryIds];
|
|
1674
|
+
for (const id of entryIds)
|
|
1675
|
+
reachableFromEntry.add(id);
|
|
1676
|
+
while (queue.length > 0) {
|
|
1677
|
+
const curr = queue.shift();
|
|
1678
|
+
for (const tgtId of index.flowOutTargetsBySource.get(curr) ?? []) {
|
|
1679
|
+
if (!reachableFromEntry.has(tgtId)) {
|
|
1680
|
+
reachableFromEntry.add(tgtId);
|
|
1681
|
+
queue.push(tgtId);
|
|
1682
|
+
}
|
|
1683
|
+
}
|
|
1684
|
+
}
|
|
1685
|
+
// 2. Dominant canonical repository wiring patterns ([PAT-MCP-09])
|
|
1686
|
+
const contractPatternCounts = new Map();
|
|
1687
|
+
const resolvedEdgePatternCounts = new Map();
|
|
1688
|
+
for (const n of index.nodeById.values()) {
|
|
1689
|
+
if (n.type === "CONTRACT" && n.patternId) {
|
|
1690
|
+
contractPatternCounts.set(n.patternId, (contractPatternCounts.get(n.patternId) ?? 0) + 1);
|
|
1691
|
+
}
|
|
1692
|
+
}
|
|
1693
|
+
for (const e of graph.edges) {
|
|
1694
|
+
if (e.targetId && e.patternId) {
|
|
1695
|
+
resolvedEdgePatternCounts.set(e.patternId, (resolvedEdgePatternCounts.get(e.patternId) ?? 0) + 1);
|
|
1696
|
+
}
|
|
1697
|
+
}
|
|
1698
|
+
const topContractPatterns = [...contractPatternCounts.entries()]
|
|
1699
|
+
.sort((a, b) => b[1] - a[1])
|
|
1700
|
+
.slice(0, 6)
|
|
1701
|
+
.map(([patternId, count]) => ({ patternId, count }));
|
|
1702
|
+
const topEdgePatterns = [...resolvedEdgePatternCounts.entries()]
|
|
1703
|
+
.sort((a, b) => b[1] - a[1])
|
|
1704
|
+
.slice(0, 6)
|
|
1705
|
+
.map(([patternId, count]) => ({ patternId, count }));
|
|
1706
|
+
// 3. Orphan contracts, Dead-End Ingress, Opaque Contracts, Unresolved Hotspots
|
|
1707
|
+
const orphanContractsAll = [];
|
|
1708
|
+
const deadEndIngressAll = [];
|
|
1709
|
+
const opaqueContractsAll = [];
|
|
1710
|
+
const unresolvedHotspotsAll = [];
|
|
1711
|
+
// v5 Loop 1/3: every signal instance, clustered by deterministic shape key after the scan.
|
|
1712
|
+
const signalInstances = [];
|
|
1713
|
+
for (const node of index.nodeById.values()) {
|
|
1714
|
+
if (isHiddenNode(node))
|
|
1715
|
+
continue;
|
|
1716
|
+
if (!matchesPkg(node.id))
|
|
1717
|
+
continue;
|
|
1718
|
+
const summaryRef = toNodeSummaryRef(node, index.resolveNodePkg);
|
|
1719
|
+
const inDeg = index.flowInSourcesByTarget.get(node.id)?.length ?? 0;
|
|
1720
|
+
const outDeg = index.flowOutTargetsBySource.get(node.id)?.length ?? 0;
|
|
1721
|
+
const unresolved = index.unresolvedCallsByNodeId.get(node.id) ?? [];
|
|
1722
|
+
const meta = parseNodeMeta(node);
|
|
1723
|
+
const astCallCount = typeof meta.astCallCount === "number" ? meta.astCallCount : 0;
|
|
1724
|
+
// Dead-End Ingress ([PAT-VIS-07])
|
|
1725
|
+
if (INGRESS_ENTITY_TYPES.has(node.entityType) &&
|
|
1726
|
+
node.entityType !== "NEXTJS_LAYOUT" &&
|
|
1727
|
+
outDeg === 0) {
|
|
1728
|
+
deadEndIngressAll.push({
|
|
1729
|
+
node: summaryRef,
|
|
1730
|
+
agentReadinessOpportunity: `Entry point '${summaryRef.label}' has 0 resolved outgoing edges on the map. ` +
|
|
1731
|
+
`If it delegates to an inline handler or dynamic dispatcher, extract or import a named service/helper contract so agents and the visualizer can trace the full request story.`,
|
|
1732
|
+
});
|
|
1733
|
+
}
|
|
1734
|
+
// Opaque Contracts ([PAT-VIS-15]: astCallCount > 0 && resolvedOutDegree === 0)
|
|
1735
|
+
if (node.type === "CONTRACT" &&
|
|
1736
|
+
!NON_EXECUTABLE_CONTRACT_ENTITY_TYPES.has(node.entityType) &&
|
|
1737
|
+
outDeg === 0 &&
|
|
1738
|
+
(astCallCount > 0 || unresolved.length > 0) &&
|
|
1739
|
+
unresolved.length > 0) {
|
|
1740
|
+
opaqueContractsAll.push({
|
|
1741
|
+
node: summaryRef,
|
|
1742
|
+
astCallCount: Math.max(astCallCount, unresolved.length),
|
|
1743
|
+
unresolvedCallCount: unresolved.length,
|
|
1744
|
+
unresolvedCalls: unresolved,
|
|
1745
|
+
agentReadinessOpportunity: `Contract '${summaryRef.label}' executes ${Math.max(astCallCount, unresolved.length)} call(s) in its body but resolves 0 outgoing structural edges (OPAQUE BODY). ` +
|
|
1746
|
+
`Aligning its dynamic receiver or callback invocation to direct module imports or factory-typed instances will illuminate its downstream path on the Chomp map. Verify via chomp_get_diff.`,
|
|
1747
|
+
});
|
|
1748
|
+
}
|
|
1749
|
+
// Unresolved Call Hotspots ([PAT-VIS-15], [PAT-MCP-09])
|
|
1750
|
+
if (unresolved.length > 0) {
|
|
1751
|
+
for (const u of unresolved) {
|
|
1752
|
+
signalInstances.push({
|
|
1753
|
+
nodeId: node.id,
|
|
1754
|
+
name: u.name,
|
|
1755
|
+
shapeKey: u.shapeKey,
|
|
1756
|
+
signal: u.reason === "opaque-body" ? "OPAQUE_BODY" : "UNRESOLVED_CALL",
|
|
1757
|
+
filePath: u.filePath,
|
|
1758
|
+
lineNumber: u.lineNumber,
|
|
1759
|
+
});
|
|
1760
|
+
}
|
|
1761
|
+
const sampleNames = unresolved
|
|
1762
|
+
.slice(0, 3)
|
|
1763
|
+
.map((u) => u.name)
|
|
1764
|
+
.join(", ");
|
|
1765
|
+
unresolvedHotspotsAll.push({
|
|
1766
|
+
node: summaryRef,
|
|
1767
|
+
resolvedOutDegree: outDeg,
|
|
1768
|
+
unresolvedCount: unresolved.length,
|
|
1769
|
+
unresolvedCalls: unresolved,
|
|
1770
|
+
agentReadinessOpportunity: `Map Visibility Opportunity: '${summaryRef.label}' emits ${unresolved.length} unresolved call(s) (${sampleNames}). ` +
|
|
1771
|
+
`Align custom dynamic indirection or untyped receiver wrappers to this repository's dominant direct import and method call patterns, or connect them via chomp_local_shims bridges—then verify with chomp_get_diff.`,
|
|
1772
|
+
});
|
|
1773
|
+
}
|
|
1774
|
+
// Orphan Contracts ([PAT-VIS-06], [PAT-VIS-14])
|
|
1775
|
+
if (!reachableFromEntry.has(node.id) &&
|
|
1776
|
+
!foldedIds.has(node.id) &&
|
|
1777
|
+
!NON_EXECUTABLE_CONTRACT_ENTITY_TYPES.has(node.entityType) &&
|
|
1778
|
+
!(node.entityType === "EXPORTED_MODULE" && outDeg === 0)) {
|
|
1779
|
+
const unresolvedIncoming = Array.isArray(meta.unresolvedIncoming)
|
|
1780
|
+
? meta.unresolvedIncoming
|
|
1781
|
+
: [];
|
|
1782
|
+
const activeExpectedCallers = unresolvedIncoming.filter((r) => r?.reason !== "imported-but-never-invoked");
|
|
1783
|
+
const unusedImportCallers = unresolvedIncoming.filter((r) => r?.reason === "imported-but-never-invoked");
|
|
1784
|
+
const classification = activeExpectedCallers.length > 0
|
|
1785
|
+
? "UNLINKED_IMPORTED_TARGET"
|
|
1786
|
+
: unusedImportCallers.length > 0
|
|
1787
|
+
? "IMPORTED_BUT_NEVER_INVOKED"
|
|
1788
|
+
: outDeg > 0
|
|
1789
|
+
? "DISCONNECTED_SUBTREE_ROOT"
|
|
1790
|
+
: "UNREFERENCED_EXPORT";
|
|
1791
|
+
const orphanEvidence = getPrimaryEvidence(node);
|
|
1792
|
+
signalInstances.push({
|
|
1793
|
+
nodeId: node.id,
|
|
1794
|
+
name: summaryRef.label,
|
|
1795
|
+
shapeKey: orphanShapeKey(node),
|
|
1796
|
+
signal: "ORPHAN_CONTRACT",
|
|
1797
|
+
filePath: orphanEvidence.filePath,
|
|
1798
|
+
lineNumber: orphanEvidence.lineNumber,
|
|
1799
|
+
});
|
|
1800
|
+
orphanContractsAll.push({
|
|
1801
|
+
node: summaryRef,
|
|
1802
|
+
resolvedInDegree: inDeg,
|
|
1803
|
+
resolvedOutDegree: outDeg,
|
|
1804
|
+
classification,
|
|
1805
|
+
...(unresolvedIncoming.length > 0 ? { unresolvedIncoming } : {}),
|
|
1806
|
+
agentReadinessOpportunity: classification === "UNLINKED_IMPORTED_TARGET"
|
|
1807
|
+
? `'${summaryRef.label}' SHOULD BE CONNECTING: it is imported and referenced by ${activeExpectedCallers.length} caller(s) (${activeExpectedCallers.map((c) => `${c.callerName} at ${c.filePath}:${c.lineNumber} [${c.usageKind}]`).join(", ")}) with 0 resolved incoming edges (${activeExpectedCallers[0].reason}).`
|
|
1808
|
+
: classification === "IMPORTED_BUT_NEVER_INVOKED"
|
|
1809
|
+
? `'${summaryRef.label}' is imported at ${unusedImportCallers.map((c) => `${c.filePath}:${c.lineNumber}`).join(", ")}, but has 0 runtime AST invocations in those file(s) (e.g. commented-out call or unused import).`
|
|
1810
|
+
: classification === "DISCONNECTED_SUBTREE_ROOT"
|
|
1811
|
+
? `'${summaryRef.label}' calls ${outDeg} downstream contract(s) but has no incoming caller from any INGRESS or INIT_BLOCK entry point. Check if it is invoked via an unmapped dynamic dispatch table/callback or if it is a standalone utility entry.`
|
|
1812
|
+
: `'${summaryRef.label}' has 0 incoming callers and is never imported in the repository graph. Verify whether it is an external public SDK export, a newly staged helper awaiting wiring, or an unused export that can be cleaned up.`,
|
|
1813
|
+
});
|
|
1814
|
+
}
|
|
1815
|
+
}
|
|
1816
|
+
const orphanPriority = {
|
|
1817
|
+
UNLINKED_IMPORTED_TARGET: 0,
|
|
1818
|
+
IMPORTED_BUT_NEVER_INVOKED: 1,
|
|
1819
|
+
DISCONNECTED_SUBTREE_ROOT: 2,
|
|
1820
|
+
UNREFERENCED_EXPORT: 3,
|
|
1821
|
+
};
|
|
1822
|
+
orphanContractsAll.sort((a, b) => (orphanPriority[a.classification] ?? 9) -
|
|
1823
|
+
(orphanPriority[b.classification] ?? 9));
|
|
1824
|
+
unresolvedHotspotsAll.sort((a, b) => b.unresolvedCount - a.unresolvedCount);
|
|
1825
|
+
// 4. Compute System & Per-Package Health Gate Metrics
|
|
1826
|
+
const computeMetricsForSlice = (nodes, edges) => {
|
|
1827
|
+
const m = computeStructuralHealthMetrics({ nodes, edges });
|
|
1828
|
+
return {
|
|
1829
|
+
status: m.status,
|
|
1830
|
+
connectivityRate: m.connectivityRate,
|
|
1831
|
+
rawConnectivityRate: m.rawConnectivityRate,
|
|
1832
|
+
knowableConnectivityRate: m.knowableConnectivityRate,
|
|
1833
|
+
unprovableFallbackCount: m.callResolutionCounts.unprovableFallbackCount,
|
|
1834
|
+
knowableGapCount: m.callResolutionCounts.knowableGapCount,
|
|
1835
|
+
dynamicBoundaryCount: m.callResolutionCounts.dynamicBoundaryCount,
|
|
1836
|
+
platformPrimitiveCount: m.callResolutionCounts.platformPrimitiveCount,
|
|
1837
|
+
entityTypeCoverage: m.entityTypeCoverage,
|
|
1838
|
+
parentCoverage: m.parentCoverage,
|
|
1839
|
+
scopePurity: m.scopePurity,
|
|
1840
|
+
totalBoundaries: m.entityCounts.boundaries,
|
|
1841
|
+
totalContracts: m.entityCounts.contracts,
|
|
1842
|
+
totalRelationships: m.entityCounts.relationships,
|
|
1843
|
+
totalOpenConnectors: m.entityCounts.openConnectors,
|
|
1844
|
+
};
|
|
1845
|
+
};
|
|
1846
|
+
const systemMetrics = computeMetricsForSlice(graph.nodes, graph.edges);
|
|
1847
|
+
// 5. Inter-Package Seam & "Missing Glue" Diagnostics ([PAT-MCP-08], [PAT-MCP-09], [PAT-VIS-15])
|
|
1848
|
+
const unstitchedProtocolSeamsAll = detectUnstitchedProtocolSeams(graph, index, {
|
|
1849
|
+
packageName: pkgFilter,
|
|
1850
|
+
repoPath: options?.repoPath,
|
|
1851
|
+
});
|
|
1852
|
+
const initBlockConnectorLeaksAll = detectInitBlockConnectorLeaks(graph, index, {
|
|
1853
|
+
packageName: pkgFilter,
|
|
1854
|
+
});
|
|
1855
|
+
// Check if a multi-package workspace (>= 2 DEPLOYMENT_UNITs with contracts) has 0 cross-package links
|
|
1856
|
+
let crossPkgFlowEdgeCount = 0;
|
|
1857
|
+
for (const edge of graph.edges) {
|
|
1858
|
+
if (!edge.targetId)
|
|
1859
|
+
continue;
|
|
1860
|
+
if (!FLOW_EDGE_ENTITY_TYPES.has(edge.entityType))
|
|
1861
|
+
continue;
|
|
1862
|
+
const src = index.nodeById.get(edge.sourceId);
|
|
1863
|
+
const tgt = index.nodeById.get(edge.targetId);
|
|
1864
|
+
if (!src || !tgt || isHiddenNode(src) || isHiddenNode(tgt))
|
|
1865
|
+
continue;
|
|
1866
|
+
const srcPkg = index.resolveNodePkg(src.id);
|
|
1867
|
+
const tgtPkg = index.resolveNodePkg(tgt.id);
|
|
1868
|
+
if (srcPkg && tgtPkg && srcPkg !== tgtPkg) {
|
|
1869
|
+
crossPkgFlowEdgeCount++;
|
|
1870
|
+
}
|
|
1871
|
+
}
|
|
1872
|
+
const activeDuSummaries = [];
|
|
1873
|
+
for (const [pkg, duNode] of index.deploymentUnitsByPkg.entries()) {
|
|
1874
|
+
if (pkgFilter &&
|
|
1875
|
+
!packageMatchesFilter(pkg, index.pathPrefixByPkg.get(pkg), pkgFilter)) {
|
|
1876
|
+
continue;
|
|
1877
|
+
}
|
|
1878
|
+
const contractCount = graph.nodes.filter((n) => n.type === "CONTRACT" &&
|
|
1879
|
+
!isHiddenNode(n) &&
|
|
1880
|
+
index.resolveNodePkg(n.id) === pkg).length;
|
|
1881
|
+
if (contractCount > 0) {
|
|
1882
|
+
activeDuSummaries.push({
|
|
1883
|
+
packageName: pkg,
|
|
1884
|
+
boundaryId: duNode.id,
|
|
1885
|
+
packagePath: index.pathPrefixByPkg.get(pkg),
|
|
1886
|
+
contractCount,
|
|
1887
|
+
});
|
|
1888
|
+
}
|
|
1889
|
+
}
|
|
1890
|
+
const isolatedDiagList = [];
|
|
1891
|
+
if (activeDuSummaries.length >= 2 && crossPkgFlowEdgeCount === 0) {
|
|
1892
|
+
const pkgList = activeDuSummaries.map((p) => p.packageName).join(", ");
|
|
1893
|
+
const isoDesc = `Multi-package workspace has ${activeDuSummaries.length} DEPLOYMENT_UNIT packages with contracts (${pkgList}) ` +
|
|
1894
|
+
`but 0 cross-package structural links (crossPackageLinkCount === 0; all packages are ISOLATED_PACKAGE).`;
|
|
1895
|
+
const isoGuidance = `Isolated Deployment Units ([PAT-MCP-08], [PAT-MCP-09]): Packages [${pkgList}] have 0 resolved cross-package edges on the map. ` +
|
|
1896
|
+
`If they communicate over HTTP/RPC/IPC or workspace barrel re-exports, inspect 'unstitchedProtocolSeams' or configure cross-package client/route conventions in chomp.config.json so the end-to-end inter-package bridge is visible, then verify with chomp_get_diff.`;
|
|
1897
|
+
isolatedDiagList.push({
|
|
1898
|
+
kind: "ISOLATED_DEPLOYMENT_UNITS",
|
|
1899
|
+
ruleId: "ISOLATED_DEPLOYMENT_UNITS",
|
|
1900
|
+
severity: "ADVISORY",
|
|
1901
|
+
isolatedPackages: activeDuSummaries,
|
|
1902
|
+
crossPackageLinkCount: 0,
|
|
1903
|
+
description: isoDesc,
|
|
1904
|
+
agentReadinessOpportunity: isoGuidance,
|
|
1905
|
+
agentReadinessGuidance: isoGuidance,
|
|
1906
|
+
});
|
|
1907
|
+
}
|
|
1908
|
+
const shadowedDbReceptorsAll = detectShadowedDbReceptors(graph, index, {
|
|
1909
|
+
packageName: pkgFilter,
|
|
1910
|
+
});
|
|
1911
|
+
const seamDiagnosticsAll = [
|
|
1912
|
+
...isolatedDiagList,
|
|
1913
|
+
...unstitchedProtocolSeamsAll,
|
|
1914
|
+
...initBlockConnectorLeaksAll,
|
|
1915
|
+
...shadowedDbReceptorsAll,
|
|
1916
|
+
];
|
|
1917
|
+
const packageSummaries = [];
|
|
1918
|
+
for (const [pkg, duNode] of index.deploymentUnitsByPkg.entries()) {
|
|
1919
|
+
if (pkgFilter &&
|
|
1920
|
+
!packageMatchesFilter(pkg, index.pathPrefixByPkg.get(pkg), pkgFilter)) {
|
|
1921
|
+
continue;
|
|
1922
|
+
}
|
|
1923
|
+
const pkgNodes = graph.nodes.filter((n) => index.resolveNodePkg(n.id) === pkg);
|
|
1924
|
+
const pkgEdges = graph.edges.filter((e) => index.resolveNodePkg(e.sourceId) === pkg);
|
|
1925
|
+
const m = computeMetricsForSlice(pkgNodes, pkgEdges);
|
|
1926
|
+
const pkgOrphans = orphanContractsAll.filter((o) => o.node.packageName === pkg).length;
|
|
1927
|
+
const pkgHotspots = unresolvedHotspotsAll.filter((h) => h.node.packageName === pkg);
|
|
1928
|
+
const pkgUnresolvedCalls = pkgHotspots.reduce((acc, h) => acc + h.unresolvedCount, 0);
|
|
1929
|
+
const pkgProtocolSeams = unstitchedProtocolSeamsAll.filter((s) => s.clientPackage === pkg || s.serverPackage === pkg).length;
|
|
1930
|
+
const pkgInitLeaks = initBlockConnectorLeaksAll.filter((l) => l.packageName === pkg).length;
|
|
1931
|
+
packageSummaries.push({
|
|
1932
|
+
packageName: pkg,
|
|
1933
|
+
boundaryId: duNode.id,
|
|
1934
|
+
rawName: duNode.name,
|
|
1935
|
+
packagePath: index.pathPrefixByPkg.get(pkg),
|
|
1936
|
+
...m,
|
|
1937
|
+
orphanContractCount: pkgOrphans,
|
|
1938
|
+
unresolvedHotspotCount: pkgHotspots.length,
|
|
1939
|
+
unresolvedCallCount: pkgUnresolvedCalls,
|
|
1940
|
+
unstitchedProtocolSeamCount: pkgProtocolSeams,
|
|
1941
|
+
initBlockConnectorLeakCount: pkgInitLeaks,
|
|
1942
|
+
});
|
|
1943
|
+
}
|
|
1944
|
+
const totalUnresolvedCalls = unresolvedHotspotsAll.reduce((sum, h) => sum + h.unresolvedCount, 0);
|
|
1945
|
+
const recommendedHighlightNodeIds = [];
|
|
1946
|
+
for (const h of unresolvedHotspotsAll) {
|
|
1947
|
+
if (recommendedHighlightNodeIds.length < 15) {
|
|
1948
|
+
recommendedHighlightNodeIds.push(h.node.id);
|
|
1949
|
+
}
|
|
1950
|
+
}
|
|
1951
|
+
for (const seam of unstitchedProtocolSeamsAll) {
|
|
1952
|
+
if (recommendedHighlightNodeIds.length < 15 &&
|
|
1953
|
+
!recommendedHighlightNodeIds.includes(seam.clientConnector.id)) {
|
|
1954
|
+
recommendedHighlightNodeIds.push(seam.clientConnector.id);
|
|
1955
|
+
}
|
|
1956
|
+
for (const r of seam.candidateServerRoutes) {
|
|
1957
|
+
if (recommendedHighlightNodeIds.length < 15 &&
|
|
1958
|
+
!recommendedHighlightNodeIds.includes(r.node.id)) {
|
|
1959
|
+
recommendedHighlightNodeIds.push(r.node.id);
|
|
1960
|
+
}
|
|
1961
|
+
}
|
|
1962
|
+
}
|
|
1963
|
+
for (const leak of initBlockConnectorLeaksAll) {
|
|
1964
|
+
if (recommendedHighlightNodeIds.length < 15 &&
|
|
1965
|
+
!recommendedHighlightNodeIds.includes(leak.initBlockNode.id)) {
|
|
1966
|
+
recommendedHighlightNodeIds.push(leak.initBlockNode.id);
|
|
1967
|
+
}
|
|
1968
|
+
for (const c of leak.deadEndContracts) {
|
|
1969
|
+
if (recommendedHighlightNodeIds.length < 15 &&
|
|
1970
|
+
!recommendedHighlightNodeIds.includes(c.id)) {
|
|
1971
|
+
recommendedHighlightNodeIds.push(c.id);
|
|
1972
|
+
}
|
|
1973
|
+
}
|
|
1974
|
+
}
|
|
1975
|
+
for (const d of deadEndIngressAll) {
|
|
1976
|
+
if (recommendedHighlightNodeIds.length < 15 &&
|
|
1977
|
+
!recommendedHighlightNodeIds.includes(d.node.id)) {
|
|
1978
|
+
recommendedHighlightNodeIds.push(d.node.id);
|
|
1979
|
+
}
|
|
1980
|
+
}
|
|
1981
|
+
for (const o of orphanContractsAll) {
|
|
1982
|
+
if (recommendedHighlightNodeIds.length < 15 &&
|
|
1983
|
+
!recommendedHighlightNodeIds.includes(o.node.id)) {
|
|
1984
|
+
recommendedHighlightNodeIds.push(o.node.id);
|
|
1985
|
+
}
|
|
1986
|
+
}
|
|
1987
|
+
const signalClusterReport = clusterSignalInstances(signalInstances);
|
|
1988
|
+
const allDarkFiles = findDarkFiles(graph);
|
|
1989
|
+
const darkFiles = pkgFilter
|
|
1990
|
+
? allDarkFiles.filter((fp) => {
|
|
1991
|
+
for (const [pkg, prefix] of index.pathPrefixByPkg.entries()) {
|
|
1992
|
+
if (packageMatchesFilter(pkg, prefix, pkgFilter)) {
|
|
1993
|
+
if (!prefix || prefix === "." || fp.startsWith(`${prefix}/`) || fp === prefix) {
|
|
1994
|
+
return true;
|
|
1995
|
+
}
|
|
1996
|
+
}
|
|
1997
|
+
}
|
|
1998
|
+
return false;
|
|
1999
|
+
})
|
|
2000
|
+
: allDarkFiles;
|
|
2001
|
+
const fallbackByShape = new Map();
|
|
2002
|
+
let fallbackTotal = 0;
|
|
2003
|
+
for (const e of graph.edges) {
|
|
2004
|
+
if (!isUnprovableFallback(e))
|
|
2005
|
+
continue;
|
|
2006
|
+
if (pkgFilter && !matchesPkg(e.sourceId))
|
|
2007
|
+
continue;
|
|
2008
|
+
fallbackTotal++;
|
|
2009
|
+
const sk = typeof e.metadata?.shapeKey === "string"
|
|
2010
|
+
? e.metadata.shapeKey
|
|
2011
|
+
: "unclassified";
|
|
2012
|
+
fallbackByShape.set(sk, (fallbackByShape.get(sk) ?? 0) + 1);
|
|
2013
|
+
}
|
|
2014
|
+
const lowConfidenceFallbacks = {
|
|
2015
|
+
totalCount: fallbackTotal,
|
|
2016
|
+
byShapeKey: [...fallbackByShape.entries()]
|
|
2017
|
+
.sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]))
|
|
2018
|
+
.slice(0, maxItems)
|
|
2019
|
+
.map(([shapeKey, count]) => ({ shapeKey, count })),
|
|
2020
|
+
};
|
|
2021
|
+
return {
|
|
2022
|
+
healthGate: {
|
|
2023
|
+
...systemMetrics,
|
|
2024
|
+
orphanContractCount: orphanContractsAll.length,
|
|
2025
|
+
unlinkedImportedOrphanCount: orphanContractsAll.filter((o) => o.classification === "UNLINKED_IMPORTED_TARGET").length,
|
|
2026
|
+
importedNeverInvokedOrphanCount: orphanContractsAll.filter((o) => o.classification === "IMPORTED_BUT_NEVER_INVOKED").length,
|
|
2027
|
+
unreferencedExportOrphanCount: orphanContractsAll.filter((o) => o.classification === "UNREFERENCED_EXPORT").length,
|
|
2028
|
+
deadEndIngressCount: deadEndIngressAll.length,
|
|
2029
|
+
opaqueContractCount: opaqueContractsAll.length,
|
|
2030
|
+
unresolvedHotspotCount: unresolvedHotspotsAll.length,
|
|
2031
|
+
totalUnresolvedCalls,
|
|
2032
|
+
darkFileCount: darkFiles.length,
|
|
2033
|
+
unstitchedProtocolSeamCount: unstitchedProtocolSeamsAll.length,
|
|
2034
|
+
initBlockConnectorLeakCount: initBlockConnectorLeaksAll.length,
|
|
2035
|
+
seamDiagnosticCount: seamDiagnosticsAll.length,
|
|
2036
|
+
},
|
|
2037
|
+
packages: packageSummaries,
|
|
2038
|
+
/**
|
|
2039
|
+
* Candidate pattern classes derived from deterministic shape keys (v5 Loop 1/3). A cluster is
|
|
2040
|
+
* a hypothesis about a shared extractor gap, not a verdict: it becomes a ledger row only after
|
|
2041
|
+
* a human/AI names and approves it. `unclassified` instances carry no shape key (unknown).
|
|
2042
|
+
*/
|
|
2043
|
+
signalClusters: {
|
|
2044
|
+
totalClusters: signalClusterReport.clusters.length,
|
|
2045
|
+
clusters: signalClusterReport.clusters.slice(0, maxItems),
|
|
2046
|
+
unclassified: signalClusterReport.unclassified,
|
|
2047
|
+
},
|
|
2048
|
+
lowConfidenceFallbacks,
|
|
2049
|
+
darkFiles: darkFiles.slice(0, maxItems),
|
|
2050
|
+
canonicalPatterns: {
|
|
2051
|
+
topContractPatterns,
|
|
2052
|
+
topEdgePatterns,
|
|
2053
|
+
note: "All diagnostics below are framed as Agent-Readiness / Map Visibility opportunities ([PAT-MCP-09]) to help align bespoke dynamic indirections to the repository's canonical static patterns.",
|
|
2054
|
+
},
|
|
2055
|
+
unstitchedProtocolSeams: unstitchedProtocolSeamsAll.slice(0, maxItems),
|
|
2056
|
+
initBlockConnectorLeaks: initBlockConnectorLeaksAll.slice(0, maxItems),
|
|
2057
|
+
seamDiagnostics: seamDiagnosticsAll.slice(0, maxItems),
|
|
2058
|
+
unresolvedHotspots: unresolvedHotspotsAll.slice(0, maxItems),
|
|
2059
|
+
opaqueContracts: opaqueContractsAll.slice(0, maxItems),
|
|
2060
|
+
deadEndIngress: deadEndIngressAll.slice(0, maxItems),
|
|
2061
|
+
orphanContracts: orphanContractsAll.slice(0, maxItems),
|
|
2062
|
+
recommendedHighlightNodeIds,
|
|
2063
|
+
};
|
|
2064
|
+
}
|
|
2065
|
+
/**
|
|
2066
|
+
* `chomp_find_redundancies` implementation ([PAT-MCP-08], [PAT-MCP-09]).
|
|
2067
|
+
*
|
|
2068
|
+
* Detects pass-through middlemen, parallel/duplicate story sequences,
|
|
2069
|
+
* duplicate contract names across files/packages, and outlier wiring patterns.
|
|
2070
|
+
*/
|
|
2071
|
+
export function findGraphRedundancies(graph, options) {
|
|
2072
|
+
const index = buildGraphIndex(graph);
|
|
2073
|
+
const maxItems = Math.max(1, Math.min(options?.limit ?? 25, 100));
|
|
2074
|
+
const pkgFilter = options?.packageName?.trim();
|
|
2075
|
+
const matchesPkg = (nodeId) => {
|
|
2076
|
+
if (!pkgFilter)
|
|
2077
|
+
return true;
|
|
2078
|
+
const pkg = index.resolveNodePkg(nodeId);
|
|
2079
|
+
const node = index.nodeById.get(nodeId);
|
|
2080
|
+
const ev = node ? getPrimaryEvidence(node) : {};
|
|
2081
|
+
return packageMatchesFilter(pkg, ev.filePath, pkgFilter);
|
|
2082
|
+
};
|
|
2083
|
+
// 1. Pass-Through Middlemen (1-to-1 relay contracts with no side-effects)
|
|
2084
|
+
const passThroughMiddlemen = [];
|
|
2085
|
+
for (const node of index.nodeById.values()) {
|
|
2086
|
+
if (node.type !== "CONTRACT")
|
|
2087
|
+
continue;
|
|
2088
|
+
if (isHiddenNode(node))
|
|
2089
|
+
continue;
|
|
2090
|
+
if (INGRESS_ENTITY_TYPES.has(node.entityType))
|
|
2091
|
+
continue;
|
|
2092
|
+
if (NON_EXECUTABLE_CONTRACT_ENTITY_TYPES.has(node.entityType))
|
|
2093
|
+
continue;
|
|
2094
|
+
if (node.entityType === "EXPORTED_MODULE")
|
|
2095
|
+
continue;
|
|
2096
|
+
if (!matchesPkg(node.id))
|
|
2097
|
+
continue;
|
|
2098
|
+
const callers = index.flowInSourcesByTarget.get(node.id) ?? [];
|
|
2099
|
+
const targets = index.flowOutTargetsBySource.get(node.id) ?? [];
|
|
2100
|
+
const unresolved = index.unresolvedCallsByNodeId.get(node.id) ?? [];
|
|
2101
|
+
if (callers.length >= 1 && targets.length === 1 && unresolved.length === 0) {
|
|
2102
|
+
const targetNode = index.nodeById.get(targets[0]);
|
|
2103
|
+
if (!targetNode || targetNode.type !== "CONTRACT")
|
|
2104
|
+
continue;
|
|
2105
|
+
// Ensure no RENDERS composition or OPEN_CONNECTOR side effects
|
|
2106
|
+
const rawOutEdges = index.outEdgesBySource.get(node.id) ?? [];
|
|
2107
|
+
const hasOpenConnectorCall = rawOutEdges.some((e) => {
|
|
2108
|
+
if (!e.targetId)
|
|
2109
|
+
return false;
|
|
2110
|
+
const t = index.nodeById.get(e.targetId);
|
|
2111
|
+
return (t &&
|
|
2112
|
+
t.type === "OPEN_CONNECTOR" &&
|
|
2113
|
+
!PACKAGE_CONNECTOR_ENTITY_TYPES.has(t.entityType));
|
|
2114
|
+
});
|
|
2115
|
+
const isRenderRelay = rawOutEdges.some((e) => e.targetId === targetNode.id && e.entityType === "RENDERS");
|
|
2116
|
+
if (hasOpenConnectorCall || isRenderRelay)
|
|
2117
|
+
continue;
|
|
2118
|
+
const nodeRef = toNodeSummaryRef(node, index.resolveNodePkg);
|
|
2119
|
+
const targetRef = toNodeSummaryRef(targetNode, index.resolveNodePkg);
|
|
2120
|
+
const callerRefs = callers
|
|
2121
|
+
.map((cId) => index.nodeById.get(cId))
|
|
2122
|
+
.filter((c) => Boolean(c))
|
|
2123
|
+
.map((c) => toNodeSummaryRef(c, index.resolveNodePkg));
|
|
2124
|
+
const crossesPkg = nodeRef.packageName !== targetRef.packageName;
|
|
2125
|
+
passThroughMiddlemen.push({
|
|
2126
|
+
middleman: nodeRef,
|
|
2127
|
+
callers: callerRefs,
|
|
2128
|
+
singleTarget: targetRef,
|
|
2129
|
+
crossesPackageBoundary: crossesPkg,
|
|
2130
|
+
agentReadinessGuidance: crossesPkg
|
|
2131
|
+
? `'${nodeRef.label}' in '${nodeRef.packageName}' is a 1-to-1 cross-package adapter delegating directly to '${targetRef.label}' in '${targetRef.packageName}'. Keep if it serves as an intentional package boundary facade; otherwise callers can import '${targetRef.label}' directly.`
|
|
2132
|
+
: `'${nodeRef.label}' is an intra-package pass-through middleman in '${nodeRef.packageName}' that only forwards to '${targetRef.label}' with no branching or side effects. Consider wiring its ${callerRefs.length} caller(s) directly to '${targetRef.label}' to simplify the execution story.`,
|
|
2133
|
+
});
|
|
2134
|
+
}
|
|
2135
|
+
}
|
|
2136
|
+
// 2. Parallel / Duplicate Story Sequences (Contracts invoking the exact same >= 2 downstream target set)
|
|
2137
|
+
const callersByCalleeSignature = new Map();
|
|
2138
|
+
for (const node of index.nodeById.values()) {
|
|
2139
|
+
if (isHiddenNode(node))
|
|
2140
|
+
continue;
|
|
2141
|
+
if (node.entityType === INIT_BLOCK_ENTITY_TYPE)
|
|
2142
|
+
continue;
|
|
2143
|
+
const targets = index.flowOutTargetsBySource.get(node.id) ?? [];
|
|
2144
|
+
if (targets.length < 2)
|
|
2145
|
+
continue;
|
|
2146
|
+
const sortedTargets = [...targets].sort();
|
|
2147
|
+
const sig = sortedTargets.join("::");
|
|
2148
|
+
let list = callersByCalleeSignature.get(sig);
|
|
2149
|
+
if (!list) {
|
|
2150
|
+
list = [];
|
|
2151
|
+
callersByCalleeSignature.set(sig, list);
|
|
2152
|
+
}
|
|
2153
|
+
list.push(node);
|
|
2154
|
+
}
|
|
2155
|
+
const duplicateStorySequences = [];
|
|
2156
|
+
for (const [sig, callerNodes] of callersByCalleeSignature.entries()) {
|
|
2157
|
+
if (callerNodes.length < 2)
|
|
2158
|
+
continue;
|
|
2159
|
+
if (pkgFilter && !callerNodes.some((c) => matchesPkg(c.id)))
|
|
2160
|
+
continue;
|
|
2161
|
+
const targetIds = sig.split("::");
|
|
2162
|
+
const targetRefs = targetIds
|
|
2163
|
+
.map((id) => index.nodeById.get(id))
|
|
2164
|
+
.filter((t) => Boolean(t))
|
|
2165
|
+
.map((t) => toNodeSummaryRef(t, index.resolveNodePkg));
|
|
2166
|
+
const callerRefs = callerNodes.map((c) => toNodeSummaryRef(c, index.resolveNodePkg));
|
|
2167
|
+
const pkgSet = new Set(callerRefs.map((c) => c.packageName));
|
|
2168
|
+
const samePackage = pkgSet.size === 1;
|
|
2169
|
+
const targetLabels = targetRefs.map((t) => t.label).join(" -> ");
|
|
2170
|
+
duplicateStorySequences.push({
|
|
2171
|
+
sharedCalleeCount: targetRefs.length,
|
|
2172
|
+
samePackage,
|
|
2173
|
+
parallelCallers: callerRefs,
|
|
2174
|
+
sharedTargets: targetRefs,
|
|
2175
|
+
patternAlignmentGuidance: callerRefs.every((c) => INGRESS_ENTITY_TYPES.has(c.entityType))
|
|
2176
|
+
? `Canonical Peer Ingress Pattern: ${callerRefs.length} entry points (${callerRefs.map((c) => c.label).join(", ")}) execute the identical downstream sequence [${targetLabels}]. If shared pre/post-processing grows, consider extracting a shared helper contract.`
|
|
2177
|
+
: `${callerRefs.length} contracts (${callerRefs.map((c) => c.label).join(", ")}) invoke the exact same ${targetRefs.length} downstream targets [${targetLabels}]. Check if these parallel orchestrators can be consolidated into a single canonical workflow function.`,
|
|
2178
|
+
});
|
|
2179
|
+
}
|
|
2180
|
+
duplicateStorySequences.sort((a, b) => b.parallelCallers.length * b.sharedCalleeCount -
|
|
2181
|
+
a.parallelCallers.length * a.sharedCalleeCount);
|
|
2182
|
+
// 3. Duplicate Contract Names across multiple files/packages
|
|
2183
|
+
const contractsByCleanLabel = new Map();
|
|
2184
|
+
const IGNORED_GENERIC_LABELS = new Set([
|
|
2185
|
+
"Module Export (Default)",
|
|
2186
|
+
"anonymous",
|
|
2187
|
+
"default",
|
|
2188
|
+
"POST",
|
|
2189
|
+
"GET",
|
|
2190
|
+
"PUT",
|
|
2191
|
+
"DELETE",
|
|
2192
|
+
"PATCH",
|
|
2193
|
+
]);
|
|
2194
|
+
for (const node of index.nodeById.values()) {
|
|
2195
|
+
if (node.type !== "CONTRACT")
|
|
2196
|
+
continue;
|
|
2197
|
+
if (isHiddenNode(node))
|
|
2198
|
+
continue;
|
|
2199
|
+
if (NON_EXECUTABLE_CONTRACT_ENTITY_TYPES.has(node.entityType))
|
|
2200
|
+
continue;
|
|
2201
|
+
if (node.entityType === "PUBLIC_METHOD" ||
|
|
2202
|
+
node.entityType === "NEXTJS_PAGE" ||
|
|
2203
|
+
node.entityType === "NEXTJS_LAYOUT" ||
|
|
2204
|
+
node.entityType === "HTTP_ENDPOINT" ||
|
|
2205
|
+
node.entityType === "API_ENDPOINT") {
|
|
2206
|
+
continue;
|
|
2207
|
+
}
|
|
2208
|
+
const label = cleanNodeLabel(node.name);
|
|
2209
|
+
if (!label || label.length < 3 || IGNORED_GENERIC_LABELS.has(label)) {
|
|
2210
|
+
continue;
|
|
2211
|
+
}
|
|
2212
|
+
let list = contractsByCleanLabel.get(label);
|
|
2213
|
+
if (!list) {
|
|
2214
|
+
list = [];
|
|
2215
|
+
contractsByCleanLabel.set(label, list);
|
|
2216
|
+
}
|
|
2217
|
+
list.push(node);
|
|
2218
|
+
}
|
|
2219
|
+
const duplicateSymbols = [];
|
|
2220
|
+
for (const [symbolName, nodes] of contractsByCleanLabel.entries()) {
|
|
2221
|
+
if (nodes.length < 2)
|
|
2222
|
+
continue;
|
|
2223
|
+
if (pkgFilter && !nodes.some((n) => matchesPkg(n.id)))
|
|
2224
|
+
continue;
|
|
2225
|
+
const refs = nodes.map((n) => toNodeSummaryRef(n, index.resolveNodePkg));
|
|
2226
|
+
const distinctFiles = new Set(refs.map((r) => r.filePath ?? r.id));
|
|
2227
|
+
if (distinctFiles.size < 2)
|
|
2228
|
+
continue;
|
|
2229
|
+
const distinctPkgs = new Set(refs.map((r) => r.packageName));
|
|
2230
|
+
duplicateSymbols.push({
|
|
2231
|
+
symbolName,
|
|
2232
|
+
instanceCount: refs.length,
|
|
2233
|
+
crossPackage: distinctPkgs.size > 1,
|
|
2234
|
+
instances: refs,
|
|
2235
|
+
consolidationGuidance: distinctPkgs.size > 1
|
|
2236
|
+
? `Symbol '${symbolName}' is defined in ${refs.length} places across packages (${[...distinctPkgs].join(", ")}). Consider centralizing shared domain logic into a shared core or utility package.`
|
|
2237
|
+
: `Symbol '${symbolName}' is duplicated across ${refs.length} files within '${[...distinctPkgs][0]}'. Consider consolidating into a single shared module export.`,
|
|
2238
|
+
});
|
|
2239
|
+
}
|
|
2240
|
+
duplicateSymbols.sort((a, b) => b.instanceCount - a.instanceCount);
|
|
2241
|
+
// 4. Package Pattern Alignment & Outlier Analysis ([PAT-MCP-09])
|
|
2242
|
+
// Group peer INGRESS / API_ENDPOINT contracts per package and compare their target patterns
|
|
2243
|
+
const patternAlignmentOpportunities = [];
|
|
2244
|
+
const ingressByPkgAndType = new Map();
|
|
2245
|
+
for (const node of index.nodeById.values()) {
|
|
2246
|
+
if (!INGRESS_ENTITY_TYPES.has(node.entityType))
|
|
2247
|
+
continue;
|
|
2248
|
+
const pkg = index.resolveNodePkg(node.id);
|
|
2249
|
+
if (!pkg)
|
|
2250
|
+
continue;
|
|
2251
|
+
if (pkgFilter && !matchesPkg(node.id))
|
|
2252
|
+
continue;
|
|
2253
|
+
const key = `${pkg}::${node.entityType}`;
|
|
2254
|
+
let list = ingressByPkgAndType.get(key);
|
|
2255
|
+
if (!list) {
|
|
2256
|
+
list = [];
|
|
2257
|
+
ingressByPkgAndType.set(key, list);
|
|
2258
|
+
}
|
|
2259
|
+
list.push(node);
|
|
2260
|
+
}
|
|
2261
|
+
for (const [key, peers] of ingressByPkgAndType.entries()) {
|
|
2262
|
+
if (peers.length < 3)
|
|
2263
|
+
continue;
|
|
2264
|
+
const [pkg, entityType] = key.split("::");
|
|
2265
|
+
// Determine which downstream target IDs are called by the majority (>= 50%) of peers
|
|
2266
|
+
const targetFrequency = new Map();
|
|
2267
|
+
for (const p of peers) {
|
|
2268
|
+
const tgts = index.flowOutTargetsBySource.get(p.id) ?? [];
|
|
2269
|
+
for (const tId of tgts) {
|
|
2270
|
+
targetFrequency.set(tId, (targetFrequency.get(tId) ?? 0) + 1);
|
|
2271
|
+
}
|
|
2272
|
+
}
|
|
2273
|
+
const canonicalTargetIds = [...targetFrequency.entries()]
|
|
2274
|
+
.filter(([, count]) => count >= Math.ceil(peers.length * 0.5))
|
|
2275
|
+
.map(([tId]) => tId);
|
|
2276
|
+
if (canonicalTargetIds.length === 0)
|
|
2277
|
+
continue;
|
|
2278
|
+
const canonicalTargetLabels = canonicalTargetIds
|
|
2279
|
+
.map((id) => index.nodeById.get(id))
|
|
2280
|
+
.filter((n) => Boolean(n))
|
|
2281
|
+
.map((n) => cleanNodeLabel(n.name));
|
|
2282
|
+
for (const p of peers) {
|
|
2283
|
+
const tgts = index.flowOutTargetsBySource.get(p.id) ?? [];
|
|
2284
|
+
const usesCanonical = canonicalTargetIds.some((cId) => tgts.includes(cId));
|
|
2285
|
+
if (!usesCanonical) {
|
|
2286
|
+
const tgtLabels = tgts
|
|
2287
|
+
.map((id) => index.nodeById.get(id))
|
|
2288
|
+
.filter((n) => Boolean(n))
|
|
2289
|
+
.map((n) => cleanNodeLabel(n.name));
|
|
2290
|
+
const pRef = toNodeSummaryRef(p, index.resolveNodePkg);
|
|
2291
|
+
patternAlignmentOpportunities.push({
|
|
2292
|
+
packageName: pkg,
|
|
2293
|
+
peerGroupType: entityType,
|
|
2294
|
+
dominantPatternDescription: `Majority of ${entityType} contracts in '${pkg}' wire through [${canonicalTargetLabels.join(", ")}]`,
|
|
2295
|
+
outlierNode: pRef,
|
|
2296
|
+
observedBehavior: tgtLabels.length > 0
|
|
2297
|
+
? `Wires to [${tgtLabels.join(", ")}] instead of the package's dominant [${canonicalTargetLabels.join(", ")}] pipeline`
|
|
2298
|
+
: `Has 0 resolved downstream calls`,
|
|
2299
|
+
agentReadinessGuidance: `Pattern Alignment Opportunity ([PAT-MCP-09]): '${pRef.label}' deviates from its ${peers.length - 1} sibling ${entityType} contracts in '${pkg}'. ` +
|
|
2300
|
+
`If it uses subprocess execution or sidecar files where siblings use direct library/storage contracts, aligning it to the canonical [${canonicalTargetLabels.join(", ")}] pattern improves end-to-end map traceability.`,
|
|
2301
|
+
});
|
|
2302
|
+
}
|
|
2303
|
+
}
|
|
2304
|
+
}
|
|
2305
|
+
return {
|
|
2306
|
+
summary: {
|
|
2307
|
+
passThroughMiddlemenCount: passThroughMiddlemen.length,
|
|
2308
|
+
duplicateStorySequenceGroups: duplicateStorySequences.length,
|
|
2309
|
+
duplicateSymbolCount: duplicateSymbols.length,
|
|
2310
|
+
patternAlignmentOpportunityCount: patternAlignmentOpportunities.length,
|
|
2311
|
+
},
|
|
2312
|
+
passThroughMiddlemen: passThroughMiddlemen.slice(0, maxItems),
|
|
2313
|
+
duplicateStorySequences: duplicateStorySequences.slice(0, maxItems),
|
|
2314
|
+
duplicateSymbols: duplicateSymbols.slice(0, maxItems),
|
|
2315
|
+
patternAlignmentOpportunities: patternAlignmentOpportunities.slice(0, maxItems),
|
|
2316
|
+
};
|
|
2317
|
+
}
|
|
2318
|
+
/**
|
|
2319
|
+
* `chomp_check_boundaries` implementation ([PAT-MCP-08], [PAT-MCP-09]).
|
|
2320
|
+
*
|
|
2321
|
+
* Evaluates package dependency directionality, topological tiers,
|
|
2322
|
+
* package-level and contract-level circular dependencies, boundary isolation rules,
|
|
2323
|
+
* and inter-package seam diagnostics (`ISOLATED_DEPLOYMENT_UNITS`,
|
|
2324
|
+
* `UNSTITCHED_PROTOCOL_SEAM`, `INIT_BLOCK_CONNECTOR_LEAK`).
|
|
2325
|
+
*/
|
|
2326
|
+
export function checkGraphBoundaries(graph, options) {
|
|
2327
|
+
const index = buildGraphIndex(graph);
|
|
2328
|
+
const pkgFilter = options?.packageName?.trim();
|
|
2329
|
+
// 1. Build cross-package dependency matrix
|
|
2330
|
+
const pairDetails = new Map();
|
|
2331
|
+
const outPkgsByPkg = new Map();
|
|
2332
|
+
const inPkgsByPkg = new Map();
|
|
2333
|
+
for (const pkg of index.deploymentUnitsByPkg.keys()) {
|
|
2334
|
+
outPkgsByPkg.set(pkg, new Set());
|
|
2335
|
+
inPkgsByPkg.set(pkg, new Set());
|
|
2336
|
+
}
|
|
2337
|
+
for (const edge of graph.edges) {
|
|
2338
|
+
if (!edge.targetId)
|
|
2339
|
+
continue;
|
|
2340
|
+
if (!FLOW_EDGE_ENTITY_TYPES.has(edge.entityType))
|
|
2341
|
+
continue;
|
|
2342
|
+
const src = index.nodeById.get(edge.sourceId);
|
|
2343
|
+
const tgt = index.nodeById.get(edge.targetId);
|
|
2344
|
+
if (!src || !tgt)
|
|
2345
|
+
continue;
|
|
2346
|
+
if (isHiddenNode(src) || isHiddenNode(tgt))
|
|
2347
|
+
continue;
|
|
2348
|
+
const srcPkg = index.resolveNodePkg(src.id);
|
|
2349
|
+
const tgtPkg = index.resolveNodePkg(tgt.id);
|
|
2350
|
+
if (!srcPkg || !tgtPkg || srcPkg === tgtPkg)
|
|
2351
|
+
continue;
|
|
2352
|
+
if (!outPkgsByPkg.has(srcPkg))
|
|
2353
|
+
outPkgsByPkg.set(srcPkg, new Set());
|
|
2354
|
+
if (!inPkgsByPkg.has(tgtPkg))
|
|
2355
|
+
inPkgsByPkg.set(tgtPkg, new Set());
|
|
2356
|
+
outPkgsByPkg.get(srcPkg).add(tgtPkg);
|
|
2357
|
+
inPkgsByPkg.get(tgtPkg).add(srcPkg);
|
|
2358
|
+
const key = `${srcPkg}::${tgtPkg}`;
|
|
2359
|
+
let list = pairDetails.get(key);
|
|
2360
|
+
if (!list) {
|
|
2361
|
+
list = [];
|
|
2362
|
+
pairDetails.set(key, list);
|
|
2363
|
+
}
|
|
2364
|
+
const ev = getPrimaryEvidence(edge);
|
|
2365
|
+
list.push({
|
|
2366
|
+
sourceNode: toNodeSummaryRef(src, index.resolveNodePkg),
|
|
2367
|
+
targetNode: toNodeSummaryRef(tgt, index.resolveNodePkg),
|
|
2368
|
+
edgeName: edge.name ?? edge.entityType,
|
|
2369
|
+
edgeType: edge.entityType,
|
|
2370
|
+
filePath: ev.filePath,
|
|
2371
|
+
lineNumber: ev.lineNumber,
|
|
2372
|
+
});
|
|
2373
|
+
}
|
|
2374
|
+
// 2. Assign topological architectural tiers to packages
|
|
2375
|
+
const packageLayers = [];
|
|
2376
|
+
const tierRankByPkg = new Map();
|
|
2377
|
+
for (const [pkg, duNode] of index.deploymentUnitsByPkg.entries()) {
|
|
2378
|
+
const outs = [...(outPkgsByPkg.get(pkg) ?? [])].sort();
|
|
2379
|
+
const ins = [...(inPkgsByPkg.get(pkg) ?? [])].sort();
|
|
2380
|
+
const isAdapterPkg = pkg === "db" ||
|
|
2381
|
+
pkg.endsWith("-db") ||
|
|
2382
|
+
pkg.endsWith("_db") ||
|
|
2383
|
+
pkg.includes("adapter");
|
|
2384
|
+
let architecturalTier;
|
|
2385
|
+
let tierRank;
|
|
2386
|
+
if (outs.length === 0 && ins.length === 0) {
|
|
2387
|
+
architecturalTier = "ISOLATED_PACKAGE";
|
|
2388
|
+
tierRank = 0;
|
|
2389
|
+
}
|
|
2390
|
+
else if (outs.length === 0 && isAdapterPkg && ins.length > 0) {
|
|
2391
|
+
architecturalTier = "INFRASTRUCTURE_ADAPTER";
|
|
2392
|
+
tierRank = 2;
|
|
2393
|
+
}
|
|
2394
|
+
else if (outs.length === 0) {
|
|
2395
|
+
architecturalTier = "FOUNDATION_CORE";
|
|
2396
|
+
tierRank = 3;
|
|
2397
|
+
}
|
|
2398
|
+
else if (ins.length === 0) {
|
|
2399
|
+
architecturalTier = "ENTRY_APPLICATION";
|
|
2400
|
+
tierRank = 0;
|
|
2401
|
+
}
|
|
2402
|
+
else if (outs.every((targetPkg) => (outPkgsByPkg.get(targetPkg)?.size ?? 0) === 0) &&
|
|
2403
|
+
isAdapterPkg) {
|
|
2404
|
+
architecturalTier = "INFRASTRUCTURE_ADAPTER";
|
|
2405
|
+
tierRank = 2;
|
|
2406
|
+
}
|
|
2407
|
+
else {
|
|
2408
|
+
architecturalTier = "SERVICE_ORCHESTRATOR";
|
|
2409
|
+
tierRank = 1;
|
|
2410
|
+
}
|
|
2411
|
+
tierRankByPkg.set(pkg, tierRank);
|
|
2412
|
+
if (!pkgFilter ||
|
|
2413
|
+
packageMatchesFilter(pkg, index.pathPrefixByPkg.get(pkg), pkgFilter)) {
|
|
2414
|
+
packageLayers.push({
|
|
2415
|
+
packageName: pkg,
|
|
2416
|
+
boundaryId: duNode.id,
|
|
2417
|
+
packagePath: index.pathPrefixByPkg.get(pkg),
|
|
2418
|
+
architecturalTier,
|
|
2419
|
+
tierRank,
|
|
2420
|
+
dependsOnPackages: outs,
|
|
2421
|
+
dependedOnByPackages: ins,
|
|
2422
|
+
});
|
|
2423
|
+
}
|
|
2424
|
+
}
|
|
2425
|
+
packageLayers.sort((a, b) => a.tierRank - b.tierRank);
|
|
2426
|
+
// 3. Detect Package-Level Circular Dependencies
|
|
2427
|
+
const packageCycles = [];
|
|
2428
|
+
const seenPkgCycleSigs = new Set();
|
|
2429
|
+
for (const startPkg of index.deploymentUnitsByPkg.keys()) {
|
|
2430
|
+
const dfsPkg = (curr, path, visited) => {
|
|
2431
|
+
for (const next of outPkgsByPkg.get(curr) ?? []) {
|
|
2432
|
+
if (next === startPkg && path.length >= 2) {
|
|
2433
|
+
const minIdx = path.reduce((best, item, idx) => (item < path[best] ? idx : best), 0);
|
|
2434
|
+
const canonical = [
|
|
2435
|
+
...path.slice(minIdx),
|
|
2436
|
+
...path.slice(0, minIdx),
|
|
2437
|
+
].join(" -> ");
|
|
2438
|
+
if (!seenPkgCycleSigs.has(canonical)) {
|
|
2439
|
+
seenPkgCycleSigs.add(canonical);
|
|
2440
|
+
packageCycles.push([...path, startPkg]);
|
|
2441
|
+
}
|
|
2442
|
+
}
|
|
2443
|
+
else if (!visited.has(next)) {
|
|
2444
|
+
visited.add(next);
|
|
2445
|
+
dfsPkg(next, [...path, next], visited);
|
|
2446
|
+
visited.delete(next);
|
|
2447
|
+
}
|
|
2448
|
+
}
|
|
2449
|
+
};
|
|
2450
|
+
dfsPkg(startPkg, [startPkg], new Set([startPkg]));
|
|
2451
|
+
}
|
|
2452
|
+
// 4. Detect Contract-Level Circular Dependencies & Self-Loops ([PAT-VIS-08])
|
|
2453
|
+
const selfLoops = [];
|
|
2454
|
+
for (const edge of graph.edges) {
|
|
2455
|
+
if (edge.targetId &&
|
|
2456
|
+
edge.sourceId === edge.targetId &&
|
|
2457
|
+
FLOW_EDGE_ENTITY_TYPES.has(edge.entityType)) {
|
|
2458
|
+
const node = index.nodeById.get(edge.sourceId);
|
|
2459
|
+
if (node && !isHiddenNode(node)) {
|
|
2460
|
+
const ev = getPrimaryEvidence(edge);
|
|
2461
|
+
selfLoops.push({
|
|
2462
|
+
node: toNodeSummaryRef(node, index.resolveNodePkg),
|
|
2463
|
+
edgeName: edge.name ?? edge.entityType,
|
|
2464
|
+
filePath: ev.filePath,
|
|
2465
|
+
lineNumber: ev.lineNumber,
|
|
2466
|
+
});
|
|
2467
|
+
}
|
|
2468
|
+
}
|
|
2469
|
+
}
|
|
2470
|
+
const contractCycles = [];
|
|
2471
|
+
const seenContractCycleSigs = new Set();
|
|
2472
|
+
const globalVisited = new Set();
|
|
2473
|
+
for (const nodeId of index.flowOutTargetsBySource.keys()) {
|
|
2474
|
+
if (globalVisited.has(nodeId) || contractCycles.length >= 20)
|
|
2475
|
+
continue;
|
|
2476
|
+
const stackSet = new Set();
|
|
2477
|
+
const pathIds = [];
|
|
2478
|
+
const dfsContract = (currId) => {
|
|
2479
|
+
if (contractCycles.length >= 20)
|
|
2480
|
+
return;
|
|
2481
|
+
globalVisited.add(currId);
|
|
2482
|
+
stackSet.add(currId);
|
|
2483
|
+
pathIds.push(currId);
|
|
2484
|
+
for (const nextId of index.flowOutTargetsBySource.get(currId) ?? []) {
|
|
2485
|
+
if (nextId === currId)
|
|
2486
|
+
continue;
|
|
2487
|
+
if (stackSet.has(nextId)) {
|
|
2488
|
+
const cycleStart = pathIds.indexOf(nextId);
|
|
2489
|
+
if (cycleStart >= 0) {
|
|
2490
|
+
const cycleSlice = pathIds.slice(cycleStart);
|
|
2491
|
+
const minIdx = cycleSlice.reduce((best, item, idx) => (item < cycleSlice[best] ? idx : best), 0);
|
|
2492
|
+
const canonical = [
|
|
2493
|
+
...cycleSlice.slice(minIdx),
|
|
2494
|
+
...cycleSlice.slice(0, minIdx),
|
|
2495
|
+
].join("::");
|
|
2496
|
+
if (!seenContractCycleSigs.has(canonical)) {
|
|
2497
|
+
seenContractCycleSigs.add(canonical);
|
|
2498
|
+
const cycleRefs = [...cycleSlice, nextId]
|
|
2499
|
+
.map((id) => index.nodeById.get(id))
|
|
2500
|
+
.filter((n) => Boolean(n))
|
|
2501
|
+
.map((n) => toNodeSummaryRef(n, index.resolveNodePkg));
|
|
2502
|
+
contractCycles.push({
|
|
2503
|
+
cycleLength: cycleSlice.length,
|
|
2504
|
+
nodes: cycleRefs,
|
|
2505
|
+
});
|
|
2506
|
+
}
|
|
2507
|
+
}
|
|
2508
|
+
}
|
|
2509
|
+
else if (!globalVisited.has(nextId)) {
|
|
2510
|
+
dfsContract(nextId);
|
|
2511
|
+
}
|
|
2512
|
+
}
|
|
2513
|
+
pathIds.pop();
|
|
2514
|
+
stackSet.delete(currId);
|
|
2515
|
+
};
|
|
2516
|
+
dfsContract(nodeId);
|
|
2517
|
+
}
|
|
2518
|
+
// 5. Check Boundary Isolation & Layer Directionality Rules
|
|
2519
|
+
const boundaryViolations = [];
|
|
2520
|
+
for (const [pairKey, details] of pairDetails.entries()) {
|
|
2521
|
+
const [srcPkg, tgtPkg] = pairKey.split("::");
|
|
2522
|
+
if (pkgFilter &&
|
|
2523
|
+
!packageMatchesFilter(srcPkg, undefined, pkgFilter) &&
|
|
2524
|
+
!packageMatchesFilter(tgtPkg, undefined, pkgFilter)) {
|
|
2525
|
+
continue;
|
|
2526
|
+
}
|
|
2527
|
+
const srcRank = tierRankByPkg.get(srcPkg) ?? 0;
|
|
2528
|
+
const tgtRank = tierRankByPkg.get(tgtPkg) ?? 0;
|
|
2529
|
+
// Rule 1: Core DB Isolation (AGENTS.md §9.1: @getchomp/core must have ZERO database imports)
|
|
2530
|
+
if (srcPkg === "core" && tgtPkg === "db") {
|
|
2531
|
+
boundaryViolations.push({
|
|
2532
|
+
ruleId: "BOUNDARY-CORE-DB-ISOLATION",
|
|
2533
|
+
severity: "VIOLATION",
|
|
2534
|
+
sourcePackage: srcPkg,
|
|
2535
|
+
targetPackage: tgtPkg,
|
|
2536
|
+
description: `'@getchomp/core' has ${details.length} direct structural dependency edge(s) into '@getchomp/db'. Core must remain 100% persistence-agnostic.`,
|
|
2537
|
+
evidence: details.slice(0, 5),
|
|
2538
|
+
agentReadinessGuidance: "Move database persistence calls out of '@getchomp/core' into '@getchomp/db' or the calling orchestrator ('@getchomp/cli' / '@getchomp/mcp').",
|
|
2539
|
+
});
|
|
2540
|
+
}
|
|
2541
|
+
else if (srcRank > tgtRank) {
|
|
2542
|
+
// Lower/foundational layer calling upward into a higher application/service layer
|
|
2543
|
+
boundaryViolations.push({
|
|
2544
|
+
ruleId: "BOUNDARY-UPWARD-LAYER-CALL",
|
|
2545
|
+
severity: "VIOLATION",
|
|
2546
|
+
sourcePackage: srcPkg,
|
|
2547
|
+
targetPackage: tgtPkg,
|
|
2548
|
+
description: `Lower-tier package '${srcPkg}' (tierRank ${srcRank}) depends upward on higher-tier package '${tgtPkg}' (tierRank ${tgtRank}).`,
|
|
2549
|
+
evidence: details.slice(0, 5),
|
|
2550
|
+
agentReadinessGuidance: `Invert the dependency between '${srcPkg}' and '${tgtPkg}' by moving shared contracts to a lower foundational package or passing callbacks/interfaces.`,
|
|
2551
|
+
});
|
|
2552
|
+
}
|
|
2553
|
+
// Check if cross-package call reaches past barrel index.ts into deep internal implementation files
|
|
2554
|
+
const deepInternalCalls = details.filter((d) => {
|
|
2555
|
+
const fp = d.targetNode.filePath;
|
|
2556
|
+
if (!fp)
|
|
2557
|
+
return false;
|
|
2558
|
+
// If a package has a src/index.ts barrel, check if target is in a nested subfolder (e.g. src/extractor/visitors/...)
|
|
2559
|
+
const relInSrc = fp.split("/src/")[1] ?? "";
|
|
2560
|
+
return relInSrc.includes("/") && !relInSrc.startsWith("adapters/");
|
|
2561
|
+
});
|
|
2562
|
+
if (deepInternalCalls.length > 0 && srcPkg !== tgtPkg) {
|
|
2563
|
+
const distinctTargets = new Map();
|
|
2564
|
+
for (const d of deepInternalCalls) {
|
|
2565
|
+
if (!distinctTargets.has(d.targetNode.id)) {
|
|
2566
|
+
distinctTargets.set(d.targetNode.id, d);
|
|
2567
|
+
}
|
|
2568
|
+
}
|
|
2569
|
+
boundaryViolations.push({
|
|
2570
|
+
ruleId: "BOUNDARY-DEEP-SUBMODULE-TARGET",
|
|
2571
|
+
severity: "ADVISORY",
|
|
2572
|
+
sourcePackage: srcPkg,
|
|
2573
|
+
targetPackage: tgtPkg,
|
|
2574
|
+
description: `'${srcPkg}' resolves to ${distinctTargets.size} contract(s) declared inside nested internal modules of '${tgtPkg}' (${[...distinctTargets.values()].map((d) => d.targetNode.label).slice(0, 4).join(", ")}).`,
|
|
2575
|
+
evidence: [...distinctTargets.values()].slice(0, 5),
|
|
2576
|
+
agentReadinessGuidance: `Verify that these target contracts remain re-exported via '${tgtPkg}/src/index.ts' so cross-package consumers rely only on '${tgtPkg}'s public barrel contract surface.`,
|
|
2577
|
+
});
|
|
2578
|
+
}
|
|
2579
|
+
}
|
|
2580
|
+
const packageDependencies = [...pairDetails.entries()]
|
|
2581
|
+
.filter(([pairKey]) => {
|
|
2582
|
+
if (!pkgFilter)
|
|
2583
|
+
return true;
|
|
2584
|
+
const [s, t] = pairKey.split("::");
|
|
2585
|
+
return (packageMatchesFilter(s, undefined, pkgFilter) ||
|
|
2586
|
+
packageMatchesFilter(t, undefined, pkgFilter));
|
|
2587
|
+
})
|
|
2588
|
+
.map(([pairKey, details]) => {
|
|
2589
|
+
const [sourcePackage, targetPackage] = pairKey.split("::");
|
|
2590
|
+
const distinctTargets = new Set(details.map((d) => d.targetNode.id));
|
|
2591
|
+
return {
|
|
2592
|
+
sourcePackage,
|
|
2593
|
+
targetPackage,
|
|
2594
|
+
edgeCount: details.length,
|
|
2595
|
+
distinctTargetContracts: distinctTargets.size,
|
|
2596
|
+
sampleEdges: details.slice(0, 5),
|
|
2597
|
+
};
|
|
2598
|
+
});
|
|
2599
|
+
// 6. Inter-Package Seam & "Missing Glue" Diagnostics ([PAT-MCP-08], [PAT-MCP-09], [PAT-VIS-15])
|
|
2600
|
+
const contractsCountByPkg = new Map();
|
|
2601
|
+
for (const n of index.nodeById.values()) {
|
|
2602
|
+
if (n.type !== "CONTRACT" || isHiddenNode(n))
|
|
2603
|
+
continue;
|
|
2604
|
+
const pkg = index.resolveNodePkg(n.id);
|
|
2605
|
+
if (!pkg)
|
|
2606
|
+
continue;
|
|
2607
|
+
contractsCountByPkg.set(pkg, (contractsCountByPkg.get(pkg) ?? 0) + 1);
|
|
2608
|
+
}
|
|
2609
|
+
const activePackageLayers = packageLayers.filter((p) => (contractsCountByPkg.get(p.packageName) ?? 0) > 0);
|
|
2610
|
+
const seamDiagnostics = [];
|
|
2611
|
+
// 6a. Isolated Package Anomaly (`ISOLATED_DEPLOYMENT_UNITS`):
|
|
2612
|
+
// Never report status: "CLEAN" when a multi-package workspace (>= 2 DEPLOYMENT_UNITs with contracts)
|
|
2613
|
+
// has crossPackageLinkCount === 0 and all packages are classified as ISOLATED_PACKAGE.
|
|
2614
|
+
if (activePackageLayers.length >= 2 &&
|
|
2615
|
+
packageDependencies.length === 0 &&
|
|
2616
|
+
activePackageLayers.every((p) => p.architecturalTier === "ISOLATED_PACKAGE")) {
|
|
2617
|
+
const pkgList = activePackageLayers.map((p) => p.packageName).join(", ");
|
|
2618
|
+
const isoDesc = `Multi-package workspace has ${activePackageLayers.length} DEPLOYMENT_UNIT packages with contracts (${pkgList}) ` +
|
|
2619
|
+
`but 0 cross-package structural links (crossPackageLinkCount === 0; all packages are ISOLATED_PACKAGE).`;
|
|
2620
|
+
const isoGuidance = `Isolated Deployment Units ([PAT-MCP-08], [PAT-MCP-09]): Packages [${pkgList}] have 0 resolved cross-package edges on the map. ` +
|
|
2621
|
+
`If they communicate over HTTP/RPC/IPC or workspace barrel re-exports, inspect 'unstitchedProtocolSeams' or configure cross-package client/route conventions in chomp.config.json so the end-to-end inter-package bridge is visible, then verify with chomp_get_diff.`;
|
|
2622
|
+
const isoDiag = {
|
|
2623
|
+
kind: "ISOLATED_DEPLOYMENT_UNITS",
|
|
2624
|
+
ruleId: "ISOLATED_DEPLOYMENT_UNITS",
|
|
2625
|
+
severity: "ADVISORY",
|
|
2626
|
+
isolatedPackages: activePackageLayers.map((p) => ({
|
|
2627
|
+
packageName: p.packageName,
|
|
2628
|
+
boundaryId: p.boundaryId,
|
|
2629
|
+
packagePath: p.packagePath,
|
|
2630
|
+
contractCount: contractsCountByPkg.get(p.packageName) ?? 0,
|
|
2631
|
+
})),
|
|
2632
|
+
crossPackageLinkCount: 0,
|
|
2633
|
+
description: isoDesc,
|
|
2634
|
+
agentReadinessOpportunity: isoGuidance,
|
|
2635
|
+
agentReadinessGuidance: isoGuidance,
|
|
2636
|
+
};
|
|
2637
|
+
seamDiagnostics.push(isoDiag);
|
|
2638
|
+
boundaryViolations.push({
|
|
2639
|
+
ruleId: "ISOLATED_DEPLOYMENT_UNITS",
|
|
2640
|
+
severity: "ADVISORY",
|
|
2641
|
+
sourcePackage: activePackageLayers[0].packageName,
|
|
2642
|
+
targetPackage: activePackageLayers
|
|
2643
|
+
.slice(1)
|
|
2644
|
+
.map((p) => p.packageName)
|
|
2645
|
+
.join(", "),
|
|
2646
|
+
description: isoDesc,
|
|
2647
|
+
evidence: [],
|
|
2648
|
+
agentReadinessGuidance: isoGuidance,
|
|
2649
|
+
});
|
|
2650
|
+
}
|
|
2651
|
+
// 6b. Unstitched Protocol / HTTP Seam Pairing (`UNSTITCHED_PROTOCOL_SEAM`)
|
|
2652
|
+
const unstitchedProtocolSeams = detectUnstitchedProtocolSeams(graph, index, {
|
|
2653
|
+
packageName: pkgFilter,
|
|
2654
|
+
repoPath: options?.repoPath,
|
|
2655
|
+
});
|
|
2656
|
+
for (const seam of unstitchedProtocolSeams) {
|
|
2657
|
+
seamDiagnostics.push(seam);
|
|
2658
|
+
const sampleSource = seam.clientCallers[0] ?? seam.clientConnector;
|
|
2659
|
+
const sampleEvidence = seam.candidateServerRoutes
|
|
2660
|
+
.slice(0, 5)
|
|
2661
|
+
.map((route) => ({
|
|
2662
|
+
sourceNode: sampleSource,
|
|
2663
|
+
targetNode: route.node,
|
|
2664
|
+
edgeName: `Unstitched HTTP Seam: ${seam.clientUrlPattern} -> ${route.httpMethod} ${route.effectivePath}`,
|
|
2665
|
+
edgeType: "UNSTITCHED_HTTP_SEAM",
|
|
2666
|
+
filePath: seam.clientConnector.filePath ?? sampleSource.filePath,
|
|
2667
|
+
lineNumber: seam.clientConnector.lineNumber ?? sampleSource.lineNumber,
|
|
2668
|
+
}));
|
|
2669
|
+
boundaryViolations.push({
|
|
2670
|
+
ruleId: "UNSTITCHED_PROTOCOL_SEAM",
|
|
2671
|
+
severity: "ADVISORY",
|
|
2672
|
+
sourcePackage: seam.clientPackage,
|
|
2673
|
+
targetPackage: seam.serverPackage,
|
|
2674
|
+
description: seam.description,
|
|
2675
|
+
evidence: sampleEvidence,
|
|
2676
|
+
agentReadinessGuidance: seam.agentReadinessGuidance,
|
|
2677
|
+
});
|
|
2678
|
+
}
|
|
2679
|
+
// 6c. INIT_BLOCK Gravity Leak Detection (`INIT_BLOCK_CONNECTOR_LEAK`)
|
|
2680
|
+
const initBlockConnectorLeaks = detectInitBlockConnectorLeaks(graph, index, {
|
|
2681
|
+
packageName: pkgFilter,
|
|
2682
|
+
});
|
|
2683
|
+
for (const leak of initBlockConnectorLeaks) {
|
|
2684
|
+
seamDiagnostics.push(leak);
|
|
2685
|
+
const sampleEvidence = leak.leakedConnectors
|
|
2686
|
+
.slice(0, 5)
|
|
2687
|
+
.map((conn) => ({
|
|
2688
|
+
sourceNode: leak.initBlockNode,
|
|
2689
|
+
targetNode: conn,
|
|
2690
|
+
edgeName: `Leaked Connector Edge: ${leak.initBlockNode.label} -> ${conn.label}`,
|
|
2691
|
+
edgeType: conn.entityType,
|
|
2692
|
+
filePath: leak.affectedFiles[0] ?? conn.filePath,
|
|
2693
|
+
lineNumber: conn.lineNumber,
|
|
2694
|
+
}));
|
|
2695
|
+
boundaryViolations.push({
|
|
2696
|
+
ruleId: "INIT_BLOCK_CONNECTOR_LEAK",
|
|
2697
|
+
severity: "ADVISORY",
|
|
2698
|
+
sourcePackage: leak.packageName,
|
|
2699
|
+
targetPackage: leak.packageName,
|
|
2700
|
+
description: leak.description,
|
|
2701
|
+
evidence: sampleEvidence,
|
|
2702
|
+
agentReadinessGuidance: leak.agentReadinessGuidance,
|
|
2703
|
+
});
|
|
2704
|
+
}
|
|
2705
|
+
// 6d. Shadowed Database Receptor Detection (`SHADOWED_DB_RECEPTOR`)
|
|
2706
|
+
const shadowedDbReceptors = detectShadowedDbReceptors(graph, index, {
|
|
2707
|
+
packageName: pkgFilter,
|
|
2708
|
+
});
|
|
2709
|
+
for (const shadowed of shadowedDbReceptors) {
|
|
2710
|
+
seamDiagnostics.push(shadowed);
|
|
2711
|
+
const sampleEvidence = shadowed.shadowedCallers
|
|
2712
|
+
.slice(0, 5)
|
|
2713
|
+
.map((caller) => ({
|
|
2714
|
+
sourceNode: caller,
|
|
2715
|
+
targetNode: shadowed.driverPackageNode,
|
|
2716
|
+
edgeName: `Shadowed DB Call: ${caller.label} -> ${shadowed.driverPackageNode.label}`,
|
|
2717
|
+
edgeType: "CALL",
|
|
2718
|
+
filePath: caller.filePath,
|
|
2719
|
+
lineNumber: caller.lineNumber,
|
|
2720
|
+
}));
|
|
2721
|
+
boundaryViolations.push({
|
|
2722
|
+
ruleId: "SHADOWED_DB_RECEPTOR",
|
|
2723
|
+
severity: "ADVISORY",
|
|
2724
|
+
sourcePackage: shadowed.packageName,
|
|
2725
|
+
targetPackage: shadowed.expectedReceptorLabel,
|
|
2726
|
+
description: shadowed.description,
|
|
2727
|
+
evidence: sampleEvidence,
|
|
2728
|
+
agentReadinessGuidance: shadowed.agentReadinessGuidance,
|
|
2729
|
+
});
|
|
2730
|
+
}
|
|
2731
|
+
const hasHardViolations = packageCycles.length > 0 ||
|
|
2732
|
+
boundaryViolations.some((v) => v.severity === "VIOLATION");
|
|
2733
|
+
return {
|
|
2734
|
+
status: hasHardViolations
|
|
2735
|
+
? "VIOLATION"
|
|
2736
|
+
: boundaryViolations.length > 0 || contractCycles.length > 0
|
|
2737
|
+
? "ADVISORY"
|
|
2738
|
+
: "CLEAN",
|
|
2739
|
+
summary: {
|
|
2740
|
+
packageCount: packageLayers.length,
|
|
2741
|
+
crossPackageLinkCount: packageDependencies.length,
|
|
2742
|
+
isolatedPackageCount: packageLayers.filter((p) => p.architecturalTier === "ISOLATED_PACKAGE").length,
|
|
2743
|
+
packageCycleCount: packageCycles.length,
|
|
2744
|
+
contractCycleCount: contractCycles.length,
|
|
2745
|
+
selfLoopCount: selfLoops.length,
|
|
2746
|
+
boundaryViolationCount: boundaryViolations.filter((v) => v.severity === "VIOLATION").length,
|
|
2747
|
+
boundaryAdvisoryCount: boundaryViolations.filter((v) => v.severity === "ADVISORY").length,
|
|
2748
|
+
unstitchedProtocolSeamCount: unstitchedProtocolSeams.length,
|
|
2749
|
+
initBlockConnectorLeakCount: initBlockConnectorLeaks.length,
|
|
2750
|
+
seamDiagnosticCount: seamDiagnostics.length,
|
|
2751
|
+
},
|
|
2752
|
+
packageLayers,
|
|
2753
|
+
packageDependencies,
|
|
2754
|
+
circularDependencies: {
|
|
2755
|
+
packageCycles,
|
|
2756
|
+
contractCycles,
|
|
2757
|
+
selfLoops,
|
|
2758
|
+
},
|
|
2759
|
+
boundaryViolations,
|
|
2760
|
+
unstitchedProtocolSeams,
|
|
2761
|
+
initBlockConnectorLeaks,
|
|
2762
|
+
seamDiagnostics,
|
|
2763
|
+
};
|
|
2764
|
+
}
|
|
2765
|
+
/**
|
|
2766
|
+
* `chomp_get_blast_radius` implementation ([PAT-MCP-08], [PAT-MCP-09]).
|
|
2767
|
+
*
|
|
2768
|
+
* Computes the upstream caller tree, downstream dependency tree, external side-effects,
|
|
2769
|
+
* affected INGRESS entry points, affected packages, Port Valve schemas, and
|
|
2770
|
+
* `highlightNodeIds` for pre-edit impact analysis.
|
|
2771
|
+
*/
|
|
2772
|
+
export function computeBlastRadius(graph, options, overlaysArg) {
|
|
2773
|
+
const index = buildGraphIndex(graph);
|
|
2774
|
+
const maxDepth = Math.max(1, Math.min(options.maxDepth ?? 4, 10));
|
|
2775
|
+
const allPortOverlays = overlaysArg ?? options.overlays;
|
|
2776
|
+
const overlaysByEntityId = new Map();
|
|
2777
|
+
if (allPortOverlays && allPortOverlays.length > 0) {
|
|
2778
|
+
for (const ov of allPortOverlays) {
|
|
2779
|
+
if (!ov || !ov.entityId)
|
|
2780
|
+
continue;
|
|
2781
|
+
let list = overlaysByEntityId.get(ov.entityId);
|
|
2782
|
+
if (!list) {
|
|
2783
|
+
list = [];
|
|
2784
|
+
overlaysByEntityId.set(ov.entityId, list);
|
|
2785
|
+
}
|
|
2786
|
+
list.push(ov);
|
|
2787
|
+
}
|
|
2788
|
+
}
|
|
2789
|
+
// 1. Resolve starting target node(s)
|
|
2790
|
+
const seedNodes = [];
|
|
2791
|
+
const seedIdSet = new Set();
|
|
2792
|
+
const addSeedNode = (node) => {
|
|
2793
|
+
if (!node || seedIdSet.has(node.id))
|
|
2794
|
+
return;
|
|
2795
|
+
seedIdSet.add(node.id);
|
|
2796
|
+
seedNodes.push(node);
|
|
2797
|
+
// If a CLASS or NAMESPACE boundary is targeted, include its child PUBLIC_METHOD / CONTRACT nodes
|
|
2798
|
+
// so callers of the class's methods are captured in the blast radius
|
|
2799
|
+
if (node.type === "BOUNDARY" &&
|
|
2800
|
+
(node.entityType === "CLASS" || node.entityType === "NAMESPACE")) {
|
|
2801
|
+
for (const candidate of index.nodeById.values()) {
|
|
2802
|
+
if (candidate.parentBoundaryId === node.id && !seedIdSet.has(candidate.id)) {
|
|
2803
|
+
seedIdSet.add(candidate.id);
|
|
2804
|
+
seedNodes.push(candidate);
|
|
2805
|
+
}
|
|
2806
|
+
}
|
|
2807
|
+
}
|
|
2808
|
+
};
|
|
2809
|
+
if (options.nodeId) {
|
|
2810
|
+
addSeedNode(index.nodeById.get(options.nodeId));
|
|
2811
|
+
}
|
|
2812
|
+
if (options.nodeIds && options.nodeIds.length > 0) {
|
|
2813
|
+
for (const id of options.nodeIds) {
|
|
2814
|
+
addSeedNode(index.nodeById.get(id));
|
|
2815
|
+
}
|
|
2816
|
+
}
|
|
2817
|
+
if (seedNodes.length === 0 && (options.searchTerm || options.packageName)) {
|
|
2818
|
+
const matched = filterNodesForMcp(graph, {
|
|
2819
|
+
searchTerm: options.searchTerm,
|
|
2820
|
+
packageName: options.packageName,
|
|
2821
|
+
}).filter((n) => !isHiddenNode(n));
|
|
2822
|
+
for (const m of matched.slice(0, 10)) {
|
|
2823
|
+
addSeedNode(m);
|
|
2824
|
+
}
|
|
2825
|
+
}
|
|
2826
|
+
if (seedNodes.length === 0) {
|
|
2827
|
+
return {
|
|
2828
|
+
found: false,
|
|
2829
|
+
message: "No matching target nodes found. Pass a valid `node_id` or `search_term` (from `chomp_get_nodes`).",
|
|
2830
|
+
targetNodes: [],
|
|
2831
|
+
portValves: [],
|
|
2832
|
+
upstreamCallers: [],
|
|
2833
|
+
downstreamDependencies: [],
|
|
2834
|
+
externalSideEffects: [],
|
|
2835
|
+
affectedEntryPoints: [],
|
|
2836
|
+
affectedPackages: [],
|
|
2837
|
+
highlightNodeIds: [],
|
|
2838
|
+
preEditGuidance: [],
|
|
2839
|
+
};
|
|
2840
|
+
}
|
|
2841
|
+
const targetRefs = seedNodes.map((n) => toNodeSummaryRef(n, index.resolveNodePkg));
|
|
2842
|
+
const targetPkgs = new Set(targetRefs.map((t) => t.packageName));
|
|
2843
|
+
// Extract Port Valves ([PAT-VIS-14]) on target nodes (Speed 1 AST + Speed 2 L1_PORTS cache)
|
|
2844
|
+
const portValves = [];
|
|
2845
|
+
for (const n of seedNodes) {
|
|
2846
|
+
const meta = parseNodeMeta(n);
|
|
2847
|
+
const merged = mergeContractPortValves(meta, overlaysByEntityId.get(n.id));
|
|
2848
|
+
if (!merged)
|
|
2849
|
+
continue;
|
|
2850
|
+
const hasMeaningfulValve = (merged.inputTypes && merged.inputTypes.length > 0) ||
|
|
2851
|
+
Boolean(merged.outputType) ||
|
|
2852
|
+
(merged.inputs && merged.inputs.length > 0) ||
|
|
2853
|
+
Boolean(merged.output) ||
|
|
2854
|
+
Boolean(merged.zeroInputs) ||
|
|
2855
|
+
(merged.diagnostics && merged.diagnostics.length > 0);
|
|
2856
|
+
if (!hasMeaningfulValve)
|
|
2857
|
+
continue;
|
|
2858
|
+
portValves.push({
|
|
2859
|
+
nodeId: n.id,
|
|
2860
|
+
label: cleanNodeLabel(n.name),
|
|
2861
|
+
...merged,
|
|
2862
|
+
});
|
|
2863
|
+
}
|
|
2864
|
+
// 2. Upstream BFS (Who calls/depends on the target?)
|
|
2865
|
+
const upstreamCallers = [];
|
|
2866
|
+
const upstreamVisited = new Set(seedIdSet);
|
|
2867
|
+
const upstreamQueue = seedNodes.map((n) => ({ id: n.id, depth: 0 }));
|
|
2868
|
+
while (upstreamQueue.length > 0) {
|
|
2869
|
+
const { id: currId, depth } = upstreamQueue.shift();
|
|
2870
|
+
if (depth >= maxDepth)
|
|
2871
|
+
continue;
|
|
2872
|
+
const currPkg = index.resolveNodePkg(currId);
|
|
2873
|
+
const inEdges = index.inEdgesByTarget.get(currId) ?? [];
|
|
2874
|
+
for (const edge of inEdges) {
|
|
2875
|
+
if (!FLOW_EDGE_ENTITY_TYPES.has(edge.entityType))
|
|
2876
|
+
continue;
|
|
2877
|
+
const caller = index.nodeById.get(edge.sourceId);
|
|
2878
|
+
if (!caller || isHiddenNode(caller))
|
|
2879
|
+
continue;
|
|
2880
|
+
if (upstreamVisited.has(caller.id))
|
|
2881
|
+
continue;
|
|
2882
|
+
upstreamVisited.add(caller.id);
|
|
2883
|
+
const callerRef = toNodeSummaryRef(caller, index.resolveNodePkg);
|
|
2884
|
+
const isIngress = INGRESS_ENTITY_TYPES.has(caller.entityType) ||
|
|
2885
|
+
caller.entityType === INIT_BLOCK_ENTITY_TYPE;
|
|
2886
|
+
upstreamCallers.push({
|
|
2887
|
+
depth: depth + 1,
|
|
2888
|
+
node: callerRef,
|
|
2889
|
+
viaEdgeName: edge.name ?? edge.entityType,
|
|
2890
|
+
viaEdgeType: edge.entityType,
|
|
2891
|
+
fromOrToNodeId: currId,
|
|
2892
|
+
crossesPackageBoundary: Boolean(currPkg && callerRef.packageName && currPkg !== callerRef.packageName),
|
|
2893
|
+
isIngressEntry: isIngress,
|
|
2894
|
+
});
|
|
2895
|
+
upstreamQueue.push({ id: caller.id, depth: depth + 1 });
|
|
2896
|
+
}
|
|
2897
|
+
}
|
|
2898
|
+
// 3. Downstream BFS (What does the target call or mutate?)
|
|
2899
|
+
const downstreamDependencies = [];
|
|
2900
|
+
const externalSideEffects = [];
|
|
2901
|
+
const downstreamVisited = new Set(seedIdSet);
|
|
2902
|
+
const downstreamQueue = seedNodes.map((n) => ({ id: n.id, depth: 0 }));
|
|
2903
|
+
while (downstreamQueue.length > 0) {
|
|
2904
|
+
const { id: currId, depth } = downstreamQueue.shift();
|
|
2905
|
+
if (depth >= maxDepth)
|
|
2906
|
+
continue;
|
|
2907
|
+
const currPkg = index.resolveNodePkg(currId);
|
|
2908
|
+
const outEdges = index.outEdgesBySource.get(currId) ?? [];
|
|
2909
|
+
for (const edge of outEdges) {
|
|
2910
|
+
if (!edge.targetId)
|
|
2911
|
+
continue;
|
|
2912
|
+
if (!FLOW_EDGE_ENTITY_TYPES.has(edge.entityType))
|
|
2913
|
+
continue;
|
|
2914
|
+
const callee = index.nodeById.get(edge.targetId);
|
|
2915
|
+
if (!callee || isHiddenNode(callee))
|
|
2916
|
+
continue;
|
|
2917
|
+
if (callee.type === "OPEN_CONNECTOR") {
|
|
2918
|
+
if (!downstreamVisited.has(callee.id)) {
|
|
2919
|
+
downstreamVisited.add(callee.id);
|
|
2920
|
+
externalSideEffects.push({
|
|
2921
|
+
depth: depth + 1,
|
|
2922
|
+
connector: toNodeSummaryRef(callee, index.resolveNodePkg),
|
|
2923
|
+
calledFromNodeId: currId,
|
|
2924
|
+
edgeName: edge.name ?? edge.entityType,
|
|
2925
|
+
});
|
|
2926
|
+
}
|
|
2927
|
+
continue;
|
|
2928
|
+
}
|
|
2929
|
+
if (downstreamVisited.has(callee.id))
|
|
2930
|
+
continue;
|
|
2931
|
+
downstreamVisited.add(callee.id);
|
|
2932
|
+
const calleeRef = toNodeSummaryRef(callee, index.resolveNodePkg);
|
|
2933
|
+
downstreamDependencies.push({
|
|
2934
|
+
depth: depth + 1,
|
|
2935
|
+
node: calleeRef,
|
|
2936
|
+
viaEdgeName: edge.name ?? edge.entityType,
|
|
2937
|
+
viaEdgeType: edge.entityType,
|
|
2938
|
+
fromOrToNodeId: currId,
|
|
2939
|
+
crossesPackageBoundary: Boolean(currPkg && calleeRef.packageName && currPkg !== calleeRef.packageName),
|
|
2940
|
+
isIngressEntry: INGRESS_ENTITY_TYPES.has(callee.entityType),
|
|
2941
|
+
});
|
|
2942
|
+
downstreamQueue.push({ id: callee.id, depth: depth + 1 });
|
|
2943
|
+
}
|
|
2944
|
+
}
|
|
2945
|
+
// 4. Affected Entry Points & Affected Packages
|
|
2946
|
+
const affectedEntryPoints = [];
|
|
2947
|
+
const seenEntries = new Set();
|
|
2948
|
+
for (const t of targetRefs) {
|
|
2949
|
+
if ((INGRESS_ENTITY_TYPES.has(t.entityType) ||
|
|
2950
|
+
t.entityType === INIT_BLOCK_ENTITY_TYPE) &&
|
|
2951
|
+
!seenEntries.has(t.id)) {
|
|
2952
|
+
seenEntries.add(t.id);
|
|
2953
|
+
affectedEntryPoints.push(t);
|
|
2954
|
+
}
|
|
2955
|
+
}
|
|
2956
|
+
for (const u of upstreamCallers) {
|
|
2957
|
+
if (u.isIngressEntry && !seenEntries.has(u.node.id)) {
|
|
2958
|
+
seenEntries.add(u.node.id);
|
|
2959
|
+
affectedEntryPoints.push(u.node);
|
|
2960
|
+
}
|
|
2961
|
+
}
|
|
2962
|
+
const affectedPackagesSet = new Set(targetPkgs);
|
|
2963
|
+
for (const u of upstreamCallers) {
|
|
2964
|
+
if (u.node.packageName)
|
|
2965
|
+
affectedPackagesSet.add(u.node.packageName);
|
|
2966
|
+
}
|
|
2967
|
+
const affectedPackages = [...affectedPackagesSet].sort();
|
|
2968
|
+
const directCallers = upstreamCallers.filter((u) => u.depth === 1);
|
|
2969
|
+
const crossPkgCallers = upstreamCallers.filter((u) => u.crossesPackageBoundary);
|
|
2970
|
+
let riskLevel = "LOW";
|
|
2971
|
+
if (upstreamCallers.length > 8 ||
|
|
2972
|
+
affectedPackages.length >= 3 ||
|
|
2973
|
+
crossPkgCallers.length >= 3) {
|
|
2974
|
+
riskLevel = "HIGH";
|
|
2975
|
+
}
|
|
2976
|
+
else if (upstreamCallers.length >= 3 ||
|
|
2977
|
+
affectedPackages.length >= 2 ||
|
|
2978
|
+
affectedEntryPoints.length >= 2) {
|
|
2979
|
+
riskLevel = "MEDIUM";
|
|
2980
|
+
}
|
|
2981
|
+
const highlightNodeIds = [];
|
|
2982
|
+
const addHighlight = (id) => {
|
|
2983
|
+
if (id && !highlightNodeIds.includes(id) && highlightNodeIds.length < 50) {
|
|
2984
|
+
highlightNodeIds.push(id);
|
|
2985
|
+
}
|
|
2986
|
+
};
|
|
2987
|
+
for (const t of targetRefs)
|
|
2988
|
+
addHighlight(t.id);
|
|
2989
|
+
for (const u of upstreamCallers)
|
|
2990
|
+
addHighlight(u.node.id);
|
|
2991
|
+
for (const d of downstreamDependencies)
|
|
2992
|
+
addHighlight(d.node.id);
|
|
2993
|
+
for (const s of externalSideEffects)
|
|
2994
|
+
addHighlight(s.connector.id);
|
|
2995
|
+
// Collect active Port Valve mismatch diagnostics on targets AND incoming direct callers
|
|
2996
|
+
const portDiagnosticsSummary = [];
|
|
2997
|
+
for (const pv of portValves) {
|
|
2998
|
+
for (const d of pv.diagnostics ?? []) {
|
|
2999
|
+
portDiagnosticsSummary.push({
|
|
3000
|
+
ownerNodeId: pv.nodeId,
|
|
3001
|
+
ownerLabel: pv.label,
|
|
3002
|
+
diagnostic: d,
|
|
3003
|
+
});
|
|
3004
|
+
}
|
|
3005
|
+
}
|
|
3006
|
+
for (const caller of directCallers) {
|
|
3007
|
+
const callerOvs = overlaysByEntityId.get(caller.node.id);
|
|
3008
|
+
if (!callerOvs)
|
|
3009
|
+
continue;
|
|
3010
|
+
const callerNode = index.nodeById.get(caller.node.id);
|
|
3011
|
+
const callerPv = mergeContractPortValves(callerNode ? parseNodeMeta(callerNode) : undefined, callerOvs);
|
|
3012
|
+
for (const d of callerPv?.diagnostics ?? []) {
|
|
3013
|
+
if (d.peerEntityId && seedIdSet.has(d.peerEntityId)) {
|
|
3014
|
+
portDiagnosticsSummary.push({
|
|
3015
|
+
ownerNodeId: caller.node.id,
|
|
3016
|
+
ownerLabel: caller.node.label,
|
|
3017
|
+
diagnostic: d,
|
|
3018
|
+
});
|
|
3019
|
+
}
|
|
3020
|
+
}
|
|
3021
|
+
}
|
|
3022
|
+
const preEditGuidance = [
|
|
3023
|
+
`1. Spotlight (Questions Only): When answering a user question or walkthrough request, pass 'highlightNodeIds' (${highlightNodeIds.length} nodes) to 'chomp_create_view' (or pass create_view: true) to highlight this blast radius on the map; leave create_view: false during routine code edits.`,
|
|
3024
|
+
directCallers.length > 0
|
|
3025
|
+
? `2. Signature Compatibility: ${directCallers.length} direct caller(s) (${directCallers.map((c) => `${c.node.packageName}:${c.node.label}`).slice(0, 5).join(", ")}) invoke the target directly. Preserve parameter/return types (${portValves.map((v) => `${v.label}: (${v.inputs?.map((p) => `${p.name}${p.optional ? "?" : ""}: ${p.type}`).join(", ") ?? (v.inputTypes ?? []).join(", ")}) => ${v.output?.type ?? v.outputType ?? "void"}`).join("; ") || "check caller call-sites"}) or update all callers in lockstep.`
|
|
3026
|
+
: `2. Leaf / Entry Target: Target has 0 direct callers in the graph; signature changes will not break upstream contracts.`,
|
|
3027
|
+
`3. Post-Edit Verification: After editing, run 'chomp_get_diff' to confirm that only the intended nodes in [${affectedPackages.join(", ")}] are MODIFIED/ADDED and no unintended edges were dropped.`,
|
|
3028
|
+
];
|
|
3029
|
+
if (portDiagnosticsSummary.length > 0) {
|
|
3030
|
+
preEditGuidance.push(`4. Type Mismatches (${portDiagnosticsSummary.length}): ${portDiagnosticsSummary
|
|
3031
|
+
.slice(0, 4)
|
|
3032
|
+
.map((m) => `${m.ownerLabel} (${m.diagnostic.filePath ?? ""}${m.diagnostic.lineNumber ? `:${m.diagnostic.lineNumber}` : ""}) [${m.diagnostic.kind}${m.diagnostic.tsCode ? ` TS${m.diagnostic.tsCode}` : ""}]: ${m.diagnostic.message}`)
|
|
3033
|
+
.join(" | ")}`);
|
|
3034
|
+
}
|
|
3035
|
+
return {
|
|
3036
|
+
found: true,
|
|
3037
|
+
summary: {
|
|
3038
|
+
riskLevel,
|
|
3039
|
+
targetCount: targetRefs.length,
|
|
3040
|
+
directUpstreamCallerCount: directCallers.length,
|
|
3041
|
+
totalUpstreamCallerCount: upstreamCallers.length,
|
|
3042
|
+
crossPackageCallerCount: crossPkgCallers.length,
|
|
3043
|
+
downstreamDependencyCount: downstreamDependencies.length,
|
|
3044
|
+
externalSideEffectCount: externalSideEffects.length,
|
|
3045
|
+
affectedEntryPointCount: affectedEntryPoints.length,
|
|
3046
|
+
portMismatchCount: portDiagnosticsSummary.length,
|
|
3047
|
+
affectedPackages,
|
|
3048
|
+
},
|
|
3049
|
+
targetNodes: targetRefs,
|
|
3050
|
+
portValves,
|
|
3051
|
+
affectedEntryPoints,
|
|
3052
|
+
upstreamCallers,
|
|
3053
|
+
downstreamDependencies,
|
|
3054
|
+
externalSideEffects,
|
|
3055
|
+
highlightNodeIds,
|
|
3056
|
+
preEditGuidance,
|
|
3057
|
+
};
|
|
3058
|
+
}
|