@getchomp/cli 0.0.0-stage → 0.2.42

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.
Files changed (62) hide show
  1. package/README.md +39 -2
  2. package/dist/commands/analyze.d.ts +49 -0
  3. package/dist/commands/analyze.js +280 -0
  4. package/dist/commands/connect.d.ts +12 -0
  5. package/dist/commands/connect.js +255 -0
  6. package/dist/commands/export.d.ts +29 -0
  7. package/dist/commands/export.js +356 -0
  8. package/dist/commands/health.d.ts +19 -0
  9. package/dist/commands/health.js +259 -0
  10. package/dist/commands/init.d.ts +40 -0
  11. package/dist/commands/init.js +654 -0
  12. package/dist/commands/mcp.d.ts +2 -0
  13. package/dist/commands/mcp.js +12 -0
  14. package/dist/commands/plugin.d.ts +8 -0
  15. package/dist/commands/plugin.js +198 -0
  16. package/dist/commands/ui.d.ts +20 -0
  17. package/dist/commands/ui.js +250 -0
  18. package/dist/commands/uninstall.d.ts +8 -0
  19. package/dist/commands/uninstall.js +238 -0
  20. package/dist/index.d.ts +3 -0
  21. package/dist/index.js +37 -0
  22. package/dist/ports/portHydrator.d.ts +63 -0
  23. package/dist/ports/portHydrator.js +954 -0
  24. package/dist/ports/portHydratorWorker.d.ts +22 -0
  25. package/dist/ports/portHydratorWorker.js +75 -0
  26. package/dist/server/buildStatusTracker.d.ts +45 -0
  27. package/dist/server/buildStatusTracker.js +122 -0
  28. package/dist/server/graphLayoutState.d.ts +205 -0
  29. package/dist/server/graphLayoutState.js +930 -0
  30. package/dist/server/loopbackSecurity.d.ts +18 -0
  31. package/dist/server/loopbackSecurity.js +57 -0
  32. package/dist/server/routes/authSourceRoutes.d.ts +18 -0
  33. package/dist/server/routes/authSourceRoutes.js +231 -0
  34. package/dist/server/routes/layoutRoutes.d.ts +3 -0
  35. package/dist/server/routes/layoutRoutes.js +857 -0
  36. package/dist/server/routes/pluginRoutes.d.ts +3 -0
  37. package/dist/server/routes/pluginRoutes.js +368 -0
  38. package/dist/server/routes/viewRulesRoutes.d.ts +3 -0
  39. package/dist/server/routes/viewRulesRoutes.js +173 -0
  40. package/dist/server/uiHotkeys.d.ts +26 -0
  41. package/dist/server/uiHotkeys.js +160 -0
  42. package/dist/utils/branding.d.ts +126 -0
  43. package/dist/utils/branding.js +976 -0
  44. package/dist/utils/credentials.d.ts +22 -0
  45. package/dist/utils/credentials.js +126 -0
  46. package/dist/utils/git.d.ts +95 -0
  47. package/dist/utils/git.js +780 -0
  48. package/dist/utils/masterContext.d.ts +102 -0
  49. package/dist/utils/masterContext.js +559 -0
  50. package/dist/visualizer/cloudLayoutClient.d.ts +84 -0
  51. package/dist/visualizer/cloudLayoutClient.js +1200 -0
  52. package/dist/visualizer/layoutCache.d.ts +25 -0
  53. package/dist/visualizer/layoutCache.js +406 -0
  54. package/dist/visualizer/localEngineBridge.d.ts +50 -0
  55. package/dist/visualizer/localEngineBridge.js +80 -0
  56. package/dist/visualizer/pluginPresentationApi.d.ts +111 -0
  57. package/dist/visualizer/pluginPresentationApi.js +432 -0
  58. package/dist/visualizer/rulesConfig.d.ts +11 -0
  59. package/dist/visualizer/rulesConfig.js +266 -0
  60. package/dist/visualizer/sourceAccess.d.ts +45 -0
  61. package/dist/visualizer/sourceAccess.js +204 -0
  62. package/package.json +51 -3
@@ -0,0 +1,1200 @@
1
+ /**
2
+ * packages/cli/src/visualizer/cloudLayoutClient.ts
3
+ *
4
+ * Stateless Skeleton-to-Coordinates Client & Server Pipeline (`api.getchomp.dev`).
5
+ *
6
+ * Architecture:
7
+ * 1. Local CLI (`chomp ui`) holds `.chomp/graph.db` and `.chomp/rules.json` 100% locally.
8
+ * 2. Before calling the remote Cloudflare Worker (`POST /v1/layout`), `anonymizeGraphForCloudLayout`
9
+ * strips all code snippets, business symbol names, and file paths — replacing them with
10
+ * deterministic, role- and length-preserving pseudonyms while pre-evaluating custom rules locally.
11
+ * 3. The stateless Cloudflare Worker executes `executeStatelessLayout` (`1-storyTracer` ->
12
+ * `2-zipMerge` -> `3-gridMapper` -> `visualLinter`) in memory with zero persistence.
13
+ * 4. `rehydrateCloudLayout` restores the user's real labels, relative `filePath:lineNumber`
14
+ * evidence (without code snippets), and overlays locally before serving `GET /api/layout`.
15
+ */
16
+ import { createHash } from "node:crypto";
17
+ import { CANONICAL_PACKAGE_ORDER, LABEL_PREFIX_RE, classifyExternalReceptorSpec, computeGraphHealthMetrics, deploymentUnitLabel, inferDatabaseDialectFromGraph, matchesCustomRule, mergeContractPortValves, } from "@getchomp/core";
18
+ import { resolveActiveBearerToken } from "../utils/credentials.js";
19
+ import { DEFAULT_CLOUD_API_URL, hasLocalMasterLayoutEngine, loadLocalMasterLayoutEngine, } from "./localEngineBridge.js";
20
+ // ---------------------------------------------------------------------------
21
+ // Evidence Snippet Sanitizer
22
+ // ---------------------------------------------------------------------------
23
+ /**
24
+ * Strips raw source code `snippet` strings from a single evidence object or array,
25
+ * keeping only `{ filePath, lineNumber, evidenceRole }`.
26
+ */
27
+ export function sanitizeEvidenceItems(evidence) {
28
+ if (!evidence)
29
+ return undefined;
30
+ const rawList = Array.isArray(evidence) ? evidence : [evidence];
31
+ const cleaned = [];
32
+ for (const item of rawList) {
33
+ if (!item || typeof item !== "object" || !item.filePath)
34
+ continue;
35
+ cleaned.push({
36
+ filePath: String(item.filePath),
37
+ ...(typeof item.lineNumber === "number"
38
+ ? { lineNumber: item.lineNumber }
39
+ : {}),
40
+ ...(typeof item.evidenceRole === "string"
41
+ ? { evidenceRole: item.evidenceRole }
42
+ : {}),
43
+ });
44
+ }
45
+ return cleaned.length > 0 ? cleaned : undefined;
46
+ }
47
+ /**
48
+ * Returns a shallow copy of `RepresentationGraph` with all `evidence.snippet` fields removed.
49
+ */
50
+ export function stripEvidenceSnippetsFromGraph(graph) {
51
+ return {
52
+ ...graph,
53
+ nodes: graph.nodes.map((n) => {
54
+ if (!n.evidence)
55
+ return n;
56
+ const ev = Array.isArray(n.evidence)
57
+ ? n.evidence.map(({ snippet: _s, ...rest }) => rest)
58
+ : (() => {
59
+ const { snippet: _s, ...rest } = n.evidence;
60
+ return rest;
61
+ })();
62
+ return { ...n, evidence: ev };
63
+ }),
64
+ edges: graph.edges.map((e) => {
65
+ if (!e.evidence)
66
+ return e;
67
+ const ev = Array.isArray(e.evidence)
68
+ ? e.evidence.map(({ snippet: _s, ...rest }) => rest)
69
+ : (() => {
70
+ const { snippet: _s, ...rest } = e.evidence;
71
+ return rest;
72
+ })();
73
+ return { ...e, evidence: ev };
74
+ }),
75
+ };
76
+ }
77
+ // ---------------------------------------------------------------------------
78
+ // Deterministic Role- & Length-Preserving Pseudonymization Helpers
79
+ // ---------------------------------------------------------------------------
80
+ const UTILITY_PREFIX_RE = /^(get|set|is|has|can|should|format|parse|build|create|make|to|from|normalize|clean|strip|truncate|sanitize|validate|check|assert|ensure|compute|calc|calculate|resolve|extract|derive|map|filter|sort|group|merge|clone|pick|omit|log|warn|error|debug|read|write|load|save|encode|decode|hash|sign|verify|compare|match|find|lookup|select|count|sum|min|max|clamp|round|pad|join|split|trim|escape|unescape|serialize|deserialize|hydrate|dehydrate|wrap|unwrap|bind|noop|identity)(?=[A-Z0-9_]|$)/;
81
+ const DOMAIN_ENGINE_PREFIX_RE = /^(run|execute|perform|process|handle|dispatch|invoke|orchestrate|coordinate|analyze|audit|evaluate|sync|publish|emit|broadcast|schedule|enqueue|consume|migrate|bootstrap|initialize|start|stop|connect|disconnect|register|mount|render|compile|transpile|bundle|deploy)(?=[A-Z0-9_]|$)/;
82
+ const DOMAIN_STATION_SUFFIX_RE = /(Service|Controller|Router|Handler|Middleware|Guard|Interceptor|Filter|Pipe|Provider|Repository|Store|Client|Adapter|Gateway|Broker|Worker|Queue|Consumer|Producer|Processor|Engine|Manager|Coordinator|Orchestrator|Dispatcher|Resolver|Mutation|Query|Subscription|Context|Hook|Component|View|Page|Layout|Screen|Modal|Drawer|Dialog|Form|Table|Board|Canvas|Panel|Plugin|Server|App|Application|Module|Boundary|Error|Exception|_DEPRECATED|Old)$/;
83
+ const UTILITY_EXACT_NAMES = new Set([
84
+ "cn",
85
+ "clsx",
86
+ "twMerge",
87
+ "cva",
88
+ "noop",
89
+ "identity",
90
+ "invariant",
91
+ "assert",
92
+ "loader",
93
+ "action",
94
+ "clientLoader",
95
+ "clientAction",
96
+ ]);
97
+ const RESERVED_PATH_SEGMENTS = new Set([
98
+ "src",
99
+ "app",
100
+ "pages",
101
+ "routes",
102
+ "api",
103
+ "components",
104
+ "_components",
105
+ "adapters",
106
+ "visitors",
107
+ "conventions",
108
+ "helpers",
109
+ "utils",
110
+ "internal",
111
+ "fake",
112
+ "fakes",
113
+ "mock",
114
+ "mocks",
115
+ "packages",
116
+ "apps",
117
+ ]);
118
+ const RESERVED_FILE_BASENAMES = new Set([
119
+ "page",
120
+ "layout",
121
+ "route",
122
+ "loading",
123
+ "error",
124
+ "not-found",
125
+ "template",
126
+ "default",
127
+ "middleware",
128
+ "index",
129
+ ]);
130
+ function shortHash(seed) {
131
+ return createHash("sha256").update(seed).digest("hex");
132
+ }
133
+ function cleanNodeName(rawName) {
134
+ const match = rawName.match(LABEL_PREFIX_RE);
135
+ const stripped = rawName.replace(LABEL_PREFIX_RE, "");
136
+ let cleanBody = stripped;
137
+ if (stripped.match(/^(GET|POST|PUT|DELETE|PATCH|HEAD|OPTIONS|ALL|ROUTE)\s/i) ||
138
+ stripped.startsWith("/") ||
139
+ /^(generateMetadata|generateStaticParams)\s*\(/.test(stripped)) {
140
+ cleanBody = stripped;
141
+ }
142
+ else if (/^Init:\s+/i.test(stripped)) {
143
+ const unitPart = stripped.replace(/^Init:\s+/i, "");
144
+ cleanBody = `Init: ${unitPart.split("/").pop() || unitPart}`;
145
+ }
146
+ else {
147
+ cleanBody = stripped.split("/").pop() || stripped;
148
+ }
149
+ return {
150
+ prefix: match ? match[0] : "",
151
+ body: cleanBody.trim(),
152
+ };
153
+ }
154
+ function extractDeploymentUnitShortName(rawName) {
155
+ return deploymentUnitLabel(rawName);
156
+ }
157
+ /**
158
+ * Encodes a non-negative integer `rank` into fixed-width base-26 lowercase letters (`aaaa`..`zzzz`).
159
+ */
160
+ function encodeRankAlpha(rank, width = 4) {
161
+ const chars = new Array(width).fill("a");
162
+ let n = Math.max(0, rank);
163
+ for (let i = width - 1; i >= 0; i--) {
164
+ chars[i] = String.fromCharCode(97 + (n % 26));
165
+ n = Math.floor(n / 26);
166
+ }
167
+ return chars.join("");
168
+ }
169
+ /**
170
+ * Produces a deterministic, role- and length-preserving pseudonym for a single identifier token.
171
+ * Preserves:
172
+ * - Exact character length (`result.length === token.length`)
173
+ * - Classifier prefixes (`get`, `run`, `use`, etc.)
174
+ * - Classifier suffixes (`Service`, `Controller`, `Error`, etc.)
175
+ * - Initial character case (`[A-Z]` vs `[a-z]`)
176
+ * - Lexicographical sort tie-breaking via `rankTag` (`aaaa`..`zzzz`)
177
+ */
178
+ function pseudonymizeSingleToken(token, rank) {
179
+ if (!token)
180
+ return token;
181
+ if (UTILITY_EXACT_NAMES.has(token))
182
+ return token;
183
+ // Preserve HTTP route method prefixes like `GET /...` or Next.js route paths `/...`
184
+ if (/^(?:GET|POST|PUT|DELETE|PATCH|HEAD|OPTIONS)\s+/i.test(token)) {
185
+ const m = token.match(/^([A-Z]+\s+)(.*)$/i);
186
+ return `${m[1]}${pseudonymizeRoutePath(m[2], rank)}`;
187
+ }
188
+ if (token.startsWith("/")) {
189
+ return pseudonymizeRoutePath(token, rank);
190
+ }
191
+ let preservedPrefix = "";
192
+ const utilMatch = token.match(UTILITY_PREFIX_RE);
193
+ const engineMatch = !utilMatch ? token.match(DOMAIN_ENGINE_PREFIX_RE) : null;
194
+ const hookMatch = !utilMatch && !engineMatch && /^use[A-Z]/.test(token) ? ["use"] : null;
195
+ if (utilMatch) {
196
+ preservedPrefix = utilMatch[1];
197
+ }
198
+ else if (engineMatch) {
199
+ preservedPrefix = engineMatch[1];
200
+ }
201
+ else if (hookMatch) {
202
+ preservedPrefix = "use";
203
+ }
204
+ let preservedSuffix = "";
205
+ const suffixMatch = token.slice(preservedPrefix.length).match(DOMAIN_STATION_SUFFIX_RE);
206
+ if (suffixMatch && suffixMatch[1].length < token.length - preservedPrefix.length) {
207
+ preservedSuffix = suffixMatch[1];
208
+ }
209
+ if (!preservedPrefix &&
210
+ token.length - preservedSuffix.length >= 6 &&
211
+ /^[a-zA-Z]{2}/.test(token)) {
212
+ preservedPrefix = token.slice(0, 2);
213
+ }
214
+ const middleBudget = token.length - preservedPrefix.length - preservedSuffix.length;
215
+ if (middleBudget <= 0) {
216
+ const h = shortHash(`tok:${token}:${rank}`);
217
+ const isUpper = /^[A-Z]/.test(token);
218
+ const first = isUpper ? "N" : "n";
219
+ return (first + encodeRankAlpha(rank, 4) + h).slice(0, Math.max(1, token.length));
220
+ }
221
+ const origMiddle = token.slice(preservedPrefix.length, token.length - preservedSuffix.length);
222
+ const startsUpper = /^[A-Z]/.test(origMiddle);
223
+ const startsDigitOrUnderscore = /^[0-9_]/.test(origMiddle);
224
+ const rankChars = encodeRankAlpha(rank, 4);
225
+ const hashFill = shortHash(`mid:${token}:${rank}`).replace(/[^a-z0-9]/g, "x");
226
+ let rawFill = `${rankChars}${hashFill}`;
227
+ while (rawFill.length < middleBudget) {
228
+ rawFill += hashFill;
229
+ }
230
+ if (startsUpper) {
231
+ rawFill = rawFill[0].toUpperCase() + rawFill.slice(1);
232
+ }
233
+ else if (startsDigitOrUnderscore && preservedPrefix.length > 0) {
234
+ rawFill = "_" + rawFill.slice(1);
235
+ }
236
+ const middle = rawFill.slice(0, middleBudget);
237
+ return `${preservedPrefix}${middle}${preservedSuffix}`;
238
+ }
239
+ function pseudonymizeRoutePath(routePath, rank) {
240
+ const parts = routePath.split("/");
241
+ return parts
242
+ .map((seg, idx) => {
243
+ if (!seg)
244
+ return "";
245
+ if (/^\([^)]+\)$/.test(seg) || /^@/.test(seg) || /^\[.*\]$/.test(seg) || seg.startsWith(":")) {
246
+ return seg;
247
+ }
248
+ if (seg === "api" || seg === "v1" || seg === "health")
249
+ return seg;
250
+ const fill = `${encodeRankAlpha(rank + idx, 3)}${shortHash(`route:${seg}`)}`;
251
+ return fill.slice(0, Math.max(1, seg.length));
252
+ })
253
+ .join("/");
254
+ }
255
+ function pseudonymizeFilePath(filePath) {
256
+ const norm = String(filePath).replace(/\\/g, "/");
257
+ const segments = norm.split("/");
258
+ return segments
259
+ .map((seg, idx) => {
260
+ if (!seg)
261
+ return "";
262
+ if (idx < segments.length - 1) {
263
+ if (RESERVED_PATH_SEGMENTS.has(seg.toLowerCase()))
264
+ return seg;
265
+ if (/^\([^)]+\)$/.test(seg) || /^@/.test(seg) || /^\[.*\]$/.test(seg)) {
266
+ return seg;
267
+ }
268
+ return `d_${shortHash(`dir:${seg}`).slice(0, 6)}`;
269
+ }
270
+ const dotIdx = seg.indexOf(".");
271
+ const base = dotIdx >= 0 ? seg.slice(0, dotIdx) : seg;
272
+ const ext = dotIdx >= 0 ? seg.slice(dotIdx) : "";
273
+ if (RESERVED_FILE_BASENAMES.has(base.toLowerCase())) {
274
+ return `${base}${ext}`;
275
+ }
276
+ return `f_${shortHash(`file:${base}`).slice(0, 6)}${ext}`;
277
+ })
278
+ .join("/");
279
+ }
280
+ // ---------------------------------------------------------------------------
281
+ // Step 1: Anonymize Local Graph into Stateless Skeleton Request
282
+ // ---------------------------------------------------------------------------
283
+ export function anonymizeGraphForCloudLayout(rawGraph, diffDelta, rulesConfig, overlays) {
284
+ const nodesById = new Map();
285
+ const realPkgByPseudoPkg = new Map();
286
+ const pseudoPkgByRealPkg = new Map();
287
+ const realDisplayNameByRealPkg = new Map();
288
+ const realBadgeByPseudoBadge = new Map();
289
+ const realReceptorIdByPseudoId = new Map();
290
+ const realUnresolvedByKey = new Map();
291
+ const nodeById = new Map();
292
+ for (const n of rawGraph.nodes) {
293
+ if (!nodeById.has(n.id))
294
+ nodeById.set(n.id, n);
295
+ }
296
+ // Group overlays by entityId for local rule evaluation & humanLabel extraction
297
+ const overlaysByEntityId = new Map();
298
+ if (Array.isArray(overlays)) {
299
+ for (const ov of overlays) {
300
+ if (!ov || !ov.entityId)
301
+ continue;
302
+ if (rulesConfig?.overlayLayers &&
303
+ rulesConfig.overlayLayers[ov.layer] === false) {
304
+ continue;
305
+ }
306
+ let list = overlaysByEntityId.get(ov.entityId);
307
+ if (!list) {
308
+ list = [];
309
+ overlaysByEntityId.set(ov.entityId, list);
310
+ }
311
+ list.push(ov);
312
+ }
313
+ }
314
+ // 1. Resolve package labels and build deterministic order-preserving package pseudonyms
315
+ const discoveredRealPkgs = new Set();
316
+ for (const n of rawGraph.nodes) {
317
+ if (n.entityType === "DEPLOYMENT_UNIT") {
318
+ const shortPkg = extractDeploymentUnitShortName(n.name);
319
+ discoveredRealPkgs.add(shortPkg);
320
+ const rawDisplayName = n.name.replace(/^Deployment Unit:\s*/i, "").trim();
321
+ if (rawDisplayName && !realDisplayNameByRealPkg.has(shortPkg)) {
322
+ realDisplayNameByRealPkg.set(shortPkg, rawDisplayName);
323
+ }
324
+ }
325
+ }
326
+ const nonCanonicalPkgs = Array.from(discoveredRealPkgs)
327
+ .filter((p) => !CANONICAL_PACKAGE_ORDER.includes(p))
328
+ .sort();
329
+ for (const canonPkg of CANONICAL_PACKAGE_ORDER) {
330
+ if (discoveredRealPkgs.has(canonPkg)) {
331
+ pseudoPkgByRealPkg.set(canonPkg, canonPkg);
332
+ realPkgByPseudoPkg.set(canonPkg, canonPkg);
333
+ }
334
+ }
335
+ nonCanonicalPkgs.forEach((realPkg, idx) => {
336
+ const rankStr = String(idx).padStart(2, "0");
337
+ const rawPseudo = `pkg_${rankStr}_${shortHash(`pkg:${realPkg}`).slice(0, 6)}`;
338
+ const pseudoPkg = realPkg.length >= 4
339
+ ? rawPseudo.slice(0, realPkg.length).padEnd(realPkg.length, "x")
340
+ : rawPseudo.slice(0, 6);
341
+ pseudoPkgByRealPkg.set(realPkg, pseudoPkg);
342
+ realPkgByPseudoPkg.set(pseudoPkg, realPkg);
343
+ });
344
+ const packageOf = (nodeId) => {
345
+ const seen = new Set();
346
+ let cursor = nodeById.get(nodeId);
347
+ while (cursor && !seen.has(cursor.id)) {
348
+ seen.add(cursor.id);
349
+ if (cursor.entityType === "DEPLOYMENT_UNIT") {
350
+ return extractDeploymentUnitShortName(cursor.name);
351
+ }
352
+ cursor = cursor.parentBoundaryId
353
+ ? nodeById.get(cursor.parentBoundaryId)
354
+ : undefined;
355
+ }
356
+ return "";
357
+ };
358
+ // 2. Collect all distinct identifier tokens across the graph and sort them
359
+ // so `localeCompare` tie-breakers in `localBoardLayout.ts` and `3-gridMapper.ts`
360
+ // stay 100% order-isomorphic.
361
+ const allTokensSet = new Set();
362
+ for (const n of rawGraph.nodes) {
363
+ const { body } = cleanNodeName(n.name);
364
+ if (body.includes(".")) {
365
+ const [cls, mem] = body.split(".", 2);
366
+ if (cls)
367
+ allTokensSet.add(cls);
368
+ if (mem)
369
+ allTokensSet.add(mem);
370
+ }
371
+ else if (body) {
372
+ allTokensSet.add(body);
373
+ }
374
+ const ovs = overlaysByEntityId.get(n.id);
375
+ if (ovs) {
376
+ for (const ov of ovs) {
377
+ if (typeof ov.payload?.humanLabel === "string" && ov.payload.humanLabel.trim()) {
378
+ allTokensSet.add(ov.payload.humanLabel.trim());
379
+ }
380
+ }
381
+ }
382
+ }
383
+ const sortedTokens = Array.from(allTokensSet).sort((a, b) => a.localeCompare(b));
384
+ const rankByToken = new Map();
385
+ sortedTokens.forEach((tok, idx) => rankByToken.set(tok, idx));
386
+ const pseudoByToken = new Map();
387
+ const getPseudoToken = (tok) => {
388
+ const cached = pseudoByToken.get(tok);
389
+ if (cached !== undefined)
390
+ return cached;
391
+ const rank = rankByToken.get(tok) ?? 0;
392
+ const pseudo = pseudonymizeSingleToken(tok, rank);
393
+ pseudoByToken.set(tok, pseudo);
394
+ return pseudo;
395
+ };
396
+ // 3. Infer database dialect locally so open connectors don't need raw file paths/snippets
397
+ const dialectInfo = inferDatabaseDialectFromGraph(rawGraph);
398
+ const shimmedNodeIds = new Set();
399
+ const shimLabelByNodeId = new Map();
400
+ const shimLabelByEdgePair = new Map();
401
+ const shimEdgePairs = new Set();
402
+ const deterministicEdgePairs = new Set();
403
+ for (const n of rawGraph.nodes) {
404
+ const meta = typeof n.metadata === "object" && n.metadata !== null
405
+ ? n.metadata
406
+ : undefined;
407
+ if (meta?.source === "USER_SHIM") {
408
+ shimmedNodeIds.add(n.id);
409
+ if (typeof meta.shimLabel === "string" && meta.shimLabel.trim()) {
410
+ shimLabelByNodeId.set(n.id, meta.shimLabel.trim());
411
+ }
412
+ }
413
+ }
414
+ for (const edge of rawGraph.edges) {
415
+ if (!edge.targetId || edge.sourceId === edge.targetId)
416
+ continue;
417
+ const pairKey = `${edge.sourceId}::${edge.targetId}`;
418
+ const edgeMeta = typeof edge.metadata === "object" && edge.metadata !== null
419
+ ? edge.metadata
420
+ : undefined;
421
+ if (edgeMeta?.source === "USER_SHIM") {
422
+ shimEdgePairs.add(pairKey);
423
+ if (!shimLabelByEdgePair.has(pairKey)) {
424
+ const explicit = typeof edgeMeta.shimLabel === "string" ? edgeMeta.shimLabel.trim() : "";
425
+ let derived = explicit;
426
+ if (!derived && edge.name) {
427
+ const rawCall = edge.name.replace(/^Call:\s*/i, "").trim();
428
+ const dotIdx = rawCall.indexOf(".");
429
+ if (dotIdx > 0) {
430
+ const recv = rawCall.slice(0, dotIdx).replace(/[^A-Za-z0-9_$]/g, "");
431
+ if (recv && recv !== "this" && recv !== "self")
432
+ derived = recv;
433
+ }
434
+ }
435
+ shimLabelByEdgePair.set(pairKey, derived || "Custom adapter");
436
+ }
437
+ }
438
+ else {
439
+ deterministicEdgePairs.add(pairKey);
440
+ }
441
+ }
442
+ for (const pk of deterministicEdgePairs) {
443
+ shimEdgePairs.delete(pk);
444
+ }
445
+ const shimmedBadgeTargetsBySourceId = new Map();
446
+ for (const pk of shimEdgePairs) {
447
+ const [srcId, tgtId] = pk.split("::");
448
+ if (!srcId || !tgtId)
449
+ continue;
450
+ shimmedNodeIds.add(tgtId);
451
+ if (!shimLabelByNodeId.has(tgtId)) {
452
+ shimLabelByNodeId.set(tgtId, shimLabelByEdgePair.get(pk) ?? "Custom adapter");
453
+ }
454
+ const tgtNode = nodeById.get(tgtId);
455
+ if (tgtNode) {
456
+ const tgtClean = cleanNodeName(tgtNode.name).body;
457
+ const pkgSpec = tgtNode.name.replace(/^Package:\s*/i, "").trim();
458
+ const candidates = [
459
+ `Component: ${tgtClean}`,
460
+ `Middleware: ${tgtClean}`,
461
+ ...(pkgSpec ? [`Dependency: pkg:${pkgSpec}`] : []),
462
+ ];
463
+ let list = shimmedBadgeTargetsBySourceId.get(srcId);
464
+ if (!list) {
465
+ list = [];
466
+ shimmedBadgeTargetsBySourceId.set(srcId, list);
467
+ }
468
+ for (const cand of candidates) {
469
+ if (!list.includes(cand))
470
+ list.push(cand);
471
+ }
472
+ }
473
+ }
474
+ const receptorShimLabelByRealId = new Map();
475
+ const nonShimmedReceptorIds = new Set();
476
+ for (const n of rawGraph.nodes) {
477
+ if (n.type !== "OPEN_CONNECTOR")
478
+ continue;
479
+ const { body } = cleanNodeName(n.name);
480
+ const realPkg = packageOf(n.id);
481
+ const fallbackDialect = (realPkg && dialectInfo.dialectByPackage?.[realPkg]) ||
482
+ dialectInfo.defaultDialect;
483
+ const rec = classifyExternalReceptorSpec({
484
+ name: n.name,
485
+ label: body,
486
+ rawLabel: body,
487
+ entityType: n.entityType,
488
+ patternId: n.patternId,
489
+ metadata: n.metadata,
490
+ evidence: n.evidence,
491
+ }, fallbackDialect);
492
+ if (!rec)
493
+ continue;
494
+ if (shimmedNodeIds.has(n.id)) {
495
+ if (!nonShimmedReceptorIds.has(rec.receptorId) && !receptorShimLabelByRealId.has(rec.receptorId)) {
496
+ receptorShimLabelByRealId.set(rec.receptorId, shimLabelByNodeId.get(n.id) ?? "Custom adapter");
497
+ }
498
+ }
499
+ else {
500
+ nonShimmedReceptorIds.add(rec.receptorId);
501
+ receptorShimLabelByRealId.delete(rec.receptorId);
502
+ }
503
+ }
504
+ // 4. Anonymize nodes and build `hydrationMap`
505
+ const anonymizedNodes = rawGraph.nodes.map((n) => {
506
+ const { prefix, body } = cleanNodeName(n.name);
507
+ const realPkg = packageOf(n.id);
508
+ const pseudoPkg = pseudoPkgByRealPkg.get(realPkg) ?? realPkg;
509
+ // Resolve parent label (e.g. parent CLASS name) for hydration
510
+ let realParentLabel;
511
+ if (n.parentBoundaryId) {
512
+ const pNode = nodeById.get(n.parentBoundaryId);
513
+ if (pNode && pNode.entityType !== "DEPLOYMENT_UNIT") {
514
+ realParentLabel = cleanNodeName(pNode.name).body;
515
+ }
516
+ }
517
+ // Check if an active L1_SEMANTIC overlay overrides `humanLabel`
518
+ const nodeOvs = overlaysByEntityId.get(n.id);
519
+ let humanLabelOverride;
520
+ if (nodeOvs) {
521
+ for (const ov of nodeOvs) {
522
+ if (ov.layer === "L1_SEMANTIC" &&
523
+ !ov.stale &&
524
+ typeof ov.payload?.humanLabel === "string" &&
525
+ ov.payload.humanLabel.trim()) {
526
+ humanLabelOverride = ov.payload.humanLabel.trim();
527
+ }
528
+ }
529
+ }
530
+ let pseudoName = n.name;
531
+ if (n.entityType === "DEPLOYMENT_UNIT") {
532
+ pseudoName = `${prefix || "Deployment Unit: "}${pseudoPkg}`;
533
+ }
534
+ else if (n.entityType === "INIT_BLOCK") {
535
+ pseudoName = `${prefix || "Init Block: "}${pseudoPkg || "root"}`;
536
+ }
537
+ else if (n.entityType === "EXTERNAL_HTTP_CALL" ||
538
+ n.entityType === "HTTP_CLIENT_CALL" ||
539
+ n.patternId?.includes("http")) {
540
+ const urlMatch = n.name.match(/https?:\/\/([^/\s"'`)]+)/i);
541
+ if (urlMatch?.[1]) {
542
+ const realHost = urlMatch[1].replace(/^www\./i, "");
543
+ const pseudoHost = `api-${shortHash(`host:${realHost}`).slice(0, 8)}.example`;
544
+ const realSlug = realHost.toLowerCase().replace(/[^a-z0-9]+/g, "_");
545
+ const pseudoSlug = pseudoHost.toLowerCase().replace(/[^a-z0-9]+/g, "_");
546
+ realPkgByPseudoPkg.set(`HTTP: ${pseudoHost}`, `HTTP: ${realHost}`);
547
+ pseudoPkgByRealPkg.set(`HTTP: ${realHost}`, `HTTP: ${pseudoHost}`);
548
+ realReceptorIdByPseudoId.set(`__ext_receptor_http_${pseudoSlug}__`, `__ext_receptor_http_${realSlug}__`);
549
+ pseudoName = `${prefix || "HTTP Call: "}https://${pseudoHost}`;
550
+ }
551
+ else {
552
+ pseudoName = `${prefix || "HTTP Call: "}${getPseudoToken(body)}`;
553
+ }
554
+ }
555
+ else if (body.includes(".")) {
556
+ const [cls, mem] = body.split(".", 2);
557
+ const pseudoCls = getPseudoToken(cls);
558
+ const pseudoMem = getPseudoToken(mem);
559
+ pseudoName = `${prefix}${pseudoCls}.${pseudoMem}`;
560
+ }
561
+ else {
562
+ const pseudoBody = getPseudoToken(body);
563
+ pseudoName = `${prefix}${pseudoBody}`;
564
+ }
565
+ const pseudoCleanBody = cleanNodeName(pseudoName).body;
566
+ const realDisplayLabel = humanLabelOverride ?? body;
567
+ const pseudoDisplayLabel = humanLabelOverride
568
+ ? getPseudoToken(humanLabelOverride)
569
+ : pseudoCleanBody;
570
+ // Record badge mappings in case this node is folded as a Component/Middleware/Dependency/Schema badge
571
+ for (const badgeKind of ["Component", "Middleware", "Dependency", "Schema"]) {
572
+ realBadgeByPseudoBadge.set(`${badgeKind}: ${pseudoCleanBody}`, `${badgeKind}: ${body}`);
573
+ realBadgeByPseudoBadge.set(`${badgeKind}: ${pseudoDisplayLabel}`, `${badgeKind}: ${realDisplayLabel}`);
574
+ if (body.includes(".")) {
575
+ const shortMem = body.split(".").pop();
576
+ const pseudoShortMem = pseudoCleanBody.split(".").pop();
577
+ realBadgeByPseudoBadge.set(`${badgeKind}: ${pseudoShortMem}`, `${badgeKind}: ${shortMem}`);
578
+ }
579
+ }
580
+ const mergedPortValves = mergeContractPortValves(n.metadata, nodeOvs);
581
+ const portMismatchCount = mergedPortValves?.diagnostics?.length ?? 0;
582
+ const sanitizedEvidence = sanitizeEvidenceItems(n.evidence);
583
+ nodesById.set(n.id, {
584
+ id: n.id,
585
+ rawName: n.name,
586
+ cleanLabel: body,
587
+ ...(humanLabelOverride ? { humanLabel: humanLabelOverride } : {}),
588
+ ...(realParentLabel ? { parentLabel: realParentLabel } : {}),
589
+ realPackageLabel: realPkg,
590
+ ...(sanitizedEvidence ? { evidence: sanitizedEvidence } : {}),
591
+ ...(Array.isArray(n.metadata?.inputTypes)
592
+ ? { inputTypes: n.metadata.inputTypes }
593
+ : {}),
594
+ ...(typeof n.metadata?.outputType === "string"
595
+ ? { outputType: n.metadata.outputType }
596
+ : {}),
597
+ ...(mergedPortValves ? { portValves: mergedPortValves } : {}),
598
+ ...(portMismatchCount > 0 ? { portMismatchCount } : {}),
599
+ ...(nodeOvs ? { overlays: nodeOvs } : {}),
600
+ ...(shimmedNodeIds.has(n.id)
601
+ ? {
602
+ isShimmed: true,
603
+ shimLabel: shimLabelByNodeId.get(n.id) ?? "Custom adapter",
604
+ }
605
+ : {}),
606
+ ...(shimmedBadgeTargetsBySourceId.has(n.id)
607
+ ? { shimmedBadgeTargets: shimmedBadgeTargetsBySourceId.get(n.id) }
608
+ : {}),
609
+ });
610
+ // Anonymize evidence filePaths (preserving framework folder tokens & extensions) and strip snippets
611
+ const anonEvidence = n.evidence
612
+ ? Array.isArray(n.evidence)
613
+ ? n.evidence.map((ev) => ({
614
+ filePath: ev?.filePath ? pseudonymizeFilePath(ev.filePath) : "f_anon.ts",
615
+ ...(typeof ev?.lineNumber === "number"
616
+ ? { lineNumber: ev.lineNumber }
617
+ : {}),
618
+ ...(typeof ev?.evidenceRole === "string"
619
+ ? { evidenceRole: ev.evidenceRole }
620
+ : {}),
621
+ }))
622
+ : {
623
+ filePath: n.evidence?.filePath
624
+ ? pseudonymizeFilePath(n.evidence.filePath)
625
+ : "f_anon.ts",
626
+ ...(typeof n.evidence?.lineNumber === "number"
627
+ ? { lineNumber: n.evidence.lineNumber }
628
+ : {}),
629
+ ...(typeof n.evidence?.evidenceRole === "string"
630
+ ? { evidenceRole: n.evidence.evidenceRole }
631
+ : {}),
632
+ }
633
+ : undefined;
634
+ // Anonymize metadata while preserving layout-critical flags & type string lengths
635
+ const anonMetadata = {};
636
+ if (n.metadata) {
637
+ if (n.metadata.flowRole)
638
+ anonMetadata.flowRole = n.metadata.flowRole;
639
+ if (n.metadata.source === "USER_SHIM")
640
+ anonMetadata.source = "USER_SHIM";
641
+ if (typeof n.metadata.isImportedInRepo === "boolean") {
642
+ anonMetadata.isImportedInRepo = n.metadata.isImportedInRepo;
643
+ }
644
+ if (typeof n.metadata.astCallCount === "number") {
645
+ anonMetadata.astCallCount = n.metadata.astCallCount;
646
+ }
647
+ if (typeof n.metadata.bodyHash === "string") {
648
+ anonMetadata.bodyHash = n.metadata.bodyHash;
649
+ }
650
+ if (Array.isArray(n.metadata.inputTypes)) {
651
+ anonMetadata.inputTypes = n.metadata.inputTypes.map((t) => "T".repeat(Math.max(1, String(t).length)));
652
+ }
653
+ if (typeof n.metadata.outputType === "string") {
654
+ anonMetadata.outputType = "R".repeat(Math.max(1, n.metadata.outputType.length));
655
+ }
656
+ if (typeof n.metadata.dialect === "string") {
657
+ anonMetadata.dialect = n.metadata.dialect;
658
+ }
659
+ }
660
+ if (!anonMetadata.dialect &&
661
+ (n.entityType === "DB_QUERY" ||
662
+ n.entityType === "DB_OPERATION" ||
663
+ n.entityType === "DB_TRANSACTION")) {
664
+ const inferred = (realPkg && dialectInfo.dialectByPackage?.[realPkg]) ||
665
+ dialectInfo.defaultDialect;
666
+ if (inferred) {
667
+ anonMetadata.dialect = inferred;
668
+ }
669
+ }
670
+ return {
671
+ ...n,
672
+ name: pseudoName,
673
+ ...(anonEvidence ? { evidence: anonEvidence } : {}),
674
+ ...(Object.keys(anonMetadata).length > 0 ? { metadata: anonMetadata } : {}),
675
+ };
676
+ });
677
+ // 5. Anonymize edges (including unresolved call edge names & evidence)
678
+ const anonymizedEdges = rawGraph.edges.map((e) => {
679
+ const ev = Array.isArray(e.evidence) ? e.evidence[0] : e.evidence;
680
+ const lineNumber = typeof ev?.lineNumber === "number" ? ev.lineNumber : undefined;
681
+ let anonEdgeName = e.name;
682
+ if (!e.targetId && e.name) {
683
+ const rawCall = e.name.replace(/^Call:\s*/i, "").trim();
684
+ const pseudoCall = `call_${shortHash(`unres:${e.sourceId}:${rawCall}`).slice(0, 8)}`;
685
+ anonEdgeName = `Call: ${pseudoCall}`;
686
+ const key = `${e.sourceId}::${lineNumber ?? 0}::${pseudoCall}`;
687
+ realUnresolvedByKey.set(key, {
688
+ name: rawCall,
689
+ ...(ev?.filePath ? { filePath: String(ev.filePath) } : {}),
690
+ ...(lineNumber !== undefined ? { lineNumber } : {}),
691
+ ...(typeof e.metadata?.importSpecifier === "string"
692
+ ? { importSpecifier: e.metadata.importSpecifier }
693
+ : {}),
694
+ ...(typeof e.metadata?.resolvedFilePath === "string"
695
+ ? { resolvedFilePath: e.metadata.resolvedFilePath }
696
+ : {}),
697
+ ...(typeof e.metadata?.targetSymbol === "string"
698
+ ? { targetSymbol: e.metadata.targetSymbol }
699
+ : {}),
700
+ });
701
+ }
702
+ const anonEdgeEvidence = !e.targetId && lineNumber !== undefined
703
+ ? [{ filePath: "f.ts", lineNumber }]
704
+ : undefined;
705
+ const anonEdgeMeta = {};
706
+ if (e.metadata) {
707
+ if (e.metadata.source === "USER_SHIM")
708
+ anonEdgeMeta.source = "USER_SHIM";
709
+ if (e.metadata.shapeKey)
710
+ anonEdgeMeta.shapeKey = e.metadata.shapeKey;
711
+ if (e.metadata.viaHelper)
712
+ anonEdgeMeta.viaHelper = e.metadata.viaHelper;
713
+ if (e.metadata.unresolvedReason) {
714
+ anonEdgeMeta.unresolvedReason = e.metadata.unresolvedReason;
715
+ }
716
+ if (e.metadata.resolutionClass) {
717
+ anonEdgeMeta.resolutionClass = e.metadata.resolutionClass;
718
+ }
719
+ }
720
+ const { evidence: _rawEdgeEv, metadata: _rawEdgeMeta, ...edgeRest } = e;
721
+ return {
722
+ ...edgeRest,
723
+ name: anonEdgeName,
724
+ evidence: anonEdgeEvidence ?? [],
725
+ ...(Object.keys(anonEdgeMeta).length > 0 ? { metadata: anonEdgeMeta } : {}),
726
+ };
727
+ });
728
+ // 6. Pre-evaluate custom rules locally so raw regex patterns, filePath patterns,
729
+ // and overlay criteria never leave the user's machine.
730
+ let anonymizedRulesConfig;
731
+ if (rulesConfig) {
732
+ const resolvedCustomRules = [];
733
+ const enabledCustom = (rulesConfig.customRules ?? []).filter((r) => r.enabled);
734
+ for (const n of rawGraph.nodes) {
735
+ const realPkg = packageOf(n.id);
736
+ const { body } = cleanNodeName(n.name);
737
+ for (const rule of enabledCustom) {
738
+ if (matchesCustomRule({
739
+ id: n.id,
740
+ name: n.name,
741
+ label: body,
742
+ entityType: n.entityType,
743
+ patternId: n.patternId,
744
+ evidence: n.evidence,
745
+ overlays: overlaysByEntityId.get(n.id),
746
+ }, realPkg, rule)) {
747
+ let anonBadgeLabel;
748
+ if (rule.badgeLabel) {
749
+ anonBadgeLabel = `b_${shortHash(`rulebadge:${rule.id}:${rule.badgeLabel}`).slice(0, Math.max(4, rule.badgeLabel.length - 2))}`;
750
+ for (const kind of ["Component", "Middleware", "Schema"]) {
751
+ realBadgeByPseudoBadge.set(`${kind}: ${anonBadgeLabel}`, `${kind}: ${rule.badgeLabel}`);
752
+ }
753
+ }
754
+ resolvedCustomRules.push({
755
+ id: `${rule.id}__${n.id}`,
756
+ name: `rule_${shortHash(rule.id).slice(0, 6)}`,
757
+ enabled: true,
758
+ match: { nodeId: n.id },
759
+ action: rule.action,
760
+ ...(anonBadgeLabel ? { badgeLabel: anonBadgeLabel } : {}),
761
+ badgeMode: rule.badgeMode,
762
+ });
763
+ }
764
+ }
765
+ }
766
+ anonymizedRulesConfig = {
767
+ version: 1,
768
+ defaults: { ...rulesConfig.defaults },
769
+ customRules: resolvedCustomRules,
770
+ overlayLayers: rulesConfig.overlayLayers
771
+ ? { ...rulesConfig.overlayLayers }
772
+ : undefined,
773
+ };
774
+ }
775
+ // 7. Create minimal anonymized overlays preserving only `humanLabel` length
776
+ const anonymizedOverlays = overlays
777
+ ? overlays
778
+ .filter((ov) => ov && ov.layer === "L1_SEMANTIC" && !ov.stale)
779
+ .map((ov) => ({
780
+ entityId: ov.entityId,
781
+ layer: ov.layer,
782
+ source: "anon",
783
+ environment: ov.environment || "local",
784
+ stale: Boolean(ov.stale),
785
+ payload: typeof ov.payload?.humanLabel === "string" &&
786
+ ov.payload.humanLabel.trim()
787
+ ? {
788
+ humanLabel: getPseudoToken(ov.payload.humanLabel.trim()),
789
+ }
790
+ : {},
791
+ }))
792
+ : undefined;
793
+ // 8. Compact & anonymize `diffDelta` by stripping full `base` / `target` node & edge objects
794
+ // and omitting `UNCHANGED` entries (reduces diff payload size by >98% while preventing leaks).
795
+ let anonymizedDiffDelta;
796
+ if (diffDelta) {
797
+ const compactNodes = {};
798
+ for (const [id, entry] of Object.entries(diffDelta.nodes ?? {})) {
799
+ if (entry && entry.status && entry.status !== "UNCHANGED") {
800
+ compactNodes[id] = { status: entry.status };
801
+ }
802
+ }
803
+ const compactEdges = {};
804
+ for (const [id, entry] of Object.entries(diffDelta.edges ?? {})) {
805
+ if (entry && entry.status && entry.status !== "UNCHANGED") {
806
+ const srcId = (entry.target ?? entry.base)?.sourceId;
807
+ compactEdges[id] = {
808
+ status: entry.status,
809
+ ...(srcId ? { target: { sourceId: srcId } } : {}),
810
+ };
811
+ }
812
+ }
813
+ anonymizedDiffDelta = {
814
+ baseCommitSha: diffDelta.baseCommitSha
815
+ ? shortHash(`commit:${diffDelta.baseCommitSha}`).slice(0, 12)
816
+ : undefined,
817
+ ...(diffDelta.summary ? { summary: diffDelta.summary } : {}),
818
+ nodes: compactNodes,
819
+ edges: compactEdges,
820
+ };
821
+ }
822
+ return {
823
+ request: {
824
+ schemaVersion: "1.0",
825
+ graph: {
826
+ ...rawGraph,
827
+ repoId: `repo_${shortHash(rawGraph.repoId || "local").slice(0, 8)}`,
828
+ nodes: anonymizedNodes,
829
+ edges: anonymizedEdges,
830
+ },
831
+ ...(anonymizedDiffDelta ? { diffDelta: anonymizedDiffDelta } : {}),
832
+ ...(anonymizedRulesConfig ? { rulesConfig: anonymizedRulesConfig } : {}),
833
+ ...(anonymizedOverlays && anonymizedOverlays.length > 0
834
+ ? { overlays: anonymizedOverlays }
835
+ : {}),
836
+ },
837
+ hydrationMap: {
838
+ nodesById,
839
+ receptorShimLabelByRealId,
840
+ realPkgByPseudoPkg,
841
+ pseudoPkgByRealPkg,
842
+ realDisplayNameByRealPkg,
843
+ realBadgeByPseudoBadge,
844
+ realReceptorIdByPseudoId,
845
+ realUnresolvedByKey,
846
+ },
847
+ };
848
+ }
849
+ // ---------------------------------------------------------------------------
850
+ // Step 2: Local Re-Hydration (Restores Real Labels, Snippet-Free Evidence & Overlays)
851
+ // ---------------------------------------------------------------------------
852
+ function extractBaseOriginalIdFromLayoutNodeId(layoutNodeId) {
853
+ // Format: `${pkg}::${originalId}::row${row}` or `${originalId}::STORY-${idx}` or `${originalId}`
854
+ const parts = layoutNodeId.split("::");
855
+ if (parts.length >= 3 && /^row\d+$/.test(parts[parts.length - 1])) {
856
+ return {
857
+ pkgPrefix: parts[0],
858
+ originalId: parts.slice(1, -1).join("::"),
859
+ rowSuffix: parts[parts.length - 1],
860
+ };
861
+ }
862
+ if (parts.length === 2 && /^STORY-\d+$/.test(parts[1])) {
863
+ return { originalId: parts[0] };
864
+ }
865
+ return { originalId: layoutNodeId };
866
+ }
867
+ function rehydrateBadgeString(pseudoBadge, hydrationMap) {
868
+ const diffMatch = pseudoBadge.match(/\s+(\+ADDED|~MOD|-REM)$/);
869
+ const diffSuffix = diffMatch ? diffMatch[0] : "";
870
+ const coreBadge = diffMatch
871
+ ? pseudoBadge.slice(0, -diffSuffix.length)
872
+ : pseudoBadge;
873
+ const exact = hydrationMap.realBadgeByPseudoBadge.get(coreBadge);
874
+ if (exact)
875
+ return `${exact}${diffSuffix}`;
876
+ return pseudoBadge;
877
+ }
878
+ export function rehydrateCloudLayout(response, hydrationMap, rawGraph, repoName, overlays) {
879
+ const layout = response.layout;
880
+ const mapPkg = (pseudoPkg) => {
881
+ if (!pseudoPkg)
882
+ return pseudoPkg;
883
+ return hydrationMap.realPkgByPseudoPkg.get(pseudoPkg) ?? pseudoPkg;
884
+ };
885
+ const mapLayoutNodeId = (id) => {
886
+ const parsed = extractBaseOriginalIdFromLayoutNodeId(id);
887
+ const realOrigId = hydrationMap.realReceptorIdByPseudoId.get(parsed.originalId) ??
888
+ parsed.originalId;
889
+ if (parsed.pkgPrefix !== undefined && parsed.rowSuffix !== undefined) {
890
+ const realPkg = mapPkg(parsed.pkgPrefix) ?? parsed.pkgPrefix;
891
+ return `${realPkg}::${realOrigId}::${parsed.rowSuffix}`;
892
+ }
893
+ return realOrigId;
894
+ };
895
+ const rehydrateSingleNode = (node) => {
896
+ const parsed = extractBaseOriginalIdFromLayoutNodeId(node.id);
897
+ const baseNodeId = parsed.originalId.split("@")[0];
898
+ const entry = hydrationMap.nodesById.get(baseNodeId);
899
+ const realPkg = mapPkg(node.packageLabel);
900
+ // Preserve `(To: <pkg>)` cross-package suffix on EGRESS pins
901
+ const toPkgMatch = node.label.match(/\s*\(To:\s*(.*?)\)$/);
902
+ const realToSuffix = toPkgMatch
903
+ ? ` (To: ${mapPkg(toPkgMatch[1]) ?? toPkgMatch[1]})`
904
+ : "";
905
+ let realLabel = node.label;
906
+ let realRawLabel = node.rawLabel;
907
+ if (node.entityType === "EXTERNAL_SYSTEM") {
908
+ realLabel = realPkg ?? node.label;
909
+ realRawLabel = realLabel;
910
+ }
911
+ else if (entry) {
912
+ const baseDisplay = entry.humanLabel ?? entry.cleanLabel;
913
+ realLabel = `${baseDisplay}${realToSuffix}`;
914
+ realRawLabel = entry.cleanLabel;
915
+ }
916
+ const rehydratedMicroNodes = node.microNodes?.map((m) => {
917
+ const mEntry = hydrationMap.nodesById.get(m.originalId.split("@")[0]);
918
+ const mParsed = extractBaseOriginalIdFromLayoutNodeId(m.id);
919
+ const mRealPkg = (mParsed.pkgPrefix ? mapPkg(mParsed.pkgPrefix) : realPkg) ?? "";
920
+ return {
921
+ ...m,
922
+ id: mParsed.rowSuffix && mRealPkg
923
+ ? `${mRealPkg}::${m.originalId}::${mParsed.rowSuffix}`
924
+ : m.id,
925
+ label: mEntry ? (mEntry.humanLabel ?? mEntry.cleanLabel) : m.label,
926
+ ...(mEntry ? { rawLabel: mEntry.cleanLabel } : {}),
927
+ ...(mEntry?.parentLabel ? { parentLabel: mEntry.parentLabel } : {}),
928
+ ...(mEntry?.isShimmed ? { isShimmed: true } : {}),
929
+ };
930
+ });
931
+ if (rehydratedMicroNodes && rehydratedMicroNodes.length > 1) {
932
+ realLabel = `${rehydratedMicroNodes[0].label} (+${rehydratedMicroNodes.length - 1})`;
933
+ }
934
+ const rehydratedFolded = node.foldedFunctions?.map((fn) => {
935
+ const fEntry = hydrationMap.nodesById.get(fn.originalId.split("@")[0]);
936
+ const fEv = fEntry?.evidence?.[0];
937
+ return {
938
+ ...fn,
939
+ label: fEntry ? (fEntry.humanLabel ?? fEntry.cleanLabel) : fn.label,
940
+ ...(fEntry ? { rawLabel: fEntry.cleanLabel } : {}),
941
+ ...(fEntry?.parentLabel ? { parentLabel: fEntry.parentLabel } : {}),
942
+ ...(fEntry?.isShimmed ? { isShimmed: true } : {}),
943
+ ...(fEv?.filePath ? { filePath: fEv.filePath } : {}),
944
+ ...(typeof fEv?.lineNumber === "number"
945
+ ? { lineNumber: fEv.lineNumber }
946
+ : {}),
947
+ };
948
+ });
949
+ const rehydratedUnresolved = node.unresolvedCalls?.map((u) => {
950
+ const pseudoCall = u.name.replace(/^Call:\s*/i, "").trim();
951
+ const key = `${baseNodeId}::${u.lineNumber ?? 0}::${pseudoCall}`;
952
+ const realU = hydrationMap.realUnresolvedByKey.get(key);
953
+ if (!realU) {
954
+ const { snippet: _s, ...rest } = u;
955
+ return rest;
956
+ }
957
+ return {
958
+ ...u,
959
+ name: realU.name,
960
+ ...(realU.filePath ? { filePath: realU.filePath } : {}),
961
+ ...(realU.lineNumber !== undefined
962
+ ? { lineNumber: realU.lineNumber }
963
+ : {}),
964
+ ...(realU.importSpecifier
965
+ ? { importSpecifier: realU.importSpecifier }
966
+ : {}),
967
+ ...(realU.resolvedFilePath
968
+ ? { resolvedFilePath: realU.resolvedFilePath }
969
+ : {}),
970
+ ...(realU.targetSymbol ? { targetSymbol: realU.targetSymbol } : {}),
971
+ snippet: undefined,
972
+ };
973
+ });
974
+ const rehydratedBadges = (node.badges ?? []).map((b) => rehydrateBadgeString(b, hydrationMap));
975
+ const rehydratedShimmedBadges = entry?.shimmedBadgeTargets
976
+ ? rehydratedBadges.filter((rb) => {
977
+ const baseRb = rb.replace(/\s+(?:\+ADDED|~MOD|-REM)$/, "");
978
+ return entry.shimmedBadgeTargets.includes(baseRb);
979
+ })
980
+ : node.shimmedBadges;
981
+ const realReceptorId = hydrationMap.realReceptorIdByPseudoId.get(parsed.originalId) ??
982
+ parsed.originalId;
983
+ const isNodeShimmed = Boolean(entry?.isShimmed || node.isShimmed);
984
+ const rehydratedShimLabel = isNodeShimmed
985
+ ? entry?.shimLabel ??
986
+ hydrationMap.receptorShimLabelByRealId?.get(realReceptorId) ??
987
+ node.shimLabel ??
988
+ "Custom adapter"
989
+ : undefined;
990
+ return {
991
+ ...node,
992
+ id: mapLayoutNodeId(node.id),
993
+ label: realLabel,
994
+ ...(realRawLabel ? { rawLabel: realRawLabel } : {}),
995
+ ...(realPkg ? { packageLabel: realPkg } : {}),
996
+ ...(entry?.parentLabel ? { parentLabel: entry.parentLabel } : {}),
997
+ ...(entry?.evidence ? { evidence: entry.evidence } : {}),
998
+ ...(entry?.inputTypes ? { inputTypes: entry.inputTypes } : {}),
999
+ ...(entry?.outputType ? { outputType: entry.outputType } : {}),
1000
+ ...(entry?.portValves ? { portValves: entry.portValves } : {}),
1001
+ ...(entry?.portMismatchCount
1002
+ ? { portMismatchCount: entry.portMismatchCount }
1003
+ : {}),
1004
+ ...(entry?.overlays ? { overlays: entry.overlays } : {}),
1005
+ ...(isNodeShimmed
1006
+ ? {
1007
+ isShimmed: true,
1008
+ ...(rehydratedShimLabel ? { shimLabel: rehydratedShimLabel } : {}),
1009
+ }
1010
+ : {}),
1011
+ ...(rehydratedShimmedBadges && rehydratedShimmedBadges.length > 0
1012
+ ? { shimmedBadges: rehydratedShimmedBadges }
1013
+ : {}),
1014
+ badges: rehydratedBadges,
1015
+ ...(rehydratedMicroNodes ? { microNodes: rehydratedMicroNodes } : {}),
1016
+ ...(rehydratedFolded ? { foldedFunctions: rehydratedFolded } : {}),
1017
+ ...(rehydratedUnresolved ? { unresolvedCalls: rehydratedUnresolved } : {}),
1018
+ };
1019
+ };
1020
+ const rehydratedNodes = layout.nodes.map(rehydrateSingleNode);
1021
+ const rehydratedIslands = (layout.islandNodes ?? []).map(rehydrateSingleNode);
1022
+ const rehydratedInvariants = (layout.invariantNodes ?? []).map(rehydrateSingleNode);
1023
+ const rehydratedEdges = layout.edges.map((e) => {
1024
+ const sourceId = mapLayoutNodeId(e.sourceId);
1025
+ const targetId = mapLayoutNodeId(e.targetId);
1026
+ return {
1027
+ ...e,
1028
+ id: `${sourceId}→${targetId}`,
1029
+ sourceId,
1030
+ targetId,
1031
+ };
1032
+ });
1033
+ const rehydratedPackageBounds = {};
1034
+ if (layout.packageBounds) {
1035
+ for (const [pseudoPkg, bounds] of Object.entries(layout.packageBounds)) {
1036
+ const realPkg = mapPkg(pseudoPkg) ?? pseudoPkg;
1037
+ const restoredDisplayName = hydrationMap.realDisplayNameByRealPkg.get(realPkg) ??
1038
+ mapPkg(bounds.displayName) ??
1039
+ realPkg;
1040
+ rehydratedPackageBounds[realPkg] = {
1041
+ ...bounds,
1042
+ displayName: restoredDisplayName,
1043
+ };
1044
+ }
1045
+ }
1046
+ const rehydratedMacroEdges = layout.macroEdges?.map((me) => {
1047
+ const sourcePkg = mapPkg(me.sourcePkg) ?? me.sourcePkg;
1048
+ const targetPkg = mapPkg(me.targetPkg) ?? me.targetPkg;
1049
+ return {
1050
+ ...me,
1051
+ id: `macro:${sourcePkg}->${targetPkg}`,
1052
+ sourcePkg,
1053
+ targetPkg,
1054
+ };
1055
+ });
1056
+ const rehydratedStoryRows = (layout.storyRows ?? []).map((row) => {
1057
+ const realPkg = mapPkg(row.packageLabel) ?? row.packageLabel;
1058
+ return {
1059
+ ...row,
1060
+ entryLabel: realPkg,
1061
+ packageLabel: realPkg,
1062
+ };
1063
+ });
1064
+ const sanitizedRawGraph = stripEvidenceSnippetsFromGraph(rawGraph);
1065
+ const { systemHealth, packageHealthByPkg } = computeGraphHealthMetrics(sanitizedRawGraph, repoName, rehydratedIslands, {
1066
+ ...layout,
1067
+ nodes: rehydratedNodes,
1068
+ edges: rehydratedEdges,
1069
+ islandNodes: rehydratedIslands,
1070
+ invariantNodes: rehydratedInvariants,
1071
+ packageBounds: rehydratedPackageBounds,
1072
+ }, overlays);
1073
+ for (const [pkg, bounds] of Object.entries(rehydratedPackageBounds)) {
1074
+ const serverHealth = bounds.health;
1075
+ if (packageHealthByPkg[pkg]) {
1076
+ bounds.health = {
1077
+ ...packageHealthByPkg[pkg],
1078
+ ...(layout.entitlement?.previewMode && serverHealth
1079
+ ? {
1080
+ orphanCount: serverHealth.orphanCount,
1081
+ invariantCount: serverHealth.invariantCount,
1082
+ }
1083
+ : {}),
1084
+ };
1085
+ }
1086
+ }
1087
+ if (layout.entitlement?.previewMode && layout.healthSummary) {
1088
+ systemHealth.orphanCount = layout.healthSummary.orphanCount;
1089
+ systemHealth.invariantCount = layout.healthSummary.invariantCount;
1090
+ }
1091
+ const rehydratedEntitlement = layout.entitlement
1092
+ ? {
1093
+ ...layout.entitlement,
1094
+ ...(layout.entitlement.unlockedPackage
1095
+ ? {
1096
+ unlockedPackage: mapPkg(layout.entitlement.unlockedPackage) ??
1097
+ layout.entitlement.unlockedPackage,
1098
+ }
1099
+ : {}),
1100
+ }
1101
+ : undefined;
1102
+ return {
1103
+ ...layout,
1104
+ repoName,
1105
+ nodes: rehydratedNodes,
1106
+ edges: rehydratedEdges,
1107
+ islandNodes: rehydratedIslands,
1108
+ invariantNodes: rehydratedInvariants,
1109
+ packageBounds: rehydratedPackageBounds,
1110
+ macroEdges: rehydratedMacroEdges,
1111
+ storyRows: rehydratedStoryRows,
1112
+ healthSummary: systemHealth,
1113
+ ...(rehydratedEntitlement ? { entitlement: rehydratedEntitlement } : {}),
1114
+ ...(overlays ? { overlays } : {}),
1115
+ };
1116
+ }
1117
+ export async function requestStatelessCloudLayout(rawGraph, repoName, diffDelta, rulesConfig, overlays, options = {}) {
1118
+ const { request, hydrationMap } = anonymizeGraphForCloudLayout(rawGraph, diffDelta, rulesConfig, overlays);
1119
+ const explicitUrl = (options.cloudApiUrl ??
1120
+ process.env.CHOMP_LAYOUT_API_URL ??
1121
+ "")
1122
+ .trim()
1123
+ .replace(/\/+$/, "");
1124
+ if (!options.remote && !explicitUrl && hasLocalMasterLayoutEngine()) {
1125
+ // Master Monorepo Mode: in-process execution of the stateless skeleton pipeline with zero network calls
1126
+ const { executeStatelessLayout } = await loadLocalMasterLayoutEngine();
1127
+ const response = executeStatelessLayout(request);
1128
+ response.layout.entitlement = response.layout.entitlement ?? {
1129
+ tier: "master",
1130
+ status: "active",
1131
+ previewMode: false,
1132
+ gatingMode: "early_access",
1133
+ };
1134
+ return rehydrateCloudLayout(response, hydrationMap, rawGraph, repoName, overlays);
1135
+ }
1136
+ const baseUrl = explicitUrl || DEFAULT_CLOUD_API_URL;
1137
+ const controller = new AbortController();
1138
+ const timeout = setTimeout(() => controller.abort(), options.timeoutMs ?? 15_000);
1139
+ try {
1140
+ const headers = {
1141
+ "Content-Type": "application/json",
1142
+ Accept: "application/json",
1143
+ "X-Chomp-Schema-Version": "1.0",
1144
+ };
1145
+ const token = resolveActiveBearerToken(options.apiKey);
1146
+ if (token) {
1147
+ headers.Authorization = `Bearer ${token}`;
1148
+ }
1149
+ const bodyJson = JSON.stringify(request);
1150
+ let res;
1151
+ let lastFetchErr;
1152
+ // Retry up to 2 times on transient socket resets (`ECONNRESET` / `UND_ERR_SOCKET`)
1153
+ for (let attempt = 0; attempt < 3; attempt++) {
1154
+ try {
1155
+ res = await fetch(`${baseUrl}/v1/layout`, {
1156
+ method: "POST",
1157
+ headers,
1158
+ body: bodyJson,
1159
+ signal: controller.signal,
1160
+ });
1161
+ break;
1162
+ }
1163
+ catch (err) {
1164
+ lastFetchErr = err;
1165
+ const code = err?.cause?.code ?? err?.code ?? "";
1166
+ const isTransientSocketReset = code === "ECONNRESET" ||
1167
+ code === "EPIPE" ||
1168
+ code === "UND_ERR_SOCKET" ||
1169
+ /ECONNRESET|socket|fetch failed/i.test(String(err?.message ?? ""));
1170
+ if (!isTransientSocketReset || attempt === 2 || controller.signal.aborted) {
1171
+ const wrapped = new Error(`Unable to reach cloud layout worker (${baseUrl}): ${err?.message || "network error"}`);
1172
+ wrapped.code = "CLOUD_UNREACHABLE";
1173
+ wrapped.upstreamUrl = baseUrl;
1174
+ throw wrapped;
1175
+ }
1176
+ await new Promise((r) => setTimeout(r, 60 * (attempt + 1)));
1177
+ }
1178
+ }
1179
+ if (!res) {
1180
+ throw lastFetchErr ?? new Error("Cloud layout request failed");
1181
+ }
1182
+ if (!res.ok) {
1183
+ const errText = await res.text().catch(() => "");
1184
+ const rayId = res.headers.get("cf-ray")?.trim() || undefined;
1185
+ const isCf1102 = /\b1102\b/.test(errText);
1186
+ const raySuffix = rayId ? ` (cf-ray: ${rayId})` : "";
1187
+ const err = new Error(`Cloud layout worker returned HTTP ${res.status}: ${errText || res.statusText}${raySuffix}`);
1188
+ err.code = isCf1102 ? "CLOUD_WORKER_1102" : "CLOUD_WORKER_ERROR";
1189
+ err.upstreamStatus = res.status;
1190
+ err.rayId = rayId;
1191
+ err.upstreamUrl = baseUrl;
1192
+ throw err;
1193
+ }
1194
+ const response = (await res.json());
1195
+ return rehydrateCloudLayout(response, hydrationMap, rawGraph, repoName, overlays);
1196
+ }
1197
+ finally {
1198
+ clearTimeout(timeout);
1199
+ }
1200
+ }