@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.
- package/LICENSE +21 -0
- package/README.md +39 -2
- package/dist/commands/analyze.d.ts +49 -0
- package/dist/commands/analyze.js +280 -0
- package/dist/commands/connect.d.ts +12 -0
- package/dist/commands/connect.js +255 -0
- package/dist/commands/export.d.ts +29 -0
- package/dist/commands/export.js +356 -0
- package/dist/commands/health.d.ts +19 -0
- package/dist/commands/health.js +259 -0
- package/dist/commands/init.d.ts +40 -0
- package/dist/commands/init.js +659 -0
- package/dist/commands/mcp.d.ts +2 -0
- package/dist/commands/mcp.js +12 -0
- package/dist/commands/plugin.d.ts +8 -0
- package/dist/commands/plugin.js +198 -0
- package/dist/commands/ui.d.ts +20 -0
- package/dist/commands/ui.js +252 -0
- package/dist/commands/uninstall.d.ts +8 -0
- package/dist/commands/uninstall.js +246 -0
- package/dist/index.d.ts +3 -0
- package/dist/index.js +37 -0
- package/dist/ports/portHydrator.d.ts +63 -0
- package/dist/ports/portHydrator.js +954 -0
- package/dist/ports/portHydratorWorker.d.ts +22 -0
- package/dist/ports/portHydratorWorker.js +75 -0
- package/dist/server/buildStatusTracker.d.ts +45 -0
- package/dist/server/buildStatusTracker.js +122 -0
- package/dist/server/graphLayoutState.d.ts +205 -0
- package/dist/server/graphLayoutState.js +930 -0
- package/dist/server/loopbackSecurity.d.ts +18 -0
- package/dist/server/loopbackSecurity.js +57 -0
- package/dist/server/routes/authSourceRoutes.d.ts +18 -0
- package/dist/server/routes/authSourceRoutes.js +231 -0
- package/dist/server/routes/layoutRoutes.d.ts +3 -0
- package/dist/server/routes/layoutRoutes.js +857 -0
- package/dist/server/routes/pluginRoutes.d.ts +3 -0
- package/dist/server/routes/pluginRoutes.js +368 -0
- package/dist/server/routes/viewRulesRoutes.d.ts +3 -0
- package/dist/server/routes/viewRulesRoutes.js +173 -0
- package/dist/server/uiHotkeys.d.ts +26 -0
- package/dist/server/uiHotkeys.js +160 -0
- package/dist/utils/branding.d.ts +126 -0
- package/dist/utils/branding.js +978 -0
- package/dist/utils/credentials.d.ts +22 -0
- package/dist/utils/credentials.js +126 -0
- package/dist/utils/git.d.ts +95 -0
- package/dist/utils/git.js +780 -0
- package/dist/utils/masterContext.d.ts +112 -0
- package/dist/utils/masterContext.js +642 -0
- package/dist/visualizer/cloudLayoutClient.d.ts +84 -0
- package/dist/visualizer/cloudLayoutClient.js +1200 -0
- package/dist/visualizer/layoutCache.d.ts +25 -0
- package/dist/visualizer/layoutCache.js +406 -0
- package/dist/visualizer/localEngineBridge.d.ts +50 -0
- package/dist/visualizer/localEngineBridge.js +80 -0
- package/dist/visualizer/pluginPresentationApi.d.ts +111 -0
- package/dist/visualizer/pluginPresentationApi.js +432 -0
- package/dist/visualizer/rulesConfig.d.ts +11 -0
- package/dist/visualizer/rulesConfig.js +266 -0
- package/dist/visualizer/sourceAccess.d.ts +45 -0
- package/dist/visualizer/sourceAccess.js +204 -0
- package/package.json +52 -3
|
@@ -0,0 +1,857 @@
|
|
|
1
|
+
import { existsSync, readFileSync, writeFileSync } from "node:fs";
|
|
2
|
+
import { basename, dirname, join } from "node:path";
|
|
3
|
+
import { CORE_EXTRACTOR_VERSION, compareGraphs, } from "@getchomp/core";
|
|
4
|
+
import { createSQLiteStorage } from "@getchomp/db";
|
|
5
|
+
import { applyActivePluginProjections } from "@getchomp/mcp";
|
|
6
|
+
import { ansi } from "../../utils/branding.js";
|
|
7
|
+
import { getGitInfoAsync, listGitBranchesAndWorktrees, resolveGitRefInfo, resolveRepoName, } from "../../utils/git.js";
|
|
8
|
+
import { stripEvidenceSnippetsFromGraph } from "../../visualizer/cloudLayoutClient.js";
|
|
9
|
+
import { clearDiskLayoutCache, computeWorkingTreeFingerprintAsync, readDiskDiffLayoutCache, readDiskLayoutCache, writeDiskDiffLayoutCache, writeDiskLayoutCache, } from "../../visualizer/layoutCache.js";
|
|
10
|
+
import { computePluginFingerprint } from "../../visualizer/pluginPresentationApi.js";
|
|
11
|
+
import { getRulesFingerprint, loadRulesConfig, } from "../../visualizer/rulesConfig.js";
|
|
12
|
+
import { buildLayout, getActiveUiTarget, getAuthModeFingerprint, getCurrentDbMtime, getLocalShimsFileFp, getPluginRegistryMeta, hasGitCommitForDiff, hydratePluginRunsForRepo, invalidateAllServerCaches, loadBaseGraphCached, readGitBlobForDiff, resolveCommittedRefGraph, resolveScopedDiffPaths, resolveWorkingTreeSnapshotGraph, scheduleBackgroundPortHydration, triggerInitialPortHydrationAfterLayout, } from "../graphLayoutState.js";
|
|
13
|
+
import { buildAuthStatusPayload } from "./authSourceRoutes.js";
|
|
14
|
+
export function registerLayoutRoutes(app, state) {
|
|
15
|
+
// GET /api/status — JSON snapshot or Server-Sent Events stream
|
|
16
|
+
app.get("/api/status", (req, res) => {
|
|
17
|
+
const { repoName: activeRepoName } = getActiveUiTarget(state);
|
|
18
|
+
const current = state.statusTracker.getSnapshot();
|
|
19
|
+
const enriched = current.state === "idle" && current.repoName !== activeRepoName
|
|
20
|
+
? { ...current, repoName: activeRepoName }
|
|
21
|
+
: current;
|
|
22
|
+
const wantsStream = req.query.stream === "true" ||
|
|
23
|
+
(typeof req.headers.accept === "string" &&
|
|
24
|
+
req.headers.accept.includes("text/event-stream"));
|
|
25
|
+
if (!wantsStream) {
|
|
26
|
+
return res.json(enriched);
|
|
27
|
+
}
|
|
28
|
+
res.setHeader("Content-Type", "text/event-stream");
|
|
29
|
+
res.setHeader("Cache-Control", "no-cache, no-transform");
|
|
30
|
+
res.setHeader("Connection", "keep-alive");
|
|
31
|
+
res.flushHeaders?.();
|
|
32
|
+
res.write(`data: ${JSON.stringify(enriched)}\n\n`);
|
|
33
|
+
const unsubscribe = state.statusTracker.subscribe((nextSnap) => {
|
|
34
|
+
try {
|
|
35
|
+
res.write(`data: ${JSON.stringify(nextSnap)}\n\n`);
|
|
36
|
+
}
|
|
37
|
+
catch {
|
|
38
|
+
// Client disconnected
|
|
39
|
+
}
|
|
40
|
+
});
|
|
41
|
+
const keepAlive = setInterval(() => {
|
|
42
|
+
try {
|
|
43
|
+
res.write(": ping\n\n");
|
|
44
|
+
}
|
|
45
|
+
catch {
|
|
46
|
+
// Ignore write error on closed socket
|
|
47
|
+
}
|
|
48
|
+
}, 15000);
|
|
49
|
+
req.on("close", () => {
|
|
50
|
+
clearInterval(keepAlive);
|
|
51
|
+
unsubscribe();
|
|
52
|
+
});
|
|
53
|
+
});
|
|
54
|
+
// GET /api/layout/fingerprint — decoupled structural vs plugin revalidation ([PAT-VIS-36])
|
|
55
|
+
app.get("/api/layout/fingerprint", async (_req, res) => {
|
|
56
|
+
try {
|
|
57
|
+
const { target: activeTarget, dbPath: activeDbPath } = getActiveUiTarget(state);
|
|
58
|
+
const baseData = await loadBaseGraphCached(state);
|
|
59
|
+
const dbMtime = baseData?.mtime ?? getCurrentDbMtime(activeDbPath);
|
|
60
|
+
const repoPath = baseData?.repo?.path || activeTarget;
|
|
61
|
+
const shimsFp = getLocalShimsFileFp(repoPath);
|
|
62
|
+
const rulesFp = `${activeDbPath}:${getRulesFingerprint(activeDbPath)}:${shimsFp}:${getAuthModeFingerprint(state)}`;
|
|
63
|
+
const wtFingerprint = await computeWorkingTreeFingerprintAsync(repoPath);
|
|
64
|
+
return res.json({
|
|
65
|
+
dbMtime,
|
|
66
|
+
rulesFp,
|
|
67
|
+
wtFingerprint,
|
|
68
|
+
portsHydrating: Boolean(state.portHydrationInFlight || state.portHydrationQueued),
|
|
69
|
+
structureFp: baseData?.structureFp ?? "",
|
|
70
|
+
pluginFp: computePluginFingerprint(baseData?.pluginOverlays ?? [], hydratePluginRunsForRepo(state, repoPath), getPluginRegistryMeta(repoPath)),
|
|
71
|
+
});
|
|
72
|
+
}
|
|
73
|
+
catch (error) {
|
|
74
|
+
return res.status(500).json({
|
|
75
|
+
error: error?.message || "Failed to compute fingerprint",
|
|
76
|
+
});
|
|
77
|
+
}
|
|
78
|
+
});
|
|
79
|
+
// GET /api/git/branches — discover local branches, worktrees & dirty state
|
|
80
|
+
app.get("/api/git/branches", async (_req, res) => {
|
|
81
|
+
try {
|
|
82
|
+
const { target: activeTarget } = getActiveUiTarget(state);
|
|
83
|
+
const baseData = await loadBaseGraphCached(state);
|
|
84
|
+
const repoPath = baseData?.repo?.path || activeTarget;
|
|
85
|
+
const targets = await listGitBranchesAndWorktrees(repoPath);
|
|
86
|
+
return res.json(targets);
|
|
87
|
+
}
|
|
88
|
+
catch (error) {
|
|
89
|
+
return res.status(500).json({
|
|
90
|
+
error: error?.message || "Failed to list git branches",
|
|
91
|
+
});
|
|
92
|
+
}
|
|
93
|
+
});
|
|
94
|
+
// POST /api/diff/refresh — manually refresh point-in-time working-tree snapshot
|
|
95
|
+
app.post("/api/diff/refresh", (_req, res) => {
|
|
96
|
+
state.workingTreeSnapshotCache = null;
|
|
97
|
+
for (const key of Array.from(state.layoutCache.keys())) {
|
|
98
|
+
if (key.includes(":diff")) {
|
|
99
|
+
state.layoutCache.delete(key);
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
return res.json({ ok: true, refreshedAt: new Date().toISOString() });
|
|
103
|
+
});
|
|
104
|
+
// GET /api/layout — primary Topological Unrolling layout endpoint
|
|
105
|
+
app.get("/api/layout", async (req, res) => {
|
|
106
|
+
try {
|
|
107
|
+
const { target: activeTarget, repoName: activeRepoName, dbPath: activeDbPath, } = getActiveUiTarget(state);
|
|
108
|
+
const diffMode = req.query.diff === "true" || req.query.diff === "1";
|
|
109
|
+
const forceRefresh = req.query.refresh === "true" || req.query.refresh === "1";
|
|
110
|
+
const rawBaseParam = typeof req.query.base === "string" && req.query.base.trim()
|
|
111
|
+
? req.query.base.trim()
|
|
112
|
+
: undefined;
|
|
113
|
+
const rawTargetParamRaw = typeof req.query.target === "string" && req.query.target.trim()
|
|
114
|
+
? req.query.target.trim()
|
|
115
|
+
: undefined;
|
|
116
|
+
const rawTargetParam = rawTargetParamRaw &&
|
|
117
|
+
rawTargetParamRaw.toUpperCase() === "WORKING_TREE"
|
|
118
|
+
? "WORKING_TREE"
|
|
119
|
+
: rawTargetParamRaw?.toLowerCase() === "working-tree"
|
|
120
|
+
? "WORKING_TREE"
|
|
121
|
+
: rawTargetParamRaw;
|
|
122
|
+
if (forceRefresh && (!diffMode || rawTargetParam !== "WORKING_TREE")) {
|
|
123
|
+
clearDiskLayoutCache(activeDbPath);
|
|
124
|
+
invalidateAllServerCaches(state);
|
|
125
|
+
}
|
|
126
|
+
else if (forceRefresh && diffMode && rawTargetParam === "WORKING_TREE") {
|
|
127
|
+
state.workingTreeSnapshotCache = null;
|
|
128
|
+
for (const key of Array.from(state.layoutCache.keys())) {
|
|
129
|
+
if (key.includes(":diff"))
|
|
130
|
+
state.layoutCache.delete(key);
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
const baseData = await loadBaseGraphCached(state);
|
|
134
|
+
if (!baseData) {
|
|
135
|
+
return res.status(404).json({
|
|
136
|
+
error: "No repositories or graph found in database.",
|
|
137
|
+
code: "NO_GRAPH",
|
|
138
|
+
});
|
|
139
|
+
}
|
|
140
|
+
const { mtime: dbMtime, repo, graph, structuralOverlays: overlays, structureFp, } = baseData;
|
|
141
|
+
const repoPath = repo.path || activeTarget;
|
|
142
|
+
const liveGit = await getGitInfoAsync(repoPath);
|
|
143
|
+
const activeBranchName = liveGit.branchName || repo.branchName || graph.branchName;
|
|
144
|
+
const activeCommitSha = liveGit.commitSha || repo.commitSha || graph.commitSha;
|
|
145
|
+
const activeCommitMessage = liveGit.commitMessage;
|
|
146
|
+
const resolvedRemoteUrl = liveGit.remoteUrl;
|
|
147
|
+
const resolvedUpdatedAt = dbMtime || Date.now();
|
|
148
|
+
const shimsFp = getLocalShimsFileFp(repoPath);
|
|
149
|
+
const rulesFp = `${getRulesFingerprint(activeDbPath)}:${shimsFp}`;
|
|
150
|
+
const authModeFp = getAuthModeFingerprint(state);
|
|
151
|
+
let resolvedBranchName = activeBranchName;
|
|
152
|
+
let resolvedCommitSha = activeCommitSha;
|
|
153
|
+
let resolvedCommitMessage = activeCommitMessage;
|
|
154
|
+
let effectiveGraphForLayout = graph;
|
|
155
|
+
let diffOptions;
|
|
156
|
+
let isCustomBranchView = false;
|
|
157
|
+
let cacheKey;
|
|
158
|
+
let diskCacheSeed = `${structureFp}:${rulesFp}:${authModeFp}`;
|
|
159
|
+
let committedDiffBaseSha;
|
|
160
|
+
let committedDiffTargetSha;
|
|
161
|
+
let hydrateRefGraphsForBuild;
|
|
162
|
+
if (diffMode && repoPath && existsSync(repoPath)) {
|
|
163
|
+
const gitTargets = await listGitBranchesAndWorktrees(repoPath);
|
|
164
|
+
const inMemoryBase = {
|
|
165
|
+
activeDbPath,
|
|
166
|
+
baseData,
|
|
167
|
+
activeCommitSha,
|
|
168
|
+
workingTreeDirty: gitTargets.workingTreeDirty,
|
|
169
|
+
};
|
|
170
|
+
const currentBranch = activeBranchName || gitTargets.currentBranch || "HEAD";
|
|
171
|
+
const defaultBase = gitTargets.defaultBaseBranch || currentBranch;
|
|
172
|
+
const hasDefaultBaseBranch = gitTargets.branches.some((b) => b.name === defaultBase);
|
|
173
|
+
const effectiveBaseRef = rawBaseParam ??
|
|
174
|
+
(rawTargetParam === "WORKING_TREE"
|
|
175
|
+
? currentBranch
|
|
176
|
+
: currentBranch !== defaultBase && hasDefaultBaseBranch
|
|
177
|
+
? defaultBase
|
|
178
|
+
: currentBranch);
|
|
179
|
+
const effectiveTargetRef = rawTargetParam ??
|
|
180
|
+
(currentBranch && currentBranch !== effectiveBaseRef
|
|
181
|
+
? currentBranch
|
|
182
|
+
: "WORKING_TREE");
|
|
183
|
+
const baseRefInfo = await resolveGitRefInfo(repoPath, effectiveBaseRef, gitTargets);
|
|
184
|
+
if (baseRefInfo) {
|
|
185
|
+
resolvedBranchName = effectiveBaseRef;
|
|
186
|
+
resolvedCommitSha = baseRefInfo.fullCommitSha;
|
|
187
|
+
resolvedCommitMessage =
|
|
188
|
+
baseRefInfo.commitMessage ?? activeCommitMessage;
|
|
189
|
+
}
|
|
190
|
+
if (effectiveTargetRef !== "WORKING_TREE") {
|
|
191
|
+
const targetRefInfo = await resolveGitRefInfo(repoPath, effectiveTargetRef, gitTargets);
|
|
192
|
+
if (!targetRefInfo) {
|
|
193
|
+
throw new Error(`Unable to resolve git ref '${effectiveTargetRef}' in ${repoPath}`);
|
|
194
|
+
}
|
|
195
|
+
const baseShaFull = baseRefInfo?.fullCommitSha ?? activeCommitSha ?? "base";
|
|
196
|
+
const targetShaFull = targetRefInfo.fullCommitSha;
|
|
197
|
+
committedDiffBaseSha = baseShaFull;
|
|
198
|
+
committedDiffTargetSha = targetShaFull;
|
|
199
|
+
cacheKey = `${activeDbPath}:${rulesFp}:${authModeFp}:diff-ref:${baseShaFull}:${targetShaFull}:${effectiveBaseRef}:${effectiveTargetRef}`;
|
|
200
|
+
diffOptions = {
|
|
201
|
+
baseCommitSha: baseRefInfo?.commitSha ?? activeCommitSha?.slice(0, 7),
|
|
202
|
+
baseFullCommitSha: baseRefInfo?.fullCommitSha ?? activeCommitSha,
|
|
203
|
+
baseRef: effectiveBaseRef,
|
|
204
|
+
baseCommitMessage: baseRefInfo?.commitMessage ?? activeCommitMessage,
|
|
205
|
+
targetCommitSha: targetRefInfo.commitSha,
|
|
206
|
+
targetFullCommitSha: targetRefInfo.fullCommitSha,
|
|
207
|
+
targetRef: effectiveTargetRef,
|
|
208
|
+
targetCommitMessage: targetRefInfo.commitMessage,
|
|
209
|
+
isWorkingTreeSnapshot: false,
|
|
210
|
+
};
|
|
211
|
+
hydrateRefGraphsForBuild = async () => {
|
|
212
|
+
const [baseResolved, targetResolved] = await Promise.all([
|
|
213
|
+
resolveCommittedRefGraph(repoPath, effectiveBaseRef, {
|
|
214
|
+
dbPath: activeDbPath,
|
|
215
|
+
forceRefresh,
|
|
216
|
+
resolvedRef: baseRefInfo,
|
|
217
|
+
inMemoryBase,
|
|
218
|
+
}).catch(() => null),
|
|
219
|
+
resolveCommittedRefGraph(repoPath, effectiveTargetRef, {
|
|
220
|
+
dbPath: activeDbPath,
|
|
221
|
+
forceRefresh,
|
|
222
|
+
resolvedRef: targetRefInfo,
|
|
223
|
+
inMemoryBase,
|
|
224
|
+
}),
|
|
225
|
+
]);
|
|
226
|
+
if (baseResolved?.commitMessage) {
|
|
227
|
+
resolvedCommitMessage = baseResolved.commitMessage;
|
|
228
|
+
}
|
|
229
|
+
diffOptions = {
|
|
230
|
+
...diffOptions,
|
|
231
|
+
baseGraph: baseResolved?.graph ?? graph,
|
|
232
|
+
...(baseResolved?.commitMessage
|
|
233
|
+
? { baseCommitMessage: baseResolved.commitMessage }
|
|
234
|
+
: {}),
|
|
235
|
+
targetGraph: targetResolved.graph,
|
|
236
|
+
...(targetResolved.commitMessage
|
|
237
|
+
? { targetCommitMessage: targetResolved.commitMessage }
|
|
238
|
+
: {}),
|
|
239
|
+
};
|
|
240
|
+
};
|
|
241
|
+
}
|
|
242
|
+
else {
|
|
243
|
+
const wtFingerprint = await computeWorkingTreeFingerprintAsync(repoPath);
|
|
244
|
+
const snap = resolveWorkingTreeSnapshotGraph(state, repoPath, wtFingerprint, forceRefresh);
|
|
245
|
+
const baseShaFull = baseRefInfo?.fullCommitSha ?? activeCommitSha ?? String(dbMtime);
|
|
246
|
+
cacheKey = `${activeDbPath}:${rulesFp}:${authModeFp}:diff-wt:${baseShaFull}:${snap.snapshotAt}:${effectiveBaseRef}`;
|
|
247
|
+
diffOptions = {
|
|
248
|
+
baseCommitSha: baseRefInfo?.commitSha ?? activeCommitSha?.slice(0, 7),
|
|
249
|
+
baseFullCommitSha: baseRefInfo?.fullCommitSha ?? activeCommitSha,
|
|
250
|
+
baseRef: effectiveBaseRef,
|
|
251
|
+
baseCommitMessage: baseRefInfo?.commitMessage ?? activeCommitMessage,
|
|
252
|
+
targetGraph: snap.liveGraph,
|
|
253
|
+
targetRef: "WORKING_TREE",
|
|
254
|
+
isWorkingTreeSnapshot: true,
|
|
255
|
+
snapshotAt: snap.snapshotAt,
|
|
256
|
+
};
|
|
257
|
+
hydrateRefGraphsForBuild = async () => {
|
|
258
|
+
const baseResolved = await resolveCommittedRefGraph(repoPath, effectiveBaseRef, {
|
|
259
|
+
dbPath: activeDbPath,
|
|
260
|
+
forceRefresh,
|
|
261
|
+
resolvedRef: baseRefInfo,
|
|
262
|
+
inMemoryBase,
|
|
263
|
+
}).catch(() => null);
|
|
264
|
+
if (baseResolved?.commitMessage) {
|
|
265
|
+
resolvedCommitMessage = baseResolved.commitMessage;
|
|
266
|
+
}
|
|
267
|
+
diffOptions = {
|
|
268
|
+
...diffOptions,
|
|
269
|
+
baseGraph: baseResolved?.graph ?? graph,
|
|
270
|
+
...(baseResolved?.commitMessage
|
|
271
|
+
? { baseCommitMessage: baseResolved.commitMessage }
|
|
272
|
+
: {}),
|
|
273
|
+
};
|
|
274
|
+
};
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
else if (!diffMode &&
|
|
278
|
+
rawBaseParam &&
|
|
279
|
+
repoPath &&
|
|
280
|
+
existsSync(repoPath) &&
|
|
281
|
+
rawBaseParam !== activeBranchName) {
|
|
282
|
+
const switchedRefInfo = await resolveGitRefInfo(repoPath, rawBaseParam);
|
|
283
|
+
if (switchedRefInfo) {
|
|
284
|
+
resolvedBranchName = rawBaseParam;
|
|
285
|
+
resolvedCommitSha = switchedRefInfo.fullCommitSha;
|
|
286
|
+
resolvedCommitMessage = switchedRefInfo.commitMessage;
|
|
287
|
+
isCustomBranchView = true;
|
|
288
|
+
diskCacheSeed = `branch:${switchedRefInfo.fullCommitSha}:${CORE_EXTRACTOR_VERSION}:${rulesFp}:${authModeFp}`;
|
|
289
|
+
cacheKey = `${activeDbPath}:${rulesFp}:${authModeFp}:branch:${switchedRefInfo.fullCommitSha}:${rawBaseParam}`;
|
|
290
|
+
hydrateRefGraphsForBuild = async () => {
|
|
291
|
+
const switched = await resolveCommittedRefGraph(repoPath, rawBaseParam, {
|
|
292
|
+
dbPath: activeDbPath,
|
|
293
|
+
forceRefresh,
|
|
294
|
+
resolvedRef: switchedRefInfo,
|
|
295
|
+
inMemoryBase: { activeDbPath, baseData, activeCommitSha },
|
|
296
|
+
});
|
|
297
|
+
effectiveGraphForLayout = switched.graph;
|
|
298
|
+
if (switched.commitMessage) {
|
|
299
|
+
resolvedCommitMessage = switched.commitMessage;
|
|
300
|
+
}
|
|
301
|
+
};
|
|
302
|
+
}
|
|
303
|
+
else {
|
|
304
|
+
cacheKey = `${activeDbPath}:${dbMtime}:${rulesFp}:${authModeFp}:normal`;
|
|
305
|
+
}
|
|
306
|
+
}
|
|
307
|
+
else {
|
|
308
|
+
cacheKey = diffMode
|
|
309
|
+
? `${activeDbPath}:${dbMtime}:${rulesFp}:${authModeFp}:diff:fallback`
|
|
310
|
+
: `${activeDbPath}:${dbMtime}:${rulesFp}:${authModeFp}:normal`;
|
|
311
|
+
}
|
|
312
|
+
const stampLiveGitMetadata = (targetLayout) => {
|
|
313
|
+
if (!diffMode &&
|
|
314
|
+
!isCustomBranchView &&
|
|
315
|
+
!targetLayout.diffSummary &&
|
|
316
|
+
state.latestDiffSummary) {
|
|
317
|
+
targetLayout.diffSummary = state.latestDiffSummary.summary;
|
|
318
|
+
}
|
|
319
|
+
if (diffMode && targetLayout.diffSummary && diffOptions) {
|
|
320
|
+
targetLayout.diffSummary = {
|
|
321
|
+
...targetLayout.diffSummary,
|
|
322
|
+
...(diffOptions.baseCommitSha
|
|
323
|
+
? { baseCommitSha: diffOptions.baseCommitSha }
|
|
324
|
+
: {}),
|
|
325
|
+
...(diffOptions.baseRef ? { baseRef: diffOptions.baseRef } : {}),
|
|
326
|
+
...(diffOptions.baseCommitMessage
|
|
327
|
+
? { baseCommitMessage: diffOptions.baseCommitMessage }
|
|
328
|
+
: {}),
|
|
329
|
+
...(diffOptions.targetCommitSha
|
|
330
|
+
? { targetCommitSha: diffOptions.targetCommitSha }
|
|
331
|
+
: {}),
|
|
332
|
+
...(diffOptions.targetRef ? { targetRef: diffOptions.targetRef } : {}),
|
|
333
|
+
...(diffOptions.targetCommitMessage
|
|
334
|
+
? { targetCommitMessage: diffOptions.targetCommitMessage }
|
|
335
|
+
: {}),
|
|
336
|
+
...(diffOptions.isWorkingTreeSnapshot !== undefined
|
|
337
|
+
? { isWorkingTreeSnapshot: diffOptions.isWorkingTreeSnapshot }
|
|
338
|
+
: {}),
|
|
339
|
+
...(diffOptions.snapshotAt
|
|
340
|
+
? { snapshotAt: diffOptions.snapshotAt }
|
|
341
|
+
: {}),
|
|
342
|
+
};
|
|
343
|
+
}
|
|
344
|
+
if (resolvedBranchName) {
|
|
345
|
+
targetLayout.branchName = resolvedBranchName;
|
|
346
|
+
if (targetLayout.healthSummary) {
|
|
347
|
+
targetLayout.healthSummary.branchName = resolvedBranchName;
|
|
348
|
+
}
|
|
349
|
+
}
|
|
350
|
+
if (resolvedCommitSha) {
|
|
351
|
+
targetLayout.commitSha = resolvedCommitSha;
|
|
352
|
+
if (targetLayout.healthSummary) {
|
|
353
|
+
targetLayout.healthSummary.commitSha = resolvedCommitSha;
|
|
354
|
+
}
|
|
355
|
+
}
|
|
356
|
+
if (resolvedCommitMessage) {
|
|
357
|
+
targetLayout.commitMessage = resolvedCommitMessage;
|
|
358
|
+
if (targetLayout.healthSummary) {
|
|
359
|
+
targetLayout.healthSummary.commitMessage = resolvedCommitMessage;
|
|
360
|
+
}
|
|
361
|
+
}
|
|
362
|
+
if (resolvedRemoteUrl) {
|
|
363
|
+
targetLayout.remoteUrl = resolvedRemoteUrl;
|
|
364
|
+
}
|
|
365
|
+
targetLayout.updatedAt = resolvedUpdatedAt;
|
|
366
|
+
if (targetLayout.healthSummary) {
|
|
367
|
+
targetLayout.healthSummary.updatedAt = resolvedUpdatedAt;
|
|
368
|
+
}
|
|
369
|
+
if (targetLayout.entitlement) {
|
|
370
|
+
state.latestEntitlement = targetLayout.entitlement;
|
|
371
|
+
}
|
|
372
|
+
};
|
|
373
|
+
if (state.layoutCache.has(cacheKey)) {
|
|
374
|
+
const cached = state.layoutCache.get(cacheKey);
|
|
375
|
+
stampLiveGitMetadata(cached);
|
|
376
|
+
triggerInitialPortHydrationAfterLayout(state);
|
|
377
|
+
return res.json(cached);
|
|
378
|
+
}
|
|
379
|
+
if (diffMode &&
|
|
380
|
+
committedDiffBaseSha &&
|
|
381
|
+
committedDiffTargetSha &&
|
|
382
|
+
!forceRefresh) {
|
|
383
|
+
const diffDiskSeed = `${CORE_EXTRACTOR_VERSION}:${rulesFp}:${authModeFp}`;
|
|
384
|
+
const diffDiskHit = readDiskDiffLayoutCache(activeDbPath, committedDiffBaseSha, committedDiffTargetSha, diffDiskSeed);
|
|
385
|
+
if (diffDiskHit) {
|
|
386
|
+
stampLiveGitMetadata(diffDiskHit);
|
|
387
|
+
state.layoutCache.set(cacheKey, diffDiskHit);
|
|
388
|
+
state.statusTracker.complete(1);
|
|
389
|
+
triggerInitialPortHydrationAfterLayout(state);
|
|
390
|
+
return res.json(diffDiskHit);
|
|
391
|
+
}
|
|
392
|
+
}
|
|
393
|
+
if (!diffMode && !forceRefresh) {
|
|
394
|
+
const diskHit = readDiskLayoutCache(activeDbPath, diskCacheSeed);
|
|
395
|
+
if (diskHit) {
|
|
396
|
+
if (diskHit.entitlement) {
|
|
397
|
+
state.latestEntitlement = diskHit.entitlement;
|
|
398
|
+
}
|
|
399
|
+
stampLiveGitMetadata(diskHit);
|
|
400
|
+
state.layoutCache.set(cacheKey, diskHit);
|
|
401
|
+
state.statusTracker.complete(1);
|
|
402
|
+
triggerInitialPortHydrationAfterLayout(state);
|
|
403
|
+
return res.json(diskHit);
|
|
404
|
+
}
|
|
405
|
+
}
|
|
406
|
+
if (state.layoutInFlight.has(cacheKey)) {
|
|
407
|
+
const pending = await state.layoutInFlight.get(cacheKey);
|
|
408
|
+
triggerInitialPortHydrationAfterLayout(state);
|
|
409
|
+
return res.json(pending);
|
|
410
|
+
}
|
|
411
|
+
const buildPromise = (async () => {
|
|
412
|
+
if (hydrateRefGraphsForBuild) {
|
|
413
|
+
await hydrateRefGraphsForBuild();
|
|
414
|
+
}
|
|
415
|
+
if (state.debug) {
|
|
416
|
+
console.log(`\n📐 Layout request — ${effectiveGraphForLayout.nodes.length} nodes, ${effectiveGraphForLayout.edges.length} edges` +
|
|
417
|
+
(diffMode
|
|
418
|
+
? ` [diff mode · ${diffOptions?.baseRef ?? "base"} -> ${diffOptions?.targetRef ?? "target"}]`
|
|
419
|
+
: ""));
|
|
420
|
+
}
|
|
421
|
+
const canonicalRepoName = repoPath
|
|
422
|
+
? resolveRepoName(repoPath)
|
|
423
|
+
: activeRepoName;
|
|
424
|
+
const resolvedRepoName = repo.name && (!repoPath || repo.name !== basename(repoPath))
|
|
425
|
+
? repo.name
|
|
426
|
+
: canonicalRepoName || repo.name || activeRepoName || "repository";
|
|
427
|
+
const resolvedRepoId = repo.id || resolvedRepoName.toLowerCase().replace(/[^a-z0-9_-]/g, "_");
|
|
428
|
+
const rulesConfig = loadRulesConfig(activeDbPath);
|
|
429
|
+
const contractCount = effectiveGraphForLayout.nodes.filter((n) => n.type === "CONTRACT")
|
|
430
|
+
.length || effectiveGraphForLayout.nodes.length;
|
|
431
|
+
const packageCount = effectiveGraphForLayout.nodes.filter((n) => n.entityType === "DEPLOYMENT_UNIT").length || 1;
|
|
432
|
+
const buildStartMs = Date.now();
|
|
433
|
+
state.statusTracker.begin({
|
|
434
|
+
repoName: resolvedRepoName,
|
|
435
|
+
branchName: resolvedBranchName,
|
|
436
|
+
diffMode,
|
|
437
|
+
contractCount,
|
|
438
|
+
packageCount,
|
|
439
|
+
});
|
|
440
|
+
let layout;
|
|
441
|
+
let liveGraph;
|
|
442
|
+
try {
|
|
443
|
+
const built = await buildLayout(effectiveGraphForLayout, repoPath, diffMode, resolvedRepoName, diffOptions?.targetGraph, rulesConfig, isCustomBranchView ? undefined : overlays, Boolean(state.debug), state.cloudUrl, (stage) => state.statusTracker.advance(stage), Boolean(state.remote), diffOptions);
|
|
444
|
+
layout = built.layout;
|
|
445
|
+
liveGraph = built.liveGraph;
|
|
446
|
+
}
|
|
447
|
+
catch (buildErr) {
|
|
448
|
+
state.statusTracker.fail(buildErr?.message || "Layout build failed");
|
|
449
|
+
throw buildErr;
|
|
450
|
+
}
|
|
451
|
+
state.statusTracker.complete(Date.now() - buildStartMs);
|
|
452
|
+
layout.repoId = resolvedRepoId;
|
|
453
|
+
if (layout.entitlement) {
|
|
454
|
+
state.latestEntitlement = layout.entitlement;
|
|
455
|
+
}
|
|
456
|
+
stampLiveGitMetadata(layout);
|
|
457
|
+
if (diffMode && liveGraph && diffOptions?.isWorkingTreeSnapshot) {
|
|
458
|
+
state.liveGraphCache = { key: cacheKey, liveGraph };
|
|
459
|
+
}
|
|
460
|
+
if (diffMode && layout.diffSummary) {
|
|
461
|
+
state.latestDiffSummary = {
|
|
462
|
+
fingerprintKey: cacheKey,
|
|
463
|
+
summary: layout.diffSummary,
|
|
464
|
+
};
|
|
465
|
+
if (committedDiffBaseSha && committedDiffTargetSha) {
|
|
466
|
+
const diffDiskSeed = `${CORE_EXTRACTOR_VERSION}:${rulesFp}:${authModeFp}`;
|
|
467
|
+
writeDiskDiffLayoutCache(activeDbPath, committedDiffBaseSha, committedDiffTargetSha, diffDiskSeed, layout);
|
|
468
|
+
}
|
|
469
|
+
}
|
|
470
|
+
else if (!diffMode) {
|
|
471
|
+
writeDiskLayoutCache(activeDbPath, diskCacheSeed, layout);
|
|
472
|
+
}
|
|
473
|
+
if (state.layoutCache.size >= 8) {
|
|
474
|
+
const oldestKey = state.layoutCache.keys().next().value;
|
|
475
|
+
if (oldestKey)
|
|
476
|
+
state.layoutCache.delete(oldestKey);
|
|
477
|
+
}
|
|
478
|
+
state.layoutCache.set(cacheKey, layout);
|
|
479
|
+
const revisionLogKey = `${activeDbPath}:${dbMtime}:${rulesFp}:${authModeFp}`;
|
|
480
|
+
if (state.debug || process.env.CHOMP_DEBUG_LAYOUT === "1") {
|
|
481
|
+
console.log(`✅ Layout complete — ${layout.nodes.length} positioned nodes, ` +
|
|
482
|
+
`${layout.islandNodes.length} islands, ${layout.badgeNodes.length} badge hubs`);
|
|
483
|
+
}
|
|
484
|
+
else if (!state.loggedBoardRevisions.has(revisionLogKey)) {
|
|
485
|
+
state.loggedBoardRevisions.add(revisionLogKey);
|
|
486
|
+
const pkgCount = Object.keys(layout.packageBounds ?? {}).length || 1;
|
|
487
|
+
console.log(` ${ansi.green("✓")} ${ansi.bold("Chomp Map ready")} ${ansi.dim(`— mapped ${layout.nodes.length} nodes across ${pkgCount} package${pkgCount === 1 ? "" : "s"}`)}`);
|
|
488
|
+
if (!state.isMasterLocalMode && layout.entitlement) {
|
|
489
|
+
const ent = layout.entitlement;
|
|
490
|
+
const authStatus = buildAuthStatusPayload(state);
|
|
491
|
+
const handleTag = ent.githubHandle
|
|
492
|
+
? `@${ent.githubHandle.replace(/^@+/, "")}`
|
|
493
|
+
: authStatus.githubHandle
|
|
494
|
+
? `@${authStatus.githubHandle}`
|
|
495
|
+
: "";
|
|
496
|
+
if (ent.previewMode) {
|
|
497
|
+
const isExpired = ent.gatingMode === "enforced" && ent.tier === "trial_expired";
|
|
498
|
+
const lockDetail = ent.lockedStationCount
|
|
499
|
+
? ` (${ent.unlockedStationCount ?? 100} stations shown · ${ent.lockedStationCount} locked)`
|
|
500
|
+
: "";
|
|
501
|
+
const actionHint = isExpired
|
|
502
|
+
? "upgrade at https://getchomp.dev/account"
|
|
503
|
+
: ent.gatingMode === "enforced"
|
|
504
|
+
? "sign in with GitHub in browser for 14-day full trial"
|
|
505
|
+
: "sign in with GitHub in browser for free Early Access";
|
|
506
|
+
console.log(` ${ansi.yellowBold("↳")} ${ansi.dim("Visualizer Access:")} ${isExpired ? "14-Day Trial Ended" : "Preview Mode"}${lockDetail} — ${actionHint}`);
|
|
507
|
+
}
|
|
508
|
+
else {
|
|
509
|
+
const tierText = ent.tier === "early_access" ||
|
|
510
|
+
(ent.gatingMode !== "enforced" && ent.tier === "trial")
|
|
511
|
+
? "Early Access (Full repo unlocked)"
|
|
512
|
+
: ent.tier === "trial"
|
|
513
|
+
? `14-Day Trial (${ent.trialDaysRemaining ? `${ent.trialDaysRemaining}d remaining · ` : ""}Full repo unlocked)`
|
|
514
|
+
: ent.tier === "team"
|
|
515
|
+
? "Team Plan (Full repo unlocked)"
|
|
516
|
+
: ent.tier === "pro"
|
|
517
|
+
? "Solo Pro (Full repo unlocked)"
|
|
518
|
+
: ent.tier === "vip"
|
|
519
|
+
? "VIP Partner (Full repo unlocked)"
|
|
520
|
+
: "Full repo unlocked";
|
|
521
|
+
console.log(` ${ansi.cyan("↳")} ${ansi.dim("Visualizer Access:")} ${tierText}${handleTag ? ` ${ansi.dim(`· ${handleTag}`)}` : ""}`);
|
|
522
|
+
}
|
|
523
|
+
}
|
|
524
|
+
}
|
|
525
|
+
return layout;
|
|
526
|
+
})().finally(() => {
|
|
527
|
+
state.layoutInFlight.delete(cacheKey);
|
|
528
|
+
});
|
|
529
|
+
state.layoutInFlight.set(cacheKey, buildPromise);
|
|
530
|
+
const resultLayout = await buildPromise;
|
|
531
|
+
triggerInitialPortHydrationAfterLayout(state);
|
|
532
|
+
return res.json(resultLayout);
|
|
533
|
+
}
|
|
534
|
+
catch (error) {
|
|
535
|
+
console.error("Layout error:", error);
|
|
536
|
+
if (error.lintErrors) {
|
|
537
|
+
return res.status(500).json({
|
|
538
|
+
error: error.message,
|
|
539
|
+
details: error.lintErrors,
|
|
540
|
+
});
|
|
541
|
+
}
|
|
542
|
+
return res.status(500).json({
|
|
543
|
+
error: error.message || "Internal server error",
|
|
544
|
+
...(error.code ? { code: String(error.code) } : {}),
|
|
545
|
+
...(typeof error.upstreamStatus === "number"
|
|
546
|
+
? { upstreamStatus: error.upstreamStatus }
|
|
547
|
+
: {}),
|
|
548
|
+
...(error.rayId ? { rayId: String(error.rayId) } : {}),
|
|
549
|
+
...(error.upstreamUrl ? { upstreamUrl: String(error.upstreamUrl) } : {}),
|
|
550
|
+
});
|
|
551
|
+
}
|
|
552
|
+
});
|
|
553
|
+
// GET /api/graph — raw sanitized graph + structural overlays for inspector evidence
|
|
554
|
+
app.get("/api/graph", async (req, res) => {
|
|
555
|
+
try {
|
|
556
|
+
const { target: activeTarget, dbPath: activeDbPath } = getActiveUiTarget(state);
|
|
557
|
+
const diffMode = req.query.diff === "true" || req.query.diff === "1";
|
|
558
|
+
const rawBaseParam = typeof req.query.base === "string" && req.query.base.trim()
|
|
559
|
+
? req.query.base.trim()
|
|
560
|
+
: undefined;
|
|
561
|
+
const rawTargetParamRaw = typeof req.query.target === "string" && req.query.target.trim()
|
|
562
|
+
? req.query.target.trim()
|
|
563
|
+
: undefined;
|
|
564
|
+
const rawTargetParam = rawTargetParamRaw &&
|
|
565
|
+
rawTargetParamRaw.toUpperCase() === "WORKING_TREE"
|
|
566
|
+
? "WORKING_TREE"
|
|
567
|
+
: rawTargetParamRaw?.toLowerCase() === "working-tree"
|
|
568
|
+
? "WORKING_TREE"
|
|
569
|
+
: rawTargetParamRaw;
|
|
570
|
+
const baseData = await loadBaseGraphCached(state);
|
|
571
|
+
if (!baseData) {
|
|
572
|
+
return res.status(404).json({
|
|
573
|
+
error: "No repositories or graph found in database.",
|
|
574
|
+
code: "NO_GRAPH",
|
|
575
|
+
});
|
|
576
|
+
}
|
|
577
|
+
const { repo, graph, structuralOverlays: overlays } = baseData;
|
|
578
|
+
const repoPath = repo.path || activeTarget;
|
|
579
|
+
const overlayLayers = loadRulesConfig(activeDbPath).overlayLayers;
|
|
580
|
+
let activeBaseGraph = graph;
|
|
581
|
+
if (!diffMode &&
|
|
582
|
+
rawBaseParam &&
|
|
583
|
+
repoPath &&
|
|
584
|
+
existsSync(repoPath)) {
|
|
585
|
+
try {
|
|
586
|
+
const resolved = await resolveCommittedRefGraph(repoPath, rawBaseParam, {
|
|
587
|
+
dbPath: activeDbPath,
|
|
588
|
+
});
|
|
589
|
+
activeBaseGraph = resolved.graph;
|
|
590
|
+
}
|
|
591
|
+
catch {
|
|
592
|
+
activeBaseGraph = graph;
|
|
593
|
+
}
|
|
594
|
+
}
|
|
595
|
+
let projectedGraph = applyActivePluginProjections(activeBaseGraph, {
|
|
596
|
+
repoPath,
|
|
597
|
+
overlays: activeBaseGraph === graph ? overlays : [],
|
|
598
|
+
overlayLayers,
|
|
599
|
+
});
|
|
600
|
+
if (diffMode && repoPath && existsSync(repoPath)) {
|
|
601
|
+
const gitTargets = await listGitBranchesAndWorktrees(repoPath);
|
|
602
|
+
const liveGit = await getGitInfoAsync(repoPath);
|
|
603
|
+
const currentBranch = liveGit.branchName ||
|
|
604
|
+
repo.branchName ||
|
|
605
|
+
graph.branchName ||
|
|
606
|
+
gitTargets.currentBranch ||
|
|
607
|
+
"HEAD";
|
|
608
|
+
const defaultBase = gitTargets.defaultBaseBranch || currentBranch;
|
|
609
|
+
const hasDefaultBaseBranch = gitTargets.branches.some((b) => b.name === defaultBase);
|
|
610
|
+
const effectiveBaseRef = rawBaseParam ??
|
|
611
|
+
(rawTargetParam === "WORKING_TREE"
|
|
612
|
+
? currentBranch
|
|
613
|
+
: currentBranch !== defaultBase && hasDefaultBaseBranch
|
|
614
|
+
? defaultBase
|
|
615
|
+
: currentBranch);
|
|
616
|
+
const effectiveTargetRef = rawTargetParam ??
|
|
617
|
+
(currentBranch && currentBranch !== effectiveBaseRef
|
|
618
|
+
? currentBranch
|
|
619
|
+
: "WORKING_TREE");
|
|
620
|
+
const inMemoryBase = {
|
|
621
|
+
activeDbPath,
|
|
622
|
+
baseData,
|
|
623
|
+
activeCommitSha: liveGit.commitSha || repo.commitSha || graph.commitSha,
|
|
624
|
+
workingTreeDirty: gitTargets.workingTreeDirty,
|
|
625
|
+
};
|
|
626
|
+
const baseRefInfo = await resolveGitRefInfo(repoPath, effectiveBaseRef, gitTargets);
|
|
627
|
+
const baseResolved = await resolveCommittedRefGraph(repoPath, effectiveBaseRef, {
|
|
628
|
+
dbPath: activeDbPath,
|
|
629
|
+
resolvedRef: baseRefInfo,
|
|
630
|
+
inMemoryBase,
|
|
631
|
+
}).catch(() => null);
|
|
632
|
+
const baseRaw = baseResolved?.graph ?? graph;
|
|
633
|
+
const baseSha = baseResolved?.fullCommitSha ?? graph.commitSha;
|
|
634
|
+
let targetRaw;
|
|
635
|
+
let targetSha;
|
|
636
|
+
let isWorkingTree = true;
|
|
637
|
+
if (effectiveTargetRef !== "WORKING_TREE") {
|
|
638
|
+
const targetRefInfo = await resolveGitRefInfo(repoPath, effectiveTargetRef, gitTargets);
|
|
639
|
+
const targetResolved = await resolveCommittedRefGraph(repoPath, effectiveTargetRef, {
|
|
640
|
+
dbPath: activeDbPath,
|
|
641
|
+
resolvedRef: targetRefInfo,
|
|
642
|
+
inMemoryBase,
|
|
643
|
+
});
|
|
644
|
+
targetRaw = targetResolved.graph;
|
|
645
|
+
targetSha = targetResolved.fullCommitSha;
|
|
646
|
+
isWorkingTree = false;
|
|
647
|
+
}
|
|
648
|
+
else {
|
|
649
|
+
const wtFingerprint = await computeWorkingTreeFingerprintAsync(repoPath);
|
|
650
|
+
const snap = resolveWorkingTreeSnapshotGraph(state, repoPath, wtFingerprint, false);
|
|
651
|
+
targetRaw = snap.liveGraph;
|
|
652
|
+
}
|
|
653
|
+
const scopedDiffPaths = resolveScopedDiffPaths(repoPath, baseSha, targetSha, isWorkingTree);
|
|
654
|
+
const baseForDiff = hasGitCommitForDiff(repoPath, baseSha)
|
|
655
|
+
? applyActivePluginProjections(baseRaw, {
|
|
656
|
+
repoPath,
|
|
657
|
+
overlayLayers,
|
|
658
|
+
readRepoFileOverride: (rel) => readGitBlobForDiff(repoPath, baseSha.trim(), rel, scopedDiffPaths),
|
|
659
|
+
})
|
|
660
|
+
: baseRaw;
|
|
661
|
+
const projectedLiveGraph = !isWorkingTree && hasGitCommitForDiff(repoPath, targetSha)
|
|
662
|
+
? applyActivePluginProjections(targetRaw, {
|
|
663
|
+
repoPath,
|
|
664
|
+
overlayLayers,
|
|
665
|
+
readRepoFileOverride: (rel) => readGitBlobForDiff(repoPath, targetSha.trim(), rel, scopedDiffPaths),
|
|
666
|
+
})
|
|
667
|
+
: applyActivePluginProjections(targetRaw, {
|
|
668
|
+
repoPath,
|
|
669
|
+
overlayLayers,
|
|
670
|
+
});
|
|
671
|
+
const diffDelta = compareGraphs(baseForDiff, projectedLiveGraph);
|
|
672
|
+
const removedNodes = Object.values(diffDelta.nodes)
|
|
673
|
+
.filter((entry) => entry.status === "REMOVED" && entry.base)
|
|
674
|
+
.map((entry) => entry.base);
|
|
675
|
+
const removedEdges = Object.values(diffDelta.edges)
|
|
676
|
+
.filter((entry) => entry.status === "REMOVED" && entry.base)
|
|
677
|
+
.map((entry) => entry.base);
|
|
678
|
+
projectedGraph = {
|
|
679
|
+
...projectedLiveGraph,
|
|
680
|
+
nodes: [...projectedLiveGraph.nodes, ...removedNodes],
|
|
681
|
+
edges: [...projectedLiveGraph.edges, ...removedEdges],
|
|
682
|
+
};
|
|
683
|
+
}
|
|
684
|
+
let gridLayout = null;
|
|
685
|
+
const gridLayoutPath = join(dirname(activeDbPath), "grid_layout.json");
|
|
686
|
+
if (existsSync(gridLayoutPath)) {
|
|
687
|
+
try {
|
|
688
|
+
gridLayout = JSON.parse(readFileSync(gridLayoutPath, "utf-8"));
|
|
689
|
+
}
|
|
690
|
+
catch {
|
|
691
|
+
console.error("Failed to parse grid_layout.json");
|
|
692
|
+
}
|
|
693
|
+
}
|
|
694
|
+
const sanitizedGraph = stripEvidenceSnippetsFromGraph(projectedGraph);
|
|
695
|
+
return res.json({
|
|
696
|
+
nodes: sanitizedGraph.nodes,
|
|
697
|
+
edges: sanitizedGraph.edges,
|
|
698
|
+
overlays,
|
|
699
|
+
gridLayout,
|
|
700
|
+
});
|
|
701
|
+
}
|
|
702
|
+
catch (error) {
|
|
703
|
+
console.error("Error fetching graph:", error);
|
|
704
|
+
return res.status(500).json({ error: "Internal server error" });
|
|
705
|
+
}
|
|
706
|
+
});
|
|
707
|
+
// GET / POST / DELETE /api/overlays — dedicated entity_overlays storage ([PAT-DB-03])
|
|
708
|
+
app.get("/api/overlays", async (req, res) => {
|
|
709
|
+
try {
|
|
710
|
+
const baseData = await loadBaseGraphCached(state);
|
|
711
|
+
if (!baseData) {
|
|
712
|
+
return res.json([]);
|
|
713
|
+
}
|
|
714
|
+
const entityId = typeof req.query.entityId === "string" ? req.query.entityId : undefined;
|
|
715
|
+
const layer = typeof req.query.layer === "string" ? req.query.layer : undefined;
|
|
716
|
+
const source = typeof req.query.source === "string" ? req.query.source : undefined;
|
|
717
|
+
const environment = typeof req.query.environment === "string"
|
|
718
|
+
? req.query.environment
|
|
719
|
+
: undefined;
|
|
720
|
+
const filtered = baseData.overlays.filter((ov) => {
|
|
721
|
+
if (entityId && ov.entityId !== entityId)
|
|
722
|
+
return false;
|
|
723
|
+
if (layer && ov.layer !== layer)
|
|
724
|
+
return false;
|
|
725
|
+
if (source && ov.source !== source)
|
|
726
|
+
return false;
|
|
727
|
+
if (environment && ov.environment !== environment)
|
|
728
|
+
return false;
|
|
729
|
+
return true;
|
|
730
|
+
});
|
|
731
|
+
return res.json(filtered);
|
|
732
|
+
}
|
|
733
|
+
catch (e) {
|
|
734
|
+
console.error("Error fetching overlays:", e);
|
|
735
|
+
return res.status(500).json({ error: "Failed to fetch entity overlays" });
|
|
736
|
+
}
|
|
737
|
+
});
|
|
738
|
+
app.post("/api/overlays", async (req, res) => {
|
|
739
|
+
try {
|
|
740
|
+
const { dbPath: activeDbPath } = getActiveUiTarget(state);
|
|
741
|
+
const storage = createSQLiteStorage(activeDbPath);
|
|
742
|
+
const repos = await storage.listRepositories();
|
|
743
|
+
if (repos.length === 0) {
|
|
744
|
+
await storage.close();
|
|
745
|
+
return res.status(404).json({ error: "No repository found in database" });
|
|
746
|
+
}
|
|
747
|
+
const repo = repos[0];
|
|
748
|
+
const items = Array.isArray(req.body)
|
|
749
|
+
? req.body
|
|
750
|
+
: req.body?.overlays
|
|
751
|
+
? req.body.overlays
|
|
752
|
+
: [req.body];
|
|
753
|
+
const valid = items.filter((item) => item &&
|
|
754
|
+
typeof item.entityId === "string" &&
|
|
755
|
+
typeof item.layer === "string");
|
|
756
|
+
const runId = typeof req.body?.runId === "string" ? req.body.runId : undefined;
|
|
757
|
+
const pruneStaleBySource = typeof req.body?.pruneStaleBySource === "boolean"
|
|
758
|
+
? req.body.pruneStaleBySource
|
|
759
|
+
: undefined;
|
|
760
|
+
await storage.upsertEntityOverlays(valid, {
|
|
761
|
+
repositoryId: repo.id,
|
|
762
|
+
...(runId ? { runId } : {}),
|
|
763
|
+
...(pruneStaleBySource !== undefined ? { pruneStaleBySource } : {}),
|
|
764
|
+
});
|
|
765
|
+
await storage.close();
|
|
766
|
+
state.layoutCache.clear();
|
|
767
|
+
state.baseGraphCache = null;
|
|
768
|
+
return res.json({ success: true, count: valid.length });
|
|
769
|
+
}
|
|
770
|
+
catch (e) {
|
|
771
|
+
console.error("Error saving overlays:", e);
|
|
772
|
+
return res.status(500).json({ error: "Failed to save entity overlays" });
|
|
773
|
+
}
|
|
774
|
+
});
|
|
775
|
+
app.delete("/api/overlays", async (req, res) => {
|
|
776
|
+
try {
|
|
777
|
+
const { dbPath: activeDbPath } = getActiveUiTarget(state);
|
|
778
|
+
const storage = createSQLiteStorage(activeDbPath);
|
|
779
|
+
const repos = await storage.listRepositories();
|
|
780
|
+
if (repos.length === 0) {
|
|
781
|
+
await storage.close();
|
|
782
|
+
return res.status(404).json({ error: "No repository found in database" });
|
|
783
|
+
}
|
|
784
|
+
const repo = repos[0];
|
|
785
|
+
const entityId = (req.body?.entityId ?? req.query.entityId);
|
|
786
|
+
const layer = (req.body?.layer ?? req.query.layer);
|
|
787
|
+
const source = (req.body?.source ?? req.query.source);
|
|
788
|
+
const environment = (req.body?.environment ?? req.query.environment);
|
|
789
|
+
const activeRunId = (req.body?.activeRunId ?? req.query.activeRunId);
|
|
790
|
+
if (activeRunId && layer && source) {
|
|
791
|
+
const pruned = await storage.pruneEntityOverlays({
|
|
792
|
+
repositoryId: repo.id,
|
|
793
|
+
layer,
|
|
794
|
+
source,
|
|
795
|
+
environment,
|
|
796
|
+
activeRunId,
|
|
797
|
+
});
|
|
798
|
+
await storage.close();
|
|
799
|
+
state.layoutCache.clear();
|
|
800
|
+
state.baseGraphCache = null;
|
|
801
|
+
return res.json({ success: true, pruned });
|
|
802
|
+
}
|
|
803
|
+
if (!entityId || !layer) {
|
|
804
|
+
await storage.close();
|
|
805
|
+
return res
|
|
806
|
+
.status(400)
|
|
807
|
+
.json({ error: "entityId and layer are required" });
|
|
808
|
+
}
|
|
809
|
+
await storage.deleteEntityOverlay({
|
|
810
|
+
repositoryId: repo.id,
|
|
811
|
+
entityId,
|
|
812
|
+
layer,
|
|
813
|
+
source,
|
|
814
|
+
environment,
|
|
815
|
+
});
|
|
816
|
+
await storage.close();
|
|
817
|
+
state.layoutCache.clear();
|
|
818
|
+
state.baseGraphCache = null;
|
|
819
|
+
return res.json({ success: true });
|
|
820
|
+
}
|
|
821
|
+
catch (e) {
|
|
822
|
+
console.error("Error deleting overlay:", e);
|
|
823
|
+
return res.status(500).json({ error: "Failed to delete entity overlay" });
|
|
824
|
+
}
|
|
825
|
+
});
|
|
826
|
+
// POST /api/ports/verify — trigger Speed 2 port valve hydration
|
|
827
|
+
app.post("/api/ports/verify", async (req, res) => {
|
|
828
|
+
try {
|
|
829
|
+
const force = Boolean(req.body?.force);
|
|
830
|
+
const result = await scheduleBackgroundPortHydration(state, force);
|
|
831
|
+
if (!result) {
|
|
832
|
+
return res
|
|
833
|
+
.status(404)
|
|
834
|
+
.json({ error: "No repository graph available to verify ports." });
|
|
835
|
+
}
|
|
836
|
+
return res.json(result);
|
|
837
|
+
}
|
|
838
|
+
catch (e) {
|
|
839
|
+
return res
|
|
840
|
+
.status(500)
|
|
841
|
+
.json({ error: e?.message || "Failed to verify port valves" });
|
|
842
|
+
}
|
|
843
|
+
});
|
|
844
|
+
// POST /api/telemetry — debug telemetry snapshot
|
|
845
|
+
app.post("/api/telemetry", (req, res) => {
|
|
846
|
+
try {
|
|
847
|
+
const { dbPath: activeDbPath } = getActiveUiTarget(state);
|
|
848
|
+
const telemetryPath = join(dirname(activeDbPath), "telemetry.json");
|
|
849
|
+
writeFileSync(telemetryPath, JSON.stringify(req.body, null, 2));
|
|
850
|
+
return res.json({ success: true });
|
|
851
|
+
}
|
|
852
|
+
catch (e) {
|
|
853
|
+
console.error("Telemetry error:", e);
|
|
854
|
+
return res.status(500).json({ error: "Failed to write telemetry" });
|
|
855
|
+
}
|
|
856
|
+
});
|
|
857
|
+
}
|