@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,356 @@
1
+ /**
2
+ * @fileoverview Zero-Backend Static Site Export (`chomp export [path] -o <outDir>`) ([PAT-CLI-13], [PAT-VIS-28]).
3
+ *
4
+ * Exports a self-contained static HTML/JS + JSON representation bundle deployable to GitHub Pages,
5
+ * S3, Vercel/Netlify static hosting, or CI build artifacts without an Express server or SQLite runtime.
6
+ */
7
+ import { cpSync, existsSync, mkdirSync, readFileSync, statSync, writeFileSync, } from "node:fs";
8
+ import { basename, dirname, join, resolve } from "node:path";
9
+ import { fileURLToPath } from "node:url";
10
+ import { createSQLiteStorage } from "@getchomp/db";
11
+ import { applyActivePluginProjections, discoverPluginsInDir, getPluginEnvStatus, getPluginMcpToolSummaries, getPluginStateDirRel, isRegisteredStructuralPluginOverlay, listChompPlugins, loadPluginSettings, } from "@getchomp/mcp";
12
+ import { stripEvidenceSnippetsFromGraph } from "../visualizer/cloudLayoutClient.js";
13
+ import { computeWorkingTreeFingerprint } from "../visualizer/layoutCache.js";
14
+ import { buildEntityPresentations, buildPluginsOverview, computePluginFingerprint, computeStructureFingerprint, overlaysForStructureFingerprint, rulesReferenceOverlays, snapshotPluginRuns, splitOverlays, } from "../visualizer/pluginPresentationApi.js";
15
+ import { getRulesFingerprint, loadRulesConfig, } from "../visualizer/rulesConfig.js";
16
+ import { ansi } from "../utils/branding.js";
17
+ import { getGitInfo, resolveRepoName } from "../utils/git.js";
18
+ import { getChompMasterRoot, resolveDefaultCliTarget, } from "../utils/masterContext.js";
19
+ import { runAnalyze } from "./analyze.js";
20
+ import { buildLayout } from "../server/graphLayoutState.js";
21
+ const __dirname = dirname(fileURLToPath(import.meta.url));
22
+ function resolveBundledUiDir(explicitUiDir) {
23
+ if (explicitUiDir) {
24
+ const resolved = resolve(explicitUiDir);
25
+ return existsSync(resolved) ? resolved : null;
26
+ }
27
+ const masterUiOut = resolve(getChompMasterRoot(), "apps/web/out");
28
+ if (existsSync(join(masterUiOut, "index.html"))) {
29
+ return masterUiOut;
30
+ }
31
+ const prodUiOut = resolve(__dirname, "../ui");
32
+ if (existsSync(join(prodUiOut, "index.html"))) {
33
+ return prodUiOut;
34
+ }
35
+ return null;
36
+ }
37
+ function writeJsonArtifact(filePath, data) {
38
+ mkdirSync(dirname(filePath), { recursive: true });
39
+ writeFileSync(filePath, JSON.stringify(data), "utf-8");
40
+ }
41
+ function injectSnapshotScriptIntoHtml(html) {
42
+ const scriptTag = '<script src="./chomp-snapshot.js"></script>';
43
+ if (html.includes("chomp-snapshot.js")) {
44
+ return html;
45
+ }
46
+ if (html.includes("</head>")) {
47
+ return html.replace("</head>", `${scriptTag}</head>`);
48
+ }
49
+ if (html.includes("<body")) {
50
+ return `${scriptTag}\n${html}`;
51
+ }
52
+ return `${scriptTag}\n${html}`;
53
+ }
54
+ export async function runExport(targetPath, options = {}) {
55
+ const resolvedTarget = resolve(targetPath);
56
+ if (!existsSync(resolvedTarget)) {
57
+ throw new Error(`Target path does not exist: ${resolvedTarget}`);
58
+ }
59
+ const isDir = statSync(resolvedTarget).isDirectory();
60
+ const repoPath = isDir ? resolvedTarget : dirname(resolvedTarget);
61
+ const baseDir = process.env.INIT_CWD ?? process.cwd();
62
+ const dbPath = options.db
63
+ ? resolve(baseDir, options.db)
64
+ : resolve(repoPath, ".chomp", "graph.db");
65
+ const outDir = options.out
66
+ ? resolve(baseDir, options.out)
67
+ : resolve(repoPath, "chomp-export");
68
+ await discoverPluginsInDir(resolve(repoPath, ".chomp", "plugins")).catch(() => []);
69
+ const liveGit = getGitInfo(repoPath);
70
+ let shouldAnalyze = Boolean(options.forceAnalyze) || !existsSync(dbPath);
71
+ if (!shouldAnalyze && !options.skipAnalyze && existsSync(dbPath)) {
72
+ const probeStorage = createSQLiteStorage(dbPath);
73
+ try {
74
+ const repos = await probeStorage.listRepositories();
75
+ if (repos.length === 0) {
76
+ shouldAnalyze = true;
77
+ }
78
+ else if (liveGit.commitSha &&
79
+ repos[0].commitSha &&
80
+ repos[0].commitSha !== liveGit.commitSha) {
81
+ shouldAnalyze = true;
82
+ }
83
+ }
84
+ finally {
85
+ await probeStorage.close();
86
+ }
87
+ }
88
+ if (shouldAnalyze && !options.skipAnalyze) {
89
+ if (!options.quiet) {
90
+ console.log(` ${ansi.cyan("↻")} Refreshing structural graph in ${ansi.dim(dbPath)}...`);
91
+ }
92
+ await runAnalyze(repoPath, {
93
+ db: dbPath,
94
+ quiet: true,
95
+ });
96
+ }
97
+ if (!existsSync(dbPath)) {
98
+ throw new Error(`Chomp database not found at ${dbPath}`);
99
+ }
100
+ const storage = createSQLiteStorage(dbPath);
101
+ let repo;
102
+ let graph;
103
+ let overlays = [];
104
+ try {
105
+ const repos = await storage.listRepositories();
106
+ if (repos.length === 0) {
107
+ throw new Error(`No repositories found in ${dbPath}`);
108
+ }
109
+ const canonicalName = resolveRepoName(repoPath);
110
+ const canonicalId = canonicalName.toLowerCase().replace(/[^a-z0-9_-]/g, "_");
111
+ repo =
112
+ repos.find((r) => r.id === canonicalId || r.name === canonicalName) ??
113
+ repos[0];
114
+ graph = await storage.getRepresentationGraph(repo.id);
115
+ if (!graph) {
116
+ throw new Error(`Representation graph missing for repository '${repo.id}'`);
117
+ }
118
+ try {
119
+ overlays = (await storage.getEntityOverlays(repo.id));
120
+ }
121
+ catch {
122
+ overlays = [];
123
+ }
124
+ }
125
+ finally {
126
+ await storage.close();
127
+ }
128
+ const canonicalRepoName = resolveRepoName(repoPath);
129
+ const resolvedRepoName = repo.name && repo.name !== basename(repoPath)
130
+ ? repo.name
131
+ : canonicalRepoName || repo.name || "repository";
132
+ const resolvedRepoId = repo.id || resolvedRepoName.toLowerCase().replace(/[^a-z0-9_-]/g, "_");
133
+ const resolvedBranchName = liveGit.branchName || repo.branchName || graph.branchName;
134
+ const resolvedCommitSha = liveGit.commitSha || repo.commitSha || graph.commitSha;
135
+ const resolvedCommitMessage = liveGit.commitMessage;
136
+ const resolvedRemoteUrl = liveGit.remoteUrl;
137
+ const dbMtime = existsSync(dbPath) ? statSync(dbPath).mtimeMs : Date.now();
138
+ const resolvedUpdatedAt = dbMtime || Date.now();
139
+ const rulesConfig = loadRulesConfig(dbPath);
140
+ const split = splitOverlays(overlays);
141
+ const structuralOverlays = split.layout;
142
+ const pluginOverlays = split.plugin;
143
+ // Build both normalLayout (diffMode = false) and diffLayout (diffMode = true)
144
+ const normalBuilt = await buildLayout(graph, repoPath, false, resolvedRepoName, undefined, rulesConfig, structuralOverlays, false, options.cloudUrl);
145
+ const diffBuilt = await buildLayout(graph, repoPath, true, resolvedRepoName, undefined, rulesConfig, structuralOverlays, false, options.cloudUrl);
146
+ const decorateLayoutMeta = (layout) => {
147
+ layout.repoId = resolvedRepoId;
148
+ if (resolvedBranchName) {
149
+ layout.branchName = resolvedBranchName;
150
+ if (layout.healthSummary) {
151
+ layout.healthSummary.branchName = resolvedBranchName;
152
+ }
153
+ }
154
+ if (resolvedCommitSha) {
155
+ layout.commitSha = resolvedCommitSha;
156
+ if (layout.healthSummary) {
157
+ layout.healthSummary.commitSha = resolvedCommitSha;
158
+ }
159
+ }
160
+ if (resolvedCommitMessage) {
161
+ layout.commitMessage = resolvedCommitMessage;
162
+ if (layout.healthSummary) {
163
+ layout.healthSummary.commitMessage = resolvedCommitMessage;
164
+ }
165
+ }
166
+ if (resolvedRemoteUrl) {
167
+ layout.remoteUrl = resolvedRemoteUrl;
168
+ }
169
+ layout.updatedAt = resolvedUpdatedAt;
170
+ if (layout.healthSummary) {
171
+ layout.healthSummary.updatedAt = resolvedUpdatedAt;
172
+ }
173
+ return layout;
174
+ };
175
+ const normalLayout = decorateLayoutMeta(normalBuilt.layout);
176
+ const diffLayout = decorateLayoutMeta(diffBuilt.layout);
177
+ if (diffLayout.diffSummary && !normalLayout.diffSummary) {
178
+ normalLayout.diffSummary = diffLayout.diffSummary;
179
+ }
180
+ // Build snippet-free /api/graph payload
181
+ const projectedGraph = applyActivePluginProjections(graph, {
182
+ repoPath,
183
+ overlays: structuralOverlays,
184
+ overlayLayers: rulesConfig.overlayLayers,
185
+ });
186
+ const sanitizedGraph = stripEvidenceSnippetsFromGraph(projectedGraph);
187
+ const graphPayload = {
188
+ nodes: sanitizedGraph.nodes,
189
+ edges: sanitizedGraph.edges,
190
+ overlays: structuralOverlays,
191
+ gridLayout: null,
192
+ };
193
+ // Resolve /api/view (.chomp/current_view.json) if valid for this repo
194
+ let activeViewPayload = null;
195
+ const viewPath = join(dirname(dbPath), "current_view.json");
196
+ if (existsSync(viewPath)) {
197
+ try {
198
+ const rawView = JSON.parse(readFileSync(viewPath, "utf-8"));
199
+ if (rawView &&
200
+ typeof rawView === "object" &&
201
+ (!rawView.repoId || rawView.repoId === resolvedRepoId) &&
202
+ (!rawView.repoName || rawView.repoName === resolvedRepoName)) {
203
+ const isBranchMismatch = Boolean(rawView.branchName &&
204
+ resolvedBranchName &&
205
+ rawView.branchName !== resolvedBranchName);
206
+ activeViewPayload = {
207
+ ...rawView,
208
+ repoId: resolvedRepoId,
209
+ repoName: resolvedRepoName,
210
+ ...(resolvedBranchName ? { currentBranchName: resolvedBranchName } : {}),
211
+ ...(isBranchMismatch
212
+ ? { expired: true, expiredReason: "branch_mismatch" }
213
+ : { expired: false }),
214
+ };
215
+ }
216
+ }
217
+ catch {
218
+ activeViewPayload = null;
219
+ }
220
+ }
221
+ // Build plugin overview + per-entity presentations for 0ms static drawer hydration
222
+ const pluginRuns = new Map();
223
+ const registryMeta = listChompPlugins().map((p) => {
224
+ const settings = p.settingsSchema ? loadPluginSettings(repoPath, p) : undefined;
225
+ const envStatus = settings ? getPluginEnvStatus(p, settings) : undefined;
226
+ return {
227
+ name: p.name,
228
+ displayName: p.displayName,
229
+ description: p.description,
230
+ version: p.version,
231
+ layer: p.layer,
232
+ defaultEnabled: p.defaultEnabled ?? true,
233
+ stateDir: getPluginStateDirRel(p.name),
234
+ ...(p.settingsSchema ? { settingsSchema: p.settingsSchema } : {}),
235
+ ...(settings ? { settings } : {}),
236
+ ...(envStatus ? { envStatus } : {}),
237
+ ...(p.mcpTools && p.mcpTools.length > 0
238
+ ? { mcpTools: getPluginMcpToolSummaries(p) }
239
+ : {}),
240
+ };
241
+ });
242
+ const structureFp = computeStructureFingerprint(graph.nodes, graph.edges, overlaysForStructureFingerprint(split, rulesReferenceOverlays(rulesConfig.customRules), isRegisteredStructuralPluginOverlay));
243
+ const pluginFp = computePluginFingerprint(pluginOverlays, snapshotPluginRuns(pluginRuns), registryMeta);
244
+ const fingerprintPayload = {
245
+ dbMtime,
246
+ rulesFp: `static:${getRulesFingerprint(dbPath)}`,
247
+ wtFingerprint: computeWorkingTreeFingerprint(repoPath),
248
+ structureFp,
249
+ pluginFp,
250
+ staticExport: true,
251
+ };
252
+ const pluginsOverview = buildPluginsOverview({
253
+ pluginOverlays,
254
+ nodes: graph.nodes,
255
+ registry: registryMeta,
256
+ runs: snapshotPluginRuns(pluginRuns),
257
+ structureFp,
258
+ });
259
+ const presentations = {};
260
+ const entityIdsWithPlugins = new Set();
261
+ for (const ov of pluginOverlays) {
262
+ if (typeof ov.entityId === "string" && ov.entityId) {
263
+ entityIdsWithPlugins.add(ov.entityId);
264
+ }
265
+ }
266
+ for (const entityId of entityIdsWithPlugins) {
267
+ const items = buildEntityPresentations({
268
+ pluginOverlays,
269
+ entityId,
270
+ registry: registryMeta,
271
+ });
272
+ if (items.length > 0) {
273
+ presentations[entityId] = items;
274
+ }
275
+ }
276
+ mkdirSync(outDir, { recursive: true });
277
+ // 1. Copy pre-built static Next.js bundle (`apps/web/out`) if available
278
+ const uiDir = resolveBundledUiDir(options.uiDir);
279
+ let copiedStaticApp = false;
280
+ if (uiDir && resolve(uiDir) !== resolve(outDir)) {
281
+ cpSync(uiDir, outDir, { recursive: true });
282
+ copiedStaticApp = true;
283
+ const indexHtmlPath = join(outDir, "index.html");
284
+ if (existsSync(indexHtmlPath)) {
285
+ const currentHtml = readFileSync(indexHtmlPath, "utf-8");
286
+ writeFileSync(indexHtmlPath, injectSnapshotScriptIntoHtml(currentHtml), "utf-8");
287
+ }
288
+ }
289
+ // 2. Write static /api/* endpoints for static hosts & fetch compatibility
290
+ writeJsonArtifact(join(outDir, "api", "layout.json"), normalLayout);
291
+ writeJsonArtifact(join(outDir, "api", "layout", "index.json"), normalLayout);
292
+ writeJsonArtifact(join(outDir, "api", "layout-diff.json"), diffLayout);
293
+ writeJsonArtifact(join(outDir, "api", "layout", "fingerprint"), fingerprintPayload);
294
+ writeJsonArtifact(join(outDir, "api", "layout", "fingerprint.json"), fingerprintPayload);
295
+ writeJsonArtifact(join(outDir, "api", "graph"), graphPayload);
296
+ writeJsonArtifact(join(outDir, "api", "graph.json"), graphPayload);
297
+ writeJsonArtifact(join(outDir, "api", "view"), activeViewPayload);
298
+ writeJsonArtifact(join(outDir, "api", "view.json"), activeViewPayload);
299
+ writeJsonArtifact(join(outDir, "api", "rules"), rulesConfig);
300
+ writeJsonArtifact(join(outDir, "api", "rules.json"), rulesConfig);
301
+ writeJsonArtifact(join(outDir, "api", "overlays"), overlays);
302
+ writeJsonArtifact(join(outDir, "api", "overlays.json"), overlays);
303
+ writeJsonArtifact(join(outDir, "api", "plugins"), pluginsOverview);
304
+ writeJsonArtifact(join(outDir, "api", "plugins.json"), pluginsOverview);
305
+ // 3. Write chomp-snapshot.json & chomp-snapshot.js (0ms window.__CHOMP_STATIC_SNAPSHOT__)
306
+ const snapshotPayload = {
307
+ version: 1,
308
+ exportedAt: new Date().toISOString(),
309
+ layout: normalLayout,
310
+ diffLayout,
311
+ fingerprint: fingerprintPayload,
312
+ graph: graphPayload,
313
+ view: activeViewPayload,
314
+ rules: rulesConfig,
315
+ overlays,
316
+ plugins: pluginsOverview,
317
+ presentations,
318
+ };
319
+ const snapshotJsonPath = join(outDir, "chomp-snapshot.json");
320
+ const snapshotJsPath = join(outDir, "chomp-snapshot.js");
321
+ writeJsonArtifact(snapshotJsonPath, snapshotPayload);
322
+ const safeJsLiteral = JSON.stringify(snapshotPayload).replace(/<\//g, "<\\/");
323
+ writeFileSync(snapshotJsPath, `window.__CHOMP_STATIC_SNAPSHOT__ = ${safeJsLiteral};\n`, "utf-8");
324
+ if (!options.quiet) {
325
+ console.log(`\n ${ansi.green("✓")} ${ansi.bold("Chomp static bundle exported")} to ${ansi.yellowBold(outDir)}`);
326
+ console.log(` ${ansi.dim("Repository:")} ${resolvedRepoName} ${ansi.dim("·")} ${ansi.dim("Nodes:")} ${normalLayout.nodes.length} ${ansi.dim("·")} ${ansi.dim("UI Shell:")} ${copiedStaticApp ? "bundled" : "data-only (build @chomp/web to include HTML shell)"}\n`);
327
+ }
328
+ return {
329
+ repoId: resolvedRepoId,
330
+ repoName: resolvedRepoName,
331
+ repoPath,
332
+ outDir,
333
+ copiedStaticApp,
334
+ normalNodeCount: normalLayout.nodes.length,
335
+ diffNodeCount: diffLayout.nodes.length,
336
+ snapshotJsPath,
337
+ snapshotJsonPath,
338
+ };
339
+ }
340
+ export function registerExportCommand(program) {
341
+ program
342
+ .command("export [path]")
343
+ .description("Export a zero-backend static HTML/JS + JSON representation bundle for GitHub Pages, S3, or CI artifacts")
344
+ .option("-o, --out <dir>", "Output directory for the exported static bundle (default: <path>/chomp-export)")
345
+ .option("--db <path>", "Path to SQLite database file (default: <path>/.chomp/graph.db)")
346
+ .option("--ui-dir <dir>", "Optional pre-built Next.js static export directory (defaults to apps/web/out)")
347
+ .option("--force-analyze", "Force re-extraction before exporting even if graph.db matches HEAD", false)
348
+ .option("--skip-analyze", "Skip automatic AST extraction refresh check", false)
349
+ .option("-q, --quiet", "Suppress console output", false)
350
+ .option("--cloud-url <url>", "Stateless Cloudflare Layout Worker URL (optional)")
351
+ .action(async (inputPath, options) => {
352
+ const baseDir = process.env.INIT_CWD ?? process.cwd();
353
+ const { targetPath } = resolveDefaultCliTarget(inputPath, baseDir, true);
354
+ await runExport(targetPath, options);
355
+ });
356
+ }
@@ -0,0 +1,19 @@
1
+ /**
2
+ * @fileoverview CLI command implementation for evaluating structural extraction health.
3
+ *
4
+ * The `health` command runs deterministic AST extraction against a target repository
5
+ * and calculates four key structural health metrics:
6
+ * 1. Connectivity Rate: Resolvability of cross-entity structural relationships.
7
+ * 2. Entity Type Coverage: Proportion of entities with identified concrete types.
8
+ * 3. Parent Coverage: Proportion of contracts attached to parent boundaries.
9
+ * 4. Scope Purity: Proportion of entities belonging to user/application scope.
10
+ *
11
+ * @module @getchomp/cli/commands/health
12
+ */
13
+ import { Command } from "commander";
14
+ /**
15
+ * Runs the 4-metric Chomp structural health check on `targetPath` and prints results.
16
+ * Returns `true` if all metrics pass, `false` otherwise.
17
+ */
18
+ export declare function runHealthCheck(targetPath: string): boolean;
19
+ export declare function registerHealthCommand(program: Command): void;
@@ -0,0 +1,259 @@
1
+ /**
2
+ * @fileoverview CLI command implementation for evaluating structural extraction health.
3
+ *
4
+ * The `health` command runs deterministic AST extraction against a target repository
5
+ * and calculates four key structural health metrics:
6
+ * 1. Connectivity Rate: Resolvability of cross-entity structural relationships.
7
+ * 2. Entity Type Coverage: Proportion of entities with identified concrete types.
8
+ * 3. Parent Coverage: Proportion of contracts attached to parent boundaries.
9
+ * 4. Scope Purity: Proportion of entities belonging to user/application scope.
10
+ *
11
+ * @module @getchomp/cli/commands/health
12
+ */
13
+ import { existsSync, statSync } from "node:fs";
14
+ import { CORE_EXTRACTOR_VERSION, analyzeTarget, auditFrameworkCoverage, computeStructuralHealthMetrics, } from "@getchomp/core";
15
+ import { applyActivePluginProjections } from "@getchomp/mcp";
16
+ import { getGitInfo, resolveRepoName } from "../utils/git.js";
17
+ import { loadExcludeWorkspaces, printFrameworkWarnings, printUnregisteredShapeHint, } from "../utils/branding.js";
18
+ import { resolveDefaultCliTarget } from "../utils/masterContext.js";
19
+ /**
20
+ * Runs the 4-metric Chomp structural health check on `targetPath` and prints results.
21
+ * Returns `true` if all metrics pass, `false` otherwise.
22
+ */
23
+ export function runHealthCheck(targetPath) {
24
+ const { commitSha } = getGitInfo(targetPath);
25
+ const excludeWorkspaces = loadExcludeWorkspaces(targetPath);
26
+ console.log(`Analyzing repository: ${targetPath}...`);
27
+ const rawGraph = analyzeTarget(targetPath, CORE_EXTRACTOR_VERSION, commitSha, excludeWorkspaces);
28
+ const graph = applyActivePluginProjections(rawGraph, {
29
+ repoPath: targetPath,
30
+ });
31
+ const shimmedEdgeCount = graph.edges.filter((e) => e.metadata?.source === "USER_SHIM").length;
32
+ const allEntities = [
33
+ ...graph.nodes,
34
+ ...graph.edges,
35
+ ];
36
+ const healthMetrics = computeStructuralHealthMetrics(graph);
37
+ const { connectivityRate, rawConnectivityRate, knowableConnectivityRate, entityTypeCoverage, parentCoverage, scopePurity, callResolutionCounts, } = healthMetrics;
38
+ const unprovableCount = callResolutionCounts.unprovableFallbackCount;
39
+ console.log("\n--- Map Health Metrics ---\n");
40
+ const metrics = [
41
+ {
42
+ Metric: "Wired calls",
43
+ Value: `${connectivityRate.toFixed(1)}%`,
44
+ Target: ">80%",
45
+ Status: connectivityRate >= 80 ? "✅ PASS" : "❌ FAIL",
46
+ },
47
+ {
48
+ Metric: "Node classification",
49
+ Value: `${entityTypeCoverage.toFixed(1)}%`,
50
+ Target: "100%",
51
+ Status: entityTypeCoverage === 100 ? "✅ PASS" : "❌ FAIL",
52
+ },
53
+ {
54
+ Metric: "Package & class ownership",
55
+ Value: `${parentCoverage.toFixed(1)}%`,
56
+ Target: "100%",
57
+ Status: parentCoverage === 100 ? "✅ PASS" : "❌ FAIL",
58
+ },
59
+ {
60
+ Metric: "Scope isolation",
61
+ Value: `${scopePurity.toFixed(1)}%`,
62
+ Target: ">95%",
63
+ Status: scopePurity >= 95 ? "✅ PASS" : "❌ FAIL",
64
+ },
65
+ ];
66
+ console.table(metrics);
67
+ console.log("\n--- Informational Counts ---\n");
68
+ const callCount = graph.edges.filter((r) => r.entityType === "CALL").length;
69
+ const rendersCount = graph.edges.filter((r) => r.entityType === "RENDERS").length;
70
+ const coverage = auditFrameworkCoverage(targetPath, graph, excludeWorkspaces);
71
+ const incomingTargetIds = new Set();
72
+ for (const edge of graph.edges) {
73
+ if (edge.targetId)
74
+ incomingTargetIds.add(edge.targetId);
75
+ }
76
+ const ingressEntityTypes = new Set([
77
+ "API_ENDPOINT",
78
+ "HTTP_ENDPOINT",
79
+ "HTTP_ROUTE",
80
+ "NEXTJS_PAGE",
81
+ "NEXTJS_LAYOUT",
82
+ "NEXTJS_MIDDLEWARE",
83
+ "SERVER_ACTION",
84
+ "EVENT_LISTENER",
85
+ "MCP_TOOL",
86
+ "PAYLOAD_ENDPOINT",
87
+ "PAYLOAD_JOB",
88
+ "PAYLOAD_HOOK",
89
+ ]);
90
+ const nonExecutableEntityTypes = new Set([
91
+ "EXPORTED_TYPE",
92
+ "TYPE_DEFINITION",
93
+ "DB_SCHEMA",
94
+ "VALIDATOR_SCHEMA",
95
+ "COLLECTION_CONFIG",
96
+ "SERVER_GUARD",
97
+ "ROUTE_CONFIG",
98
+ "NEXTJS_ROUTE_CONFIG",
99
+ "METADATA_EXPORT",
100
+ "NEXTJS_METADATA",
101
+ "EXPRESS_ROUTE_PARAM",
102
+ ]);
103
+ const orphanContracts = graph.nodes.filter((n) => n.type === "CONTRACT" &&
104
+ (n.scope ?? "USER") === "USER" &&
105
+ !nonExecutableEntityTypes.has(n.entityType) &&
106
+ !ingressEntityTypes.has(n.entityType) &&
107
+ !incomingTargetIds.has(n.id));
108
+ const unlinkedImportedOrphans = orphanContracts.filter((n) => {
109
+ const inc = Array.isArray(n.metadata?.unresolvedIncoming)
110
+ ? n.metadata.unresolvedIncoming
111
+ : [];
112
+ return inc.some((r) => r?.reason !== "imported-but-never-invoked");
113
+ });
114
+ const importedNeverInvokedOrphans = orphanContracts.filter((n) => {
115
+ const inc = Array.isArray(n.metadata?.unresolvedIncoming)
116
+ ? n.metadata.unresolvedIncoming
117
+ : [];
118
+ return (inc.length > 0 &&
119
+ inc.every((r) => r?.reason === "imported-but-never-invoked"));
120
+ });
121
+ const unreferencedExportOrphans = orphanContracts.filter((n) => {
122
+ const inc = Array.isArray(n.metadata?.unresolvedIncoming)
123
+ ? n.metadata.unresolvedIncoming
124
+ : [];
125
+ return inc.length === 0;
126
+ });
127
+ const counts = [
128
+ { Entity: "Function & method calls", Count: callCount },
129
+ { Entity: "Component renders", Count: rendersCount },
130
+ ...(shimmedEdgeCount > 0
131
+ ? [{ Entity: "Bridges active (chomp_local_shims)", Count: shimmedEdgeCount }]
132
+ : []),
133
+ { Entity: "Dynamic calls (excluded from gate)", Count: unprovableCount },
134
+ {
135
+ Entity: "Raw call resolution (all edges)",
136
+ Count: `${rawConnectivityRate.toFixed(1)}%`,
137
+ },
138
+ {
139
+ Entity: "Actionable call coverage",
140
+ Count: `${knowableConnectivityRate.toFixed(1)}%`,
141
+ },
142
+ {
143
+ Entity: "Wired calls",
144
+ Count: callResolutionCounts.resolvedCount,
145
+ },
146
+ {
147
+ Entity: "? Actionable unresolved calls",
148
+ Count: callResolutionCounts.knowableGapCount,
149
+ },
150
+ {
151
+ Entity: "Dynamic boundary calls",
152
+ Count: callResolutionCounts.dynamicBoundaryCount,
153
+ },
154
+ {
155
+ Entity: "Built-in / platform calls",
156
+ Count: callResolutionCounts.platformPrimitiveCount,
157
+ },
158
+ {
159
+ Entity: "Uncalled exports (unlinked import)",
160
+ Count: unlinkedImportedOrphans.length,
161
+ },
162
+ {
163
+ Entity: "Uncalled exports (imported, never called)",
164
+ Count: importedNeverInvokedOrphans.length,
165
+ },
166
+ {
167
+ Entity: "Uncalled exports (unreferenced)",
168
+ Count: unreferencedExportOrphans.length,
169
+ },
170
+ {
171
+ Entity: "Unmapped files (0 extracted nodes)",
172
+ Count: coverage.darkFiles.length,
173
+ },
174
+ {
175
+ Entity: "Packages & boundaries",
176
+ Count: graph.nodes.filter((n) => n.type === "BOUNDARY").length,
177
+ },
178
+ {
179
+ Entity: "Callable nodes",
180
+ Count: graph.nodes.filter((n) => n.type === "CONTRACT").length,
181
+ },
182
+ { Entity: "Connections", Count: graph.edges.length },
183
+ {
184
+ Entity: "External calls",
185
+ Count: graph.nodes.filter((n) => n.type === "OPEN_CONNECTOR").length,
186
+ },
187
+ { Entity: "Total mapped items", Count: allEntities.length },
188
+ ];
189
+ console.table(counts);
190
+ const unresolvedImportEdges = graph.edges.filter((e) => !e.targetId &&
191
+ (e.entityType === "CALL" || e.entityType === "RENDERS") &&
192
+ typeof e.metadata?.unresolvedReason === "string");
193
+ if (unresolvedImportEdges.length > 0 ||
194
+ unlinkedImportedOrphans.length > 0 ||
195
+ importedNeverInvokedOrphans.length > 0) {
196
+ console.log("\n--- Unresolved Connections & Uncalled Diagnostics ---\n");
197
+ const diagRows = [];
198
+ for (const edge of unresolvedImportEdges.slice(0, 15)) {
199
+ const ev = Array.isArray(edge.evidence)
200
+ ? edge.evidence.find((item) => item?.evidenceRole === "syntax-call") ?? edge.evidence[0]
201
+ : edge.evidence;
202
+ diagRows.push({
203
+ Kind: `Unresolved ${edge.entityType}`,
204
+ Entity: edge.name,
205
+ PeerOrSymbol: `${edge.metadata?.importSpecifier ?? "?"} :: ${edge.metadata?.targetSymbol ?? "?"}`,
206
+ Location: ev?.filePath ? `${ev.filePath}:${ev.lineNumber ?? 1}` : "unknown",
207
+ Reason: String(edge.metadata?.unresolvedReason ?? "unresolved-target"),
208
+ });
209
+ }
210
+ for (const orphan of [...unlinkedImportedOrphans, ...importedNeverInvokedOrphans].slice(0, 15)) {
211
+ const inc = Array.isArray(orphan.metadata?.unresolvedIncoming)
212
+ ? orphan.metadata.unresolvedIncoming
213
+ : [];
214
+ for (const ref of inc.slice(0, 3)) {
215
+ diagRows.push({
216
+ Kind: "Orphan Expected Caller",
217
+ Entity: orphan.name,
218
+ PeerOrSymbol: `${ref.callerName} [${ref.usageKind}]`,
219
+ Location: `${ref.filePath}:${ref.lineNumber}`,
220
+ Reason: String(ref.reason),
221
+ });
222
+ }
223
+ }
224
+ if (diagRows.length > 0) {
225
+ console.table(diagRows);
226
+ }
227
+ }
228
+ if (coverage.warnings.length > 0) {
229
+ console.log("");
230
+ printFrameworkWarnings(coverage.warnings);
231
+ }
232
+ printUnregisteredShapeHint(graph, resolveRepoName(targetPath), coverage.darkFiles);
233
+ const allPass = metrics.every((m) => m.Status === "✅ PASS");
234
+ if (!allPass) {
235
+ console.error("\nHealth check failed: One or more metrics did not meet the target.");
236
+ }
237
+ else {
238
+ console.log("\nHealth check passed! Repository graph is structurally sound.");
239
+ }
240
+ return allPass;
241
+ }
242
+ export function registerHealthCommand(program) {
243
+ program
244
+ .command("health [path]")
245
+ .description("Compute extraction health metrics for a repository (defaults to current directory)")
246
+ .option("--repo <path>", "Path to a directory to analyze (alias for [path])")
247
+ .action((inputPath, options) => {
248
+ const baseDir = process.env.INIT_CWD ?? process.cwd();
249
+ const { targetPath } = resolveDefaultCliTarget(options.repo ?? inputPath, baseDir);
250
+ if (!existsSync(targetPath) || !statSync(targetPath).isDirectory()) {
251
+ console.error(`Error: Target path ${targetPath} is not a valid directory.`);
252
+ process.exit(1);
253
+ }
254
+ const allPass = runHealthCheck(targetPath);
255
+ if (!allPass) {
256
+ process.exit(1);
257
+ }
258
+ });
259
+ }
@@ -0,0 +1,40 @@
1
+ import { Command } from "commander";
2
+ export declare const HARNESS_TEXT: string;
3
+ export declare const CHOMP_HOOK_BLOCK: string;
4
+ export declare function installGitHooks(repoRoot: string): {
5
+ mode: "husky" | "git-hooks" | "none";
6
+ files: string[];
7
+ };
8
+ export declare const KIRO_AUTO_APPROVE_TOOLS: readonly ["chomp_get_nodes", "chomp_get_edges", "chomp_get_diff", "chomp_create_view", "chomp_audit_health", "chomp_find_redundancies", "chomp_check_boundaries", "chomp_get_blast_radius", "chomp_get_conventions", "chomp_audit_design_system", "chomp_diff_design_system"];
9
+ export declare const KIRO_STEALTH_EXCLUDE_ENTRIES: readonly [".kiro/settings/mcp.json", ".kiro/steering/chomp-architecture.md", ".kiro/hooks/chomp-sync.kiro.hook", ".kiro/powers/chomp/"];
10
+ export interface AgentIntegrationSpec {
11
+ id: "cursor" | "claude" | "antigravity" | "windsurf" | "kiro";
12
+ label: string;
13
+ hint: string;
14
+ detected: boolean;
15
+ ruleFile: string;
16
+ mcpConfigPath?: string;
17
+ }
18
+ export declare function detectAgentIntegrations(repoRoot: string, env?: NodeJS.ProcessEnv): AgentIntegrationSpec[];
19
+ export declare function upsertMcpServerConfig(mcpJsonPath: string, repoRoot: string, options?: {
20
+ kiro?: boolean;
21
+ }): boolean;
22
+ export declare function installKiroIntegration(repoRoot: string, options?: {
23
+ stealth?: boolean;
24
+ }): {
25
+ mcpUpdated: boolean;
26
+ steeringUpdated: boolean;
27
+ hookUpdated: boolean;
28
+ powerUpdated: boolean;
29
+ };
30
+ export interface InitWizardOptions {
31
+ yes?: boolean;
32
+ ui?: boolean;
33
+ port?: string;
34
+ logo?: boolean;
35
+ dryRun?: boolean;
36
+ sandbox?: boolean;
37
+ stealth?: boolean;
38
+ }
39
+ export declare function runInitWizard(inputPath: string | undefined, options?: InitWizardOptions): Promise<void>;
40
+ export declare function registerInitCommand(program: Command): void;