@getchomp/cli 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.
Files changed (63) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +39 -2
  3. package/dist/commands/analyze.d.ts +49 -0
  4. package/dist/commands/analyze.js +280 -0
  5. package/dist/commands/connect.d.ts +12 -0
  6. package/dist/commands/connect.js +255 -0
  7. package/dist/commands/export.d.ts +29 -0
  8. package/dist/commands/export.js +356 -0
  9. package/dist/commands/health.d.ts +19 -0
  10. package/dist/commands/health.js +259 -0
  11. package/dist/commands/init.d.ts +40 -0
  12. package/dist/commands/init.js +659 -0
  13. package/dist/commands/mcp.d.ts +2 -0
  14. package/dist/commands/mcp.js +12 -0
  15. package/dist/commands/plugin.d.ts +8 -0
  16. package/dist/commands/plugin.js +198 -0
  17. package/dist/commands/ui.d.ts +20 -0
  18. package/dist/commands/ui.js +252 -0
  19. package/dist/commands/uninstall.d.ts +8 -0
  20. package/dist/commands/uninstall.js +246 -0
  21. package/dist/index.d.ts +3 -0
  22. package/dist/index.js +37 -0
  23. package/dist/ports/portHydrator.d.ts +63 -0
  24. package/dist/ports/portHydrator.js +954 -0
  25. package/dist/ports/portHydratorWorker.d.ts +22 -0
  26. package/dist/ports/portHydratorWorker.js +75 -0
  27. package/dist/server/buildStatusTracker.d.ts +45 -0
  28. package/dist/server/buildStatusTracker.js +122 -0
  29. package/dist/server/graphLayoutState.d.ts +205 -0
  30. package/dist/server/graphLayoutState.js +930 -0
  31. package/dist/server/loopbackSecurity.d.ts +18 -0
  32. package/dist/server/loopbackSecurity.js +57 -0
  33. package/dist/server/routes/authSourceRoutes.d.ts +18 -0
  34. package/dist/server/routes/authSourceRoutes.js +231 -0
  35. package/dist/server/routes/layoutRoutes.d.ts +3 -0
  36. package/dist/server/routes/layoutRoutes.js +857 -0
  37. package/dist/server/routes/pluginRoutes.d.ts +3 -0
  38. package/dist/server/routes/pluginRoutes.js +368 -0
  39. package/dist/server/routes/viewRulesRoutes.d.ts +3 -0
  40. package/dist/server/routes/viewRulesRoutes.js +173 -0
  41. package/dist/server/uiHotkeys.d.ts +26 -0
  42. package/dist/server/uiHotkeys.js +160 -0
  43. package/dist/utils/branding.d.ts +126 -0
  44. package/dist/utils/branding.js +978 -0
  45. package/dist/utils/credentials.d.ts +22 -0
  46. package/dist/utils/credentials.js +126 -0
  47. package/dist/utils/git.d.ts +95 -0
  48. package/dist/utils/git.js +780 -0
  49. package/dist/utils/masterContext.d.ts +112 -0
  50. package/dist/utils/masterContext.js +642 -0
  51. package/dist/visualizer/cloudLayoutClient.d.ts +84 -0
  52. package/dist/visualizer/cloudLayoutClient.js +1200 -0
  53. package/dist/visualizer/layoutCache.d.ts +25 -0
  54. package/dist/visualizer/layoutCache.js +406 -0
  55. package/dist/visualizer/localEngineBridge.d.ts +50 -0
  56. package/dist/visualizer/localEngineBridge.js +80 -0
  57. package/dist/visualizer/pluginPresentationApi.d.ts +111 -0
  58. package/dist/visualizer/pluginPresentationApi.js +432 -0
  59. package/dist/visualizer/rulesConfig.d.ts +11 -0
  60. package/dist/visualizer/rulesConfig.js +266 -0
  61. package/dist/visualizer/sourceAccess.d.ts +45 -0
  62. package/dist/visualizer/sourceAccess.js +204 -0
  63. package/package.json +52 -3
@@ -0,0 +1,930 @@
1
+ import { execFileSync, execSync } from "node:child_process";
2
+ import { createHash } from "node:crypto";
3
+ import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, statSync, unlinkSync, writeFileSync, } from "node:fs";
4
+ import { tmpdir } from "node:os";
5
+ import { basename, dirname, join, resolve } from "node:path";
6
+ import { CORE_EXTRACTOR_VERSION, analyzeTarget, compareGraphs, computeGraphHealthMetrics, validateLayoutPayload, } from "@getchomp/core";
7
+ import { createSQLiteStorage } from "@getchomp/db";
8
+ import { applyActivePluginProjections, discoverPluginsInDir, getPluginEnvStatus, getPluginMcpToolSummaries, getPluginStateDirRel, isRegisteredStructuralPluginOverlay, listChompPlugins, loadPluginSettings, readPluginLastRun, } from "@getchomp/mcp";
9
+ import { runPortHydrationInChildProcess, } from "../ports/portHydrator.js";
10
+ import { ansi, loadExcludeWorkspaces } from "../utils/branding.js";
11
+ import { resolveActiveBearerToken } from "../utils/credentials.js";
12
+ import { cleanGitEnv, getGitInfoFromFs, getGitRepoIdentity, listGitBranchesAndWorktrees, resolveGitRefCommitAsync, resolveRepoName, } from "../utils/git.js";
13
+ import { readMasterContext } from "../utils/masterContext.js";
14
+ import { requestStatelessCloudLayout, stripEvidenceSnippetsFromGraph, } from "../visualizer/cloudLayoutClient.js";
15
+ import { clearDiskLayoutCache, clearWorkingTreeFingerprintCache, } from "../visualizer/layoutCache.js";
16
+ import { DEFAULT_CLOUD_API_URL, hasLocalMasterLayoutEngine, loadLocalMasterLayoutEngine, } from "../visualizer/localEngineBridge.js";
17
+ import { computeStructureFingerprint, overlaysForStructureFingerprint, rulesReferenceOverlays, snapshotPluginRuns, splitOverlays, } from "../visualizer/pluginPresentationApi.js";
18
+ import { loadRulesConfig } from "../visualizer/rulesConfig.js";
19
+ import { LAYOUT_BUILD_STAGES, } from "./buildStatusTracker.js";
20
+ export function createUiServerState(params) {
21
+ return {
22
+ ...params,
23
+ pinToResolvedTarget: Boolean(params.pinToResolvedTarget ?? params.explicitDbOption),
24
+ resolvedIsWorktree: Boolean(params.resolvedIsWorktree),
25
+ latestEntitlement: params.isMasterLocalMode
26
+ ? {
27
+ tier: "master",
28
+ status: "active",
29
+ previewMode: false,
30
+ gatingMode: "early_access",
31
+ }
32
+ : undefined,
33
+ layoutCache: new Map(),
34
+ layoutInFlight: new Map(),
35
+ loggedBoardRevisions: new Set(),
36
+ pluginRuns: new Map(),
37
+ baseGraphCache: null,
38
+ baseGraphInFlight: null,
39
+ liveGraphCache: null,
40
+ workingTreeSnapshotCache: null,
41
+ latestDiffSummary: null,
42
+ portHydrationInFlight: null,
43
+ activePortHydrationHandle: null,
44
+ portHydrationQueued: false,
45
+ portHydrationForceQueued: false,
46
+ initialPortHydrationTriggered: false,
47
+ designSystemReportCache: null,
48
+ viewValidationCache: null,
49
+ };
50
+ }
51
+ export function getActiveUiTarget(state) {
52
+ if (!state.pinToResolvedTarget && !state.explicitDbOption) {
53
+ const ctx = readMasterContext();
54
+ if (ctx?.activeRepoPath && existsSync(ctx.activeRepoPath)) {
55
+ const tetheredDb = resolve(ctx.activeRepoPath, ".chomp", "graph.db");
56
+ if (existsSync(tetheredDb)) {
57
+ return {
58
+ target: ctx.activeRepoPath,
59
+ repoName: resolveRepoName(ctx.activeRepoPath),
60
+ dbPath: tetheredDb,
61
+ };
62
+ }
63
+ }
64
+ }
65
+ return {
66
+ target: state.resolvedTarget,
67
+ repoName: state.repoName,
68
+ dbPath: state.dbPath,
69
+ };
70
+ }
71
+ export function cancelActivePortHydration(state) {
72
+ state.portHydrationQueued = false;
73
+ state.portHydrationForceQueued = false;
74
+ if (state.activePortHydrationHandle) {
75
+ const handle = state.activePortHydrationHandle;
76
+ state.activePortHydrationHandle = null;
77
+ handle.cancel();
78
+ }
79
+ }
80
+ export function invalidateAllServerCaches(state) {
81
+ state.layoutCache.clear();
82
+ state.layoutInFlight.clear();
83
+ state.loggedBoardRevisions.clear();
84
+ state.baseGraphCache = null;
85
+ state.baseGraphInFlight = null;
86
+ state.liveGraphCache = null;
87
+ state.workingTreeSnapshotCache = null;
88
+ state.designSystemReportCache = null;
89
+ state.viewValidationCache = null;
90
+ clearWorkingTreeFingerprintCache();
91
+ }
92
+ export function invalidateAuthCachesOnly(state, activeDbPath) {
93
+ clearDiskLayoutCache(activeDbPath);
94
+ state.layoutCache.clear();
95
+ state.layoutInFlight.clear();
96
+ state.loggedBoardRevisions.clear();
97
+ }
98
+ export function getCurrentDbMtime(targetDbPath) {
99
+ return existsSync(targetDbPath) ? statSync(targetDbPath).mtimeMs : 0;
100
+ }
101
+ export function getLocalShimsFileFp(targetRepoPath) {
102
+ if (!targetRepoPath)
103
+ return "0";
104
+ const shimsPath = resolve(targetRepoPath, ".chomp", "plugins", "local-shims", "shims.json");
105
+ if (!existsSync(shimsPath))
106
+ return "0";
107
+ try {
108
+ const st = statSync(shimsPath);
109
+ return `${st.mtimeMs}:${st.size}`;
110
+ }
111
+ catch {
112
+ return "0";
113
+ }
114
+ }
115
+ export function getAuthModeFingerprint(state) {
116
+ const activeBearer = resolveActiveBearerToken();
117
+ const bearerTag = activeBearer
118
+ ? createHash("sha1").update(activeBearer).digest("hex").slice(0, 12)
119
+ : "anon";
120
+ return `${state.isMasterLocalMode ? "master" : state.resolvedCloudApiUrl}:${bearerTag}`;
121
+ }
122
+ export async function loadBaseGraphCached(state) {
123
+ const { target: activeTarget, dbPath: activeDbPath } = getActiveUiTarget(state);
124
+ const currentMtime = getCurrentDbMtime(activeDbPath);
125
+ const dbKey = `${activeDbPath}:${currentMtime}`;
126
+ if (state.baseGraphCache && state.baseGraphCache.key === dbKey) {
127
+ return state.baseGraphCache;
128
+ }
129
+ if (state.baseGraphInFlight) {
130
+ return state.baseGraphInFlight;
131
+ }
132
+ state.baseGraphInFlight = (async () => {
133
+ try {
134
+ const storage = createSQLiteStorage(activeDbPath);
135
+ const repos = await storage.listRepositories();
136
+ if (repos.length === 0) {
137
+ await storage.close();
138
+ return null;
139
+ }
140
+ const repo = repos[0];
141
+ const graph = await storage.getRepresentationGraph(repo.id);
142
+ const overlays = await storage.getEntityOverlays(repo.id);
143
+ await storage.close();
144
+ if (!graph)
145
+ return null;
146
+ // Closing a WAL-mode SQLite connection checkpoints `-wal` into `graph.db`,
147
+ // updating `mtimeMs`. Record the post-close `mtimeMs` so subsequent reads hit cache.
148
+ const postCloseMtime = getCurrentDbMtime(activeDbPath);
149
+ const finalKey = `${activeDbPath}:${postCloseMtime}`;
150
+ const split = splitOverlays(overlays);
151
+ const repoPathForPlugins = repo.path || activeTarget;
152
+ const repoLocalPluginsDir = resolve(repoPathForPlugins, ".chomp", "plugins");
153
+ if (existsSync(repoLocalPluginsDir)) {
154
+ await discoverPluginsInDir(repoLocalPluginsDir);
155
+ }
156
+ state.baseGraphCache = {
157
+ key: finalKey,
158
+ mtime: postCloseMtime,
159
+ repo,
160
+ graph,
161
+ overlays,
162
+ structuralOverlays: split.layout,
163
+ pluginOverlays: split.plugin,
164
+ structureFp: computeStructureFingerprint(graph.nodes, graph.edges, overlaysForStructureFingerprint(split, rulesReferenceOverlays(loadRulesConfig(activeDbPath).customRules), isRegisteredStructuralPluginOverlay)),
165
+ };
166
+ return state.baseGraphCache;
167
+ }
168
+ finally {
169
+ state.baseGraphInFlight = null;
170
+ }
171
+ })();
172
+ return state.baseGraphInFlight;
173
+ }
174
+ export function hydratePluginRunsForRepo(state, repoPath) {
175
+ const snap = snapshotPluginRuns(state.pluginRuns);
176
+ if (!repoPath)
177
+ return snap;
178
+ for (const p of listChompPlugins()) {
179
+ const mem = snap[p.name];
180
+ if (mem?.state === "running")
181
+ continue;
182
+ const disk = readPluginLastRun(repoPath, p.name);
183
+ if (!disk)
184
+ continue;
185
+ if (!mem || !mem.finishedAt || disk.finishedAt >= mem.finishedAt) {
186
+ snap[p.name] = {
187
+ state: disk.status === "error" ? "error" : "idle",
188
+ startedAt: disk.startedAt,
189
+ finishedAt: disk.finishedAt,
190
+ ...(disk.error ? { error: disk.error } : {}),
191
+ };
192
+ }
193
+ }
194
+ return snap;
195
+ }
196
+ export function getPluginRegistryMeta(repoPath) {
197
+ return listChompPlugins().map((p) => {
198
+ const settings = p.settingsSchema ? loadPluginSettings(repoPath, p) : undefined;
199
+ const envStatus = settings ? getPluginEnvStatus(p, settings) : undefined;
200
+ const lastRun = readPluginLastRun(repoPath, p.name);
201
+ return {
202
+ name: p.name,
203
+ displayName: p.displayName,
204
+ description: p.description,
205
+ version: p.version,
206
+ ...(p.order !== undefined ? { order: p.order } : {}),
207
+ layer: p.layer,
208
+ defaultEnabled: p.defaultEnabled ?? true,
209
+ ...(p.inspectorScopes ? { inspectorScopes: p.inspectorScopes } : {}),
210
+ stateDir: getPluginStateDirRel(p.name),
211
+ ...(p.settingsSchema ? { settingsSchema: p.settingsSchema } : {}),
212
+ ...(settings ? { settings } : {}),
213
+ ...(envStatus ? { envStatus } : {}),
214
+ ...(p.mcpTools && p.mcpTools.length > 0 ? { mcpTools: getPluginMcpToolSummaries(p) } : {}),
215
+ ...(lastRun
216
+ ? {
217
+ lastRun: {
218
+ status: lastRun.status,
219
+ startedAt: lastRun.startedAt,
220
+ finishedAt: lastRun.finishedAt,
221
+ durationMs: lastRun.durationMs,
222
+ ...(lastRun.overlayCount !== undefined ? { overlayCount: lastRun.overlayCount } : {}),
223
+ ...(lastRun.presentationWarnings.length > 0
224
+ ? { presentationWarnings: lastRun.presentationWarnings }
225
+ : {}),
226
+ ...(lastRun.error ? { error: lastRun.error } : {}),
227
+ },
228
+ }
229
+ : {}),
230
+ };
231
+ });
232
+ }
233
+ export function getDirtyRepoPathsForDiff(repoPath) {
234
+ try {
235
+ const out = execSync("git status --porcelain -uall", {
236
+ cwd: repoPath,
237
+ encoding: "utf8",
238
+ stdio: ["ignore", "pipe", "ignore"],
239
+ });
240
+ const dirty = new Set();
241
+ for (const line of out.split("\n")) {
242
+ if (!line)
243
+ continue;
244
+ const raw = line.slice(3).trim();
245
+ if (!raw)
246
+ continue;
247
+ if (raw.includes(" -> ")) {
248
+ const [orig, dest] = raw.split(" -> ");
249
+ if (orig)
250
+ dirty.add(orig.trim().replace(/\\/g, "/"));
251
+ if (dest)
252
+ dirty.add(dest.trim().replace(/\\/g, "/"));
253
+ }
254
+ else {
255
+ dirty.add(raw.replace(/\\/g, "/"));
256
+ }
257
+ }
258
+ return dirty;
259
+ }
260
+ catch {
261
+ return null;
262
+ }
263
+ }
264
+ export function getChangedRepoPathsBetweenCommits(repoPath, baseSha, targetSha) {
265
+ const cleanBase = baseSha.trim();
266
+ const cleanTarget = targetSha.trim();
267
+ if (!cleanBase || !cleanTarget)
268
+ return null;
269
+ if (cleanBase === cleanTarget)
270
+ return new Set();
271
+ try {
272
+ const out = execFileSync("git", ["diff", "--name-only", `${cleanBase}..${cleanTarget}`], {
273
+ cwd: repoPath,
274
+ encoding: "utf8",
275
+ stdio: ["ignore", "pipe", "ignore"],
276
+ env: cleanGitEnv(),
277
+ });
278
+ const changed = new Set();
279
+ for (const line of out.split(/\r?\n/)) {
280
+ const trimmed = line.trim();
281
+ if (trimmed) {
282
+ changed.add(trimmed.replace(/\\/g, "/"));
283
+ }
284
+ }
285
+ return changed;
286
+ }
287
+ catch {
288
+ return null;
289
+ }
290
+ }
291
+ export function resolveScopedDiffPaths(repoPath, baseSha, targetSha, isWorkingTree) {
292
+ const wtDirty = getDirtyRepoPathsForDiff(repoPath);
293
+ const headSha = getGitInfoFromFs(repoPath).commitSha?.trim();
294
+ const shaMatches = (a, b) => Boolean(a && b && (a.startsWith(b) || b.startsWith(a)));
295
+ if (isWorkingTree) {
296
+ if (!wtDirty)
297
+ return null;
298
+ if (baseSha && headSha && !shaMatches(headSha, baseSha.trim())) {
299
+ const headDiff = getChangedRepoPathsBetweenCommits(repoPath, baseSha, headSha);
300
+ if (!headDiff)
301
+ return null;
302
+ for (const p of headDiff)
303
+ wtDirty.add(p);
304
+ }
305
+ return wtDirty;
306
+ }
307
+ if (!baseSha || !targetSha)
308
+ return null;
309
+ const branchDiff = getChangedRepoPathsBetweenCommits(repoPath, baseSha, targetSha);
310
+ if (!branchDiff)
311
+ return null;
312
+ const scoped = new Set(branchDiff);
313
+ if (wtDirty) {
314
+ for (const p of wtDirty)
315
+ scoped.add(p);
316
+ }
317
+ if (headSha &&
318
+ !shaMatches(headSha, baseSha.trim()) &&
319
+ !shaMatches(headSha, targetSha.trim())) {
320
+ const headToBase = getChangedRepoPathsBetweenCommits(repoPath, headSha, baseSha);
321
+ if (!headToBase)
322
+ return null;
323
+ for (const p of headToBase)
324
+ scoped.add(p);
325
+ }
326
+ return scoped;
327
+ }
328
+ export function readGitBlobForDiff(repoPath, commitSha, relPath, dirtyPaths) {
329
+ const normRel = relPath.replace(/\\/g, "/").replace(/^\.?\//, "");
330
+ if (dirtyPaths && !dirtyPaths.has(normRel)) {
331
+ const absPath = resolve(repoPath, normRel);
332
+ try {
333
+ return existsSync(absPath) ? readFileSync(absPath, "utf8") : null;
334
+ }
335
+ catch {
336
+ // Fall back to git show if disk read fails
337
+ }
338
+ }
339
+ try {
340
+ return execFileSync("git", ["show", `${commitSha}:${normRel}`], {
341
+ cwd: repoPath,
342
+ encoding: "utf8",
343
+ stdio: ["ignore", "pipe", "ignore"],
344
+ env: cleanGitEnv(),
345
+ });
346
+ }
347
+ catch {
348
+ return null;
349
+ }
350
+ }
351
+ export function hasGitCommitForDiff(repoPath, commitSha) {
352
+ if (!commitSha || !/^[0-9a-f]{7,40}$/i.test(commitSha.trim()))
353
+ return false;
354
+ try {
355
+ execFileSync("git", ["cat-file", "-e", `${commitSha.trim()}^{commit}`], {
356
+ cwd: repoPath,
357
+ stdio: ["ignore", "ignore", "ignore"],
358
+ env: cleanGitEnv(),
359
+ });
360
+ return true;
361
+ }
362
+ catch {
363
+ return false;
364
+ }
365
+ }
366
+ function filterToUserScopeGraph(raw) {
367
+ const userNodes = raw.nodes.filter((n) => (n.scope ?? "USER") === "USER");
368
+ const userNodeIds = new Set(userNodes.map((n) => n.id));
369
+ return {
370
+ ...raw,
371
+ nodes: userNodes,
372
+ edges: raw.edges
373
+ .filter((e) => (e.scope ?? "USER") === "USER")
374
+ .map((e) => e.targetId && !userNodeIds.has(e.targetId)
375
+ ? { ...e, targetId: undefined }
376
+ : e),
377
+ };
378
+ }
379
+ export function extractFilteredLiveUserGraph(repoPath) {
380
+ const excludeWorkspaces = loadExcludeWorkspaces(repoPath);
381
+ const rawLive = analyzeTarget(repoPath, CORE_EXTRACTOR_VERSION, undefined, excludeWorkspaces);
382
+ return filterToUserScopeGraph(rawLive);
383
+ }
384
+ const MAX_REF_GRAPH_CACHE_FILES = 12;
385
+ function writeRefGraphDiskCache(cacheDir, fullCommitSha, commitMessage, graph) {
386
+ try {
387
+ mkdirSync(cacheDir, { recursive: true });
388
+ const cachePath = join(cacheDir, `ref-graph-${fullCommitSha.slice(0, 12)}.json`);
389
+ writeFileSync(cachePath, JSON.stringify({
390
+ extractorVersion: CORE_EXTRACTOR_VERSION,
391
+ fullCommitSha,
392
+ commitMessage,
393
+ savedAt: new Date().toISOString(),
394
+ graph,
395
+ }), "utf8");
396
+ const entries = readdirSync(cacheDir)
397
+ .filter((f) => f.startsWith("ref-graph-") && f.endsWith(".json"))
398
+ .map((f) => {
399
+ const full = join(cacheDir, f);
400
+ let mtimeMs = 0;
401
+ try {
402
+ mtimeMs = statSync(full).mtimeMs;
403
+ }
404
+ catch {
405
+ // ignore
406
+ }
407
+ return { full, mtimeMs };
408
+ })
409
+ .sort((a, b) => b.mtimeMs - a.mtimeMs);
410
+ for (const stale of entries.slice(MAX_REF_GRAPH_CACHE_FILES)) {
411
+ try {
412
+ unlinkSync(stale.full);
413
+ }
414
+ catch {
415
+ // ignore
416
+ }
417
+ }
418
+ }
419
+ catch {
420
+ // Non-fatal if cache dir is read-only
421
+ }
422
+ }
423
+ export function seedRefGraphDiskCache(params) {
424
+ const cleanSha = params.fullCommitSha.trim();
425
+ if (!/^[0-9a-f]{40}$/i.test(cleanSha))
426
+ return;
427
+ const filtered = filterToUserScopeGraph({
428
+ ...params.graph,
429
+ commitSha: cleanSha,
430
+ ...(params.branchName ? { branchName: params.branchName } : {}),
431
+ });
432
+ const localCacheDir = join(dirname(params.dbPath), "cache");
433
+ writeRefGraphDiskCache(localCacheDir, cleanSha, params.commitMessage, filtered);
434
+ const identity = getGitRepoIdentity(params.repoPath);
435
+ if (identity?.isLinkedWorktree &&
436
+ identity.primaryRepoRoot &&
437
+ existsSync(resolve(identity.primaryRepoRoot, ".chomp"))) {
438
+ const sharedCacheDir = resolve(identity.primaryRepoRoot, ".chomp", "cache");
439
+ if (resolve(sharedCacheDir) !== resolve(localCacheDir)) {
440
+ writeRefGraphDiskCache(sharedCacheDir, cleanSha, params.commitMessage, filtered);
441
+ }
442
+ }
443
+ }
444
+ export function tryReuseInMemoryBaseGraph(ctx, refInfo) {
445
+ const { activeDbPath, baseData, activeCommitSha, workingTreeDirty } = ctx;
446
+ if (baseData.graph.extractorVersion &&
447
+ baseData.graph.extractorVersion !== CORE_EXTRACTOR_VERSION) {
448
+ return null;
449
+ }
450
+ let snapCommitSha;
451
+ const snapPath = resolve(dirname(activeDbPath), "base_snapshot.json");
452
+ if (existsSync(snapPath)) {
453
+ try {
454
+ const snap = JSON.parse(readFileSync(snapPath, "utf8"));
455
+ if (snap?.workingTreeDirty === true)
456
+ return null;
457
+ if (typeof snap?.commitSha === "string" && snap.commitSha.trim()) {
458
+ snapCommitSha = snap.commitSha.trim();
459
+ }
460
+ }
461
+ catch {
462
+ // Ignore malformed base_snapshot.json
463
+ }
464
+ }
465
+ else if (workingTreeDirty === true) {
466
+ return null;
467
+ }
468
+ const recordedSha = (snapCommitSha ??
469
+ baseData.repo.commitSha ??
470
+ baseData.graph.commitSha ??
471
+ (!existsSync(snapPath) && !workingTreeDirty ? activeCommitSha : undefined))?.trim();
472
+ if (!recordedSha ||
473
+ (!refInfo.fullCommitSha.startsWith(recordedSha) &&
474
+ !recordedSha.startsWith(refInfo.fullCommitSha))) {
475
+ return null;
476
+ }
477
+ const filtered = filterToUserScopeGraph({
478
+ ...baseData.graph,
479
+ commitSha: refInfo.fullCommitSha,
480
+ ...(refInfo.branchName ? { branchName: refInfo.branchName } : {}),
481
+ });
482
+ return {
483
+ ref: refInfo.ref,
484
+ commitSha: refInfo.commitSha,
485
+ fullCommitSha: refInfo.fullCommitSha,
486
+ ...(refInfo.branchName ? { branchName: refInfo.branchName } : {}),
487
+ ...(refInfo.commitMessage ? { commitMessage: refInfo.commitMessage } : {}),
488
+ graph: filtered,
489
+ tier: "memory",
490
+ };
491
+ }
492
+ function worktreeHasAlignedPackageName(wtPath, repoPath) {
493
+ if (basename(resolve(wtPath)) === basename(resolve(repoPath)))
494
+ return true;
495
+ try {
496
+ const pkgJsonPath = resolve(wtPath, "package.json");
497
+ if (!existsSync(pkgJsonPath))
498
+ return false;
499
+ const pkg = JSON.parse(readFileSync(pkgJsonPath, "utf8"));
500
+ return Boolean(typeof pkg?.name === "string" && pkg.name.trim());
501
+ }
502
+ catch {
503
+ return false;
504
+ }
505
+ }
506
+ /**
507
+ * Resolves the Layer 0 `RepresentationGraph` for any committed Git branch or SHA
508
+ * using a 4-tier fast path:
509
+ * 0. Clean in-memory `baseData.graph` match (`0ms` memory hit)
510
+ * 1. `.chomp/cache/ref-graph-<sha12>.json` (`<5ms` disk hit across local or primary worktree cache)
511
+ * 2. Checked-out local Git worktree `.chomp/graph.db` matching `fullCommitSha` (`<15ms` SQLite hit)
512
+ * 3. Clean `git archive <sha>` extraction + `analyzeTarget`, persisted to `.chomp/cache/`
513
+ */
514
+ export async function resolveCommittedRefGraph(repoPath, refOrBranch, options) {
515
+ const resolved = options?.resolvedRef ?? (await resolveGitRefCommitAsync(repoPath, refOrBranch));
516
+ if (!resolved) {
517
+ throw new Error(`Unable to resolve git ref '${refOrBranch}' in ${repoPath}`);
518
+ }
519
+ const { fullCommitSha, commitSha, branchName, commitMessage } = resolved;
520
+ // Tier 0: Clean in-memory baseData.graph hit (0ms)
521
+ if (!options?.forceRefresh && options?.inMemoryBase) {
522
+ const memHit = tryReuseInMemoryBaseGraph(options.inMemoryBase, {
523
+ ...resolved,
524
+ ref: refOrBranch,
525
+ });
526
+ if (memHit) {
527
+ return memHit;
528
+ }
529
+ }
530
+ const cacheDir = options?.dbPath
531
+ ? join(dirname(options.dbPath), "cache")
532
+ : resolve(repoPath, ".chomp", "cache");
533
+ const cacheFilename = `ref-graph-${fullCommitSha.slice(0, 12)}.json`;
534
+ const candidateCachePaths = [join(cacheDir, cacheFilename)];
535
+ const identity = getGitRepoIdentity(repoPath);
536
+ if (identity?.primaryRepoRoot) {
537
+ const sharedPath = join(resolve(identity.primaryRepoRoot, ".chomp", "cache"), cacheFilename);
538
+ if (!candidateCachePaths.includes(sharedPath)) {
539
+ candidateCachePaths.push(sharedPath);
540
+ }
541
+ }
542
+ // Tier 1: Disk cache hit (<5ms)
543
+ if (!options?.forceRefresh) {
544
+ for (const refCachePath of candidateCachePaths) {
545
+ if (!existsSync(refCachePath))
546
+ continue;
547
+ try {
548
+ const parsed = JSON.parse(readFileSync(refCachePath, "utf8"));
549
+ if (parsed?.extractorVersion === CORE_EXTRACTOR_VERSION &&
550
+ parsed?.fullCommitSha === fullCommitSha &&
551
+ parsed?.graph &&
552
+ Array.isArray(parsed.graph.nodes)) {
553
+ return {
554
+ ref: refOrBranch,
555
+ commitSha,
556
+ fullCommitSha,
557
+ branchName,
558
+ commitMessage: commitMessage ?? parsed.commitMessage,
559
+ graph: parsed.graph,
560
+ tier: "disk-cache",
561
+ };
562
+ }
563
+ }
564
+ catch {
565
+ // Fall through to next cache path / Tier 2 / Tier 3 on corrupt cache entry
566
+ }
567
+ }
568
+ }
569
+ // Tier 2: Active worktree .chomp/graph.db hit (<15ms)
570
+ try {
571
+ const gitTargets = await listGitBranchesAndWorktrees(repoPath);
572
+ const candidateWorktrees = gitTargets.branches
573
+ .filter((b) => b.worktreePath &&
574
+ b.hasCachedGraphDb &&
575
+ (b.fullCommitSha === fullCommitSha || b.name === refOrBranch))
576
+ .map((b) => b.worktreePath);
577
+ const selfDb = resolve(repoPath, ".chomp", "graph.db");
578
+ if (existsSync(selfDb) && !candidateWorktrees.includes(resolve(repoPath))) {
579
+ candidateWorktrees.push(resolve(repoPath));
580
+ }
581
+ for (const wtPath of candidateWorktrees) {
582
+ if (!worktreeHasAlignedPackageName(wtPath, repoPath))
583
+ continue;
584
+ const wtDbPath = resolve(wtPath, ".chomp", "graph.db");
585
+ if (!existsSync(wtDbPath))
586
+ continue;
587
+ const snapPath = resolve(wtPath, ".chomp", "base_snapshot.json");
588
+ if (existsSync(snapPath)) {
589
+ try {
590
+ const snap = JSON.parse(readFileSync(snapPath, "utf8"));
591
+ if (snap?.workingTreeDirty === true)
592
+ continue;
593
+ }
594
+ catch {
595
+ // Ignore malformed snapshot metadata
596
+ }
597
+ }
598
+ const storage = createSQLiteStorage(wtDbPath);
599
+ try {
600
+ const repos = await storage.listRepositories();
601
+ const repoRec = repos[0];
602
+ if (!repoRec?.commitSha)
603
+ continue;
604
+ const recSha = repoRec.commitSha.trim();
605
+ if (!fullCommitSha.startsWith(recSha) && !recSha.startsWith(fullCommitSha)) {
606
+ continue;
607
+ }
608
+ const dbGraph = await storage.getRepresentationGraph(repoRec.id);
609
+ if (dbGraph &&
610
+ (!dbGraph.extractorVersion || dbGraph.extractorVersion === CORE_EXTRACTOR_VERSION)) {
611
+ const filtered = filterToUserScopeGraph({
612
+ ...dbGraph,
613
+ commitSha: fullCommitSha,
614
+ ...(branchName ? { branchName } : {}),
615
+ });
616
+ writeRefGraphDiskCache(cacheDir, fullCommitSha, commitMessage, filtered);
617
+ return {
618
+ ref: refOrBranch,
619
+ commitSha,
620
+ fullCommitSha,
621
+ branchName,
622
+ commitMessage,
623
+ graph: filtered,
624
+ tier: "worktree-db",
625
+ };
626
+ }
627
+ }
628
+ finally {
629
+ await storage.close();
630
+ }
631
+ }
632
+ }
633
+ catch {
634
+ // Fall through to Tier 3 git archive extraction
635
+ }
636
+ // Tier 3: Clean git archive extraction + analyzeTarget + disk cache persistence
637
+ const excludeWorkspaces = loadExcludeWorkspaces(repoPath);
638
+ const tempDir = join(tmpdir(), `chomp-ref-${fullCommitSha.slice(0, 12)}-${Date.now()}-${Math.random().toString(36).slice(2, 6)}`);
639
+ const archiveRoot = join(tempDir, basename(resolve(repoPath)) || "repo");
640
+ mkdirSync(archiveRoot, { recursive: true });
641
+ try {
642
+ const archiveBuf = execFileSync("git", ["archive", "--format=tar", fullCommitSha], {
643
+ cwd: repoPath,
644
+ env: cleanGitEnv(),
645
+ maxBuffer: 128 * 1024 * 1024,
646
+ stdio: ["ignore", "pipe", "ignore"],
647
+ });
648
+ execFileSync("tar", ["-x", "-C", archiveRoot], {
649
+ input: archiveBuf,
650
+ stdio: ["pipe", "ignore", "ignore"],
651
+ });
652
+ const rawGraph = analyzeTarget(archiveRoot, CORE_EXTRACTOR_VERSION, fullCommitSha, excludeWorkspaces);
653
+ const filtered = filterToUserScopeGraph({
654
+ ...rawGraph,
655
+ commitSha: fullCommitSha,
656
+ ...(branchName ? { branchName } : {}),
657
+ });
658
+ writeRefGraphDiskCache(cacheDir, fullCommitSha, commitMessage, filtered);
659
+ return {
660
+ ref: refOrBranch,
661
+ commitSha,
662
+ fullCommitSha,
663
+ branchName,
664
+ commitMessage,
665
+ graph: filtered,
666
+ tier: "git-archive",
667
+ };
668
+ }
669
+ finally {
670
+ if (existsSync(tempDir)) {
671
+ rmSync(tempDir, { recursive: true, force: true });
672
+ }
673
+ }
674
+ }
675
+ export function resolveWorkingTreeSnapshotGraph(state, repoPath, wtFingerprint, forceRefresh = false) {
676
+ const absRepo = resolve(repoPath);
677
+ if (!forceRefresh &&
678
+ state.workingTreeSnapshotCache &&
679
+ state.workingTreeSnapshotCache.repoPath === absRepo) {
680
+ return {
681
+ snapshotAt: state.workingTreeSnapshotCache.snapshotAt,
682
+ liveGraph: state.workingTreeSnapshotCache.liveGraph,
683
+ };
684
+ }
685
+ const liveGraph = extractFilteredLiveUserGraph(absRepo);
686
+ const snapshotAt = new Date().toISOString();
687
+ state.workingTreeSnapshotCache = {
688
+ repoPath: absRepo,
689
+ snapshotAt,
690
+ wtFingerprint,
691
+ liveGraph,
692
+ };
693
+ return { snapshotAt, liveGraph };
694
+ }
695
+ const yieldEventLoop = () => new Promise((resolveYield) => setImmediate(resolveYield));
696
+ export async function buildLayout(graph, repoPath, diffMode, repoName = "repository", cachedLiveGraph, rulesConfig, overlays, debugMode = false, cloudApiUrl, onStage, remoteMode = false, diffOptions) {
697
+ const reportStage = async (idx) => {
698
+ if (!onStage)
699
+ return;
700
+ await onStage(LAYOUT_BUILD_STAGES[idx]);
701
+ await yieldEventLoop();
702
+ };
703
+ await reportStage(0);
704
+ const overlayLayers = rulesConfig?.overlayLayers;
705
+ let targetGraph = applyActivePluginProjections(graph, {
706
+ repoPath,
707
+ overlays: overlays ?? [],
708
+ overlayLayers,
709
+ });
710
+ let diffDelta;
711
+ let resolvedLiveGraph = diffOptions?.targetGraph ?? cachedLiveGraph;
712
+ if (diffMode && repoPath && existsSync(repoPath)) {
713
+ const baseRawGraph = diffOptions?.baseGraph ?? graph;
714
+ const baseSha = diffOptions?.baseFullCommitSha ??
715
+ diffOptions?.baseCommitSha ??
716
+ baseRawGraph.commitSha;
717
+ if (!resolvedLiveGraph) {
718
+ resolvedLiveGraph = extractFilteredLiveUserGraph(repoPath);
719
+ }
720
+ const isWorkingTree = diffOptions?.isWorkingTreeSnapshot ?? !diffOptions?.targetFullCommitSha;
721
+ const targetSha = diffOptions?.targetFullCommitSha ?? diffOptions?.targetCommitSha;
722
+ const scopedDiffPaths = resolveScopedDiffPaths(repoPath, baseSha, targetSha, isWorkingTree);
723
+ const baseForDiff = hasGitCommitForDiff(repoPath, baseSha)
724
+ ? applyActivePluginProjections(baseRawGraph, {
725
+ repoPath,
726
+ overlayLayers,
727
+ readRepoFileOverride: (rel) => readGitBlobForDiff(repoPath, baseSha.trim(), rel, scopedDiffPaths),
728
+ })
729
+ : baseRawGraph;
730
+ const projectedLiveGraph = !isWorkingTree && hasGitCommitForDiff(repoPath, targetSha)
731
+ ? applyActivePluginProjections(resolvedLiveGraph, {
732
+ repoPath,
733
+ overlayLayers,
734
+ readRepoFileOverride: (rel) => readGitBlobForDiff(repoPath, targetSha.trim(), rel, scopedDiffPaths),
735
+ })
736
+ : applyActivePluginProjections(resolvedLiveGraph, {
737
+ repoPath,
738
+ overlayLayers,
739
+ });
740
+ diffDelta = compareGraphs(baseForDiff, projectedLiveGraph);
741
+ const removedNodes = Object.values(diffDelta.nodes)
742
+ .filter((entry) => entry.status === "REMOVED" && entry.base)
743
+ .map((entry) => entry.base);
744
+ const removedEdges = Object.values(diffDelta.edges)
745
+ .filter((entry) => entry.status === "REMOVED" && entry.base)
746
+ .map((entry) => entry.base);
747
+ targetGraph = {
748
+ ...projectedLiveGraph,
749
+ nodes: [...projectedLiveGraph.nodes, ...removedNodes],
750
+ edges: [...projectedLiveGraph.edges, ...removedEdges],
751
+ };
752
+ }
753
+ const enrichDiffSummaryMeta = (summary) => {
754
+ if (!summary)
755
+ return undefined;
756
+ return {
757
+ ...summary,
758
+ ...(diffOptions?.baseCommitSha ? { baseCommitSha: diffOptions.baseCommitSha } : {}),
759
+ ...(diffOptions?.baseRef ? { baseRef: diffOptions.baseRef } : {}),
760
+ ...(diffOptions?.baseCommitMessage ? { baseCommitMessage: diffOptions.baseCommitMessage } : {}),
761
+ ...(diffOptions?.targetCommitSha ? { targetCommitSha: diffOptions.targetCommitSha } : {}),
762
+ ...(diffOptions?.targetRef ? { targetRef: diffOptions.targetRef } : {}),
763
+ ...(diffOptions?.targetCommitMessage
764
+ ? { targetCommitMessage: diffOptions.targetCommitMessage }
765
+ : {}),
766
+ ...(diffOptions?.isWorkingTreeSnapshot !== undefined
767
+ ? { isWorkingTreeSnapshot: diffOptions.isWorkingTreeSnapshot }
768
+ : {}),
769
+ ...(diffOptions?.snapshotAt ? { snapshotAt: diffOptions.snapshotAt } : {}),
770
+ };
771
+ };
772
+ // Strip raw source code snippets from evidence so only filePath:lineNumber is exposed
773
+ targetGraph = stripEvidenceSnippetsFromGraph(targetGraph);
774
+ const hasLocalMaster = hasLocalMasterLayoutEngine();
775
+ const explicitCloudUrl = (cloudApiUrl ??
776
+ process.env.CHOMP_LAYOUT_API_URL ??
777
+ "").trim();
778
+ const shouldUseRemoteCloud = remoteMode || Boolean(explicitCloudUrl) || !hasLocalMaster;
779
+ if (shouldUseRemoteCloud) {
780
+ const targetCloudUrl = explicitCloudUrl || DEFAULT_CLOUD_API_URL;
781
+ try {
782
+ await reportStage(1);
783
+ await reportStage(2);
784
+ await reportStage(3);
785
+ const cloudLayout = await requestStatelessCloudLayout(targetGraph, repoName, diffDelta, rulesConfig, overlays, {
786
+ cloudApiUrl: targetCloudUrl,
787
+ remote: true,
788
+ });
789
+ if (cloudLayout.diffSummary) {
790
+ cloudLayout.diffSummary = enrichDiffSummaryMeta(cloudLayout.diffSummary);
791
+ }
792
+ await reportStage(4);
793
+ return { layout: cloudLayout, liveGraph: resolvedLiveGraph };
794
+ }
795
+ catch (cloudErr) {
796
+ if (!hasLocalMaster || remoteMode) {
797
+ throw cloudErr;
798
+ }
799
+ console.warn(` ${ansi.yellowBold("⚠")} Cloud layout worker (${targetCloudUrl}) unreachable (${cloudErr?.cause?.code || cloudErr?.message || "fetch error"}) — falling back to local master layout pipeline.`);
800
+ }
801
+ }
802
+ const { runStoryTracer, runZipMerge, runGridMapper, writeMatrixCsv, writeLayoutCsv, } = await loadLocalMasterLayoutEngine();
803
+ // Stage 1 — Story Tracer: entity-level DFS over the v4 graph → Story[]
804
+ await reportStage(1);
805
+ const storyGraph = runStoryTracer(targetGraph, diffDelta, rulesConfig, overlays);
806
+ const verbosePipelineLogs = debugMode || process.env.CHOMP_DEBUG_LAYOUT === "1";
807
+ if (verbosePipelineLogs) {
808
+ console.log(` 📖 Stories: ${storyGraph.stories.length} | ` +
809
+ `Raw nodes: ${storyGraph.totalRawNodeCount} | ` +
810
+ `Orphans: ${storyGraph.orphanNodes.length}`);
811
+ }
812
+ // Stage 2 — Zip Merge: badge utilities, merge shared terminals
813
+ await reportStage(2);
814
+ const mergedGraph = runZipMerge(storyGraph);
815
+ if (verbosePipelineLogs) {
816
+ console.log(` 🔗 Anchors: ${mergedGraph.anchorCount} | ` +
817
+ `Badged: ${mergedGraph.badgedCount} | ` +
818
+ `Stories after merge: ${mergedGraph.stories.length}`);
819
+ }
820
+ if (debugMode) {
821
+ writeMatrixCsv(mergedGraph);
822
+ }
823
+ // Stage 3 — Grid Mapper: assign x/y coordinates
824
+ await reportStage(3);
825
+ const layoutData = runGridMapper(mergedGraph, rulesConfig);
826
+ layoutData.repoName = repoName;
827
+ layoutData.entitlement = {
828
+ tier: "master",
829
+ status: "active",
830
+ previewMode: false,
831
+ gatingMode: "early_access",
832
+ };
833
+ if (overlays) {
834
+ layoutData.overlays = overlays;
835
+ }
836
+ layoutData.islandNodes = storyGraph.orphanNodes.map((o, idx) => ({
837
+ ...o,
838
+ role: "ISLAND",
839
+ x: 0,
840
+ y: idx * 36,
841
+ width: 240,
842
+ height: 32,
843
+ }));
844
+ await reportStage(4);
845
+ const { systemHealth, packageHealthByPkg } = computeGraphHealthMetrics(targetGraph, repoName, storyGraph.orphanNodes, layoutData, overlays);
846
+ layoutData.healthSummary = systemHealth;
847
+ if (layoutData.packageBounds) {
848
+ for (const [pkg, bounds] of Object.entries(layoutData.packageBounds)) {
849
+ if (packageHealthByPkg[pkg]) {
850
+ bounds.health = packageHealthByPkg[pkg];
851
+ }
852
+ }
853
+ }
854
+ if (diffDelta) {
855
+ const renderedNodes = layoutData.nodes.filter((n) => !n.isPackage);
856
+ layoutData.diffSummary = enrichDiffSummaryMeta({
857
+ baseCommitSha: diffDelta.baseCommitSha,
858
+ addedNodes: renderedNodes.filter((n) => n.diffStatus === "ADDED").length,
859
+ modifiedNodes: renderedNodes.filter((n) => n.diffStatus === "MODIFIED").length,
860
+ removedNodes: renderedNodes.filter((n) => n.diffStatus === "REMOVED").length,
861
+ addedEdges: layoutData.edges.filter((e) => e.diffStatus === "ADDED").length,
862
+ modifiedEdges: layoutData.edges.filter((e) => e.diffStatus === "MODIFIED").length,
863
+ removedEdges: layoutData.edges.filter((e) => e.diffStatus === "REMOVED").length,
864
+ });
865
+ }
866
+ if (debugMode) {
867
+ writeLayoutCsv(layoutData);
868
+ }
869
+ delete layoutData.cliStories;
870
+ // Stage 4 — Visual Rules Ledger validation
871
+ const lintIssues = validateLayoutPayload(layoutData);
872
+ const fatalErrors = lintIssues.filter((msg) => !msg.includes("[PAT-VIS-07]"));
873
+ const warnings = lintIssues.filter((msg) => msg.includes("[PAT-VIS-07]"));
874
+ if (warnings.length > 0 && verbosePipelineLogs) {
875
+ console.warn(" ⚠️ Visual Linter Warnings:", warnings);
876
+ }
877
+ if (fatalErrors.length > 0) {
878
+ console.error("Visual Linter Failed:", fatalErrors);
879
+ throw Object.assign(new Error("Layout generation failed rules ledger"), {
880
+ lintErrors: fatalErrors,
881
+ });
882
+ }
883
+ return { layout: layoutData, liveGraph: resolvedLiveGraph };
884
+ }
885
+ /**
886
+ * Speed 2 Background Port Valve Verification (`[PAT-VIS-14]`, `[PAT-DB-03]`).
887
+ * Runs in an isolated forked child process so TypeScript compilation never blocks the UI event loop.
888
+ */
889
+ export function scheduleBackgroundPortHydration(state, force = false) {
890
+ if (state.portHydrationInFlight) {
891
+ state.portHydrationQueued = true;
892
+ state.portHydrationForceQueued = state.portHydrationForceQueued || force;
893
+ return state.portHydrationInFlight;
894
+ }
895
+ const { target: activeTarget, dbPath: activeDbPath } = getActiveUiTarget(state);
896
+ if (!existsSync(activeDbPath)) {
897
+ return Promise.resolve(null);
898
+ }
899
+ const handle = runPortHydrationInChildProcess({
900
+ dbPath: activeDbPath,
901
+ repoPath: activeTarget,
902
+ force,
903
+ });
904
+ state.activePortHydrationHandle = handle;
905
+ state.portHydrationInFlight = handle.promise.then(async (result) => {
906
+ if (state.activePortHydrationHandle === handle) {
907
+ state.activePortHydrationHandle = null;
908
+ }
909
+ if (result && (result.hydratedCount > 0 || result.prunedCount > 0)) {
910
+ invalidateAllServerCaches(state);
911
+ }
912
+ state.portHydrationInFlight = null;
913
+ if (state.portHydrationQueued) {
914
+ const nextForce = state.portHydrationForceQueued;
915
+ state.portHydrationQueued = false;
916
+ state.portHydrationForceQueued = false;
917
+ return scheduleBackgroundPortHydration(state, nextForce);
918
+ }
919
+ return result;
920
+ });
921
+ return state.portHydrationInFlight;
922
+ }
923
+ export function triggerInitialPortHydrationAfterLayout(state) {
924
+ if (state.initialPortHydrationTriggered)
925
+ return;
926
+ state.initialPortHydrationTriggered = true;
927
+ setTimeout(() => {
928
+ void scheduleBackgroundPortHydration(state, false);
929
+ }, 350);
930
+ }