@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
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Chomp
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,40 @@
|
|
|
1
|
-
#
|
|
1
|
+
# `@getchomp/cli`
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
**Chomp CLI** — The live structural map of your TypeScript & JavaScript codebase for humans and AI coding agents.
|
|
4
|
+
|
|
5
|
+
- **Global CLI, Per-Project Context:** Install `@getchomp/cli` once globally (`npm install -g @getchomp/cli`) and initialize per-project maps (`.chomp/graph.db`) in any repository without touching `package.json`.
|
|
6
|
+
- **100% Local Source Privacy:** AST parsing, SQLite storage, and MCP agent queries run locally on `127.0.0.1` — customer source code, file paths, and symbol names never leave your machine.
|
|
7
|
+
|
|
8
|
+
## Quick Start
|
|
9
|
+
|
|
10
|
+
```bash
|
|
11
|
+
# Install globally once
|
|
12
|
+
npm install -g @getchomp/cli
|
|
13
|
+
|
|
14
|
+
# Set up Chomp in any repository (creates .chomp/graph.db & connects your AI agent)
|
|
15
|
+
chomp init
|
|
16
|
+
|
|
17
|
+
# Launch Chomp Map in your browser
|
|
18
|
+
chomp ui
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
Or run directly with `npx`:
|
|
22
|
+
|
|
23
|
+
```bash
|
|
24
|
+
npx @getchomp/cli init && npx @getchomp/cli ui
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
## Core Commands
|
|
28
|
+
|
|
29
|
+
- `chomp init [--stealth]` — Analyze your repo, wire MCP & Map-First rules into Cursor, Claude Code, Kiro, Windsurf, or Antigravity, and configure background Git sync hooks.
|
|
30
|
+
- `chomp ui [--port 5555]` — Start the local `127.0.0.1` loopback bridge and open Chomp Map (`https://app.getchomp.dev`).
|
|
31
|
+
- `chomp analyze [path]` — Refresh `.chomp/graph.db` and seed branch comparison caches.
|
|
32
|
+
- `chomp connect [target]` — Switch the active repository for global MCP and Chomp Map.
|
|
33
|
+
- `chomp health [path]` — Run structural completeness and connectivity diagnostics.
|
|
34
|
+
- `chomp plugin run <name>` — Run built-in or workspace plugins (`design-system`, `local-shims`, `enrich-nodes`).
|
|
35
|
+
- `chomp export [path]` — Export a self-contained static map snapshot.
|
|
36
|
+
- `chomp uninstall [path]` — Cleanly remove `.chomp/`, agent harness blocks, MCP entries, and Git hooks with zero residue.
|
|
37
|
+
|
|
38
|
+
## Documentation
|
|
39
|
+
|
|
40
|
+
See [https://getchomp.dev/docs](https://getchomp.dev/docs).
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @fileoverview CLI command implementation for deterministic AST analysis and representation graph generation.
|
|
3
|
+
*
|
|
4
|
+
* The `analyze` command parses a given TypeScript or JavaScript source file or directory,
|
|
5
|
+
* extracts structural nodes (Boundaries, Contracts, Open Connectors) and edges (Relationships),
|
|
6
|
+
* persists the resulting Representation Graph into an SQLite database, and prints
|
|
7
|
+
* a concise structural Bite Report (or a full evidence table when `--verbose` is passed).
|
|
8
|
+
*
|
|
9
|
+
* @module @getchomp/cli/commands/analyze
|
|
10
|
+
*/
|
|
11
|
+
import { Command } from "commander";
|
|
12
|
+
import { type RepresentationGraph } from "@getchomp/core";
|
|
13
|
+
export interface RunAnalyzeOptions {
|
|
14
|
+
db?: string;
|
|
15
|
+
verbose?: boolean;
|
|
16
|
+
quiet?: boolean;
|
|
17
|
+
animateBanner?: boolean;
|
|
18
|
+
plugins?: boolean;
|
|
19
|
+
noPlugins?: boolean;
|
|
20
|
+
verifyPorts?: boolean;
|
|
21
|
+
}
|
|
22
|
+
export interface PluginRunFailureSummary {
|
|
23
|
+
pluginName: string;
|
|
24
|
+
error: string;
|
|
25
|
+
}
|
|
26
|
+
export interface PluginRunWarningSummary {
|
|
27
|
+
pluginName: string;
|
|
28
|
+
warnings: string[];
|
|
29
|
+
}
|
|
30
|
+
export interface RunAnalyzeResult {
|
|
31
|
+
repoId: string;
|
|
32
|
+
repoName: string;
|
|
33
|
+
repoPath: string;
|
|
34
|
+
dbPath: string;
|
|
35
|
+
commitSha?: string;
|
|
36
|
+
branchName?: string;
|
|
37
|
+
durationMs: number;
|
|
38
|
+
graph: RepresentationGraph;
|
|
39
|
+
pluginOverlayCount?: number;
|
|
40
|
+
pluginFailures?: PluginRunFailureSummary[];
|
|
41
|
+
pluginWarnings?: PluginRunWarningSummary[];
|
|
42
|
+
portHydratedCount?: number;
|
|
43
|
+
portDiagnosticCount?: number;
|
|
44
|
+
}
|
|
45
|
+
/**
|
|
46
|
+
* Runs deterministic AST extraction on `targetPath` and persists the RepresentationGraph to `.chomp/graph.db`.
|
|
47
|
+
*/
|
|
48
|
+
export declare function runAnalyze(targetPath: string, options?: RunAnalyzeOptions): Promise<RunAnalyzeResult>;
|
|
49
|
+
export declare function registerAnalyzeCommand(program: Command): void;
|
|
@@ -0,0 +1,280 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @fileoverview CLI command implementation for deterministic AST analysis and representation graph generation.
|
|
3
|
+
*
|
|
4
|
+
* The `analyze` command parses a given TypeScript or JavaScript source file or directory,
|
|
5
|
+
* extracts structural nodes (Boundaries, Contracts, Open Connectors) and edges (Relationships),
|
|
6
|
+
* persists the resulting Representation Graph into an SQLite database, and prints
|
|
7
|
+
* a concise structural Bite Report (or a full evidence table when `--verbose` is passed).
|
|
8
|
+
*
|
|
9
|
+
* @module @getchomp/cli/commands/analyze
|
|
10
|
+
*/
|
|
11
|
+
import { existsSync, statSync, mkdirSync, writeFileSync } from "node:fs";
|
|
12
|
+
import { execFileSync } from "node:child_process";
|
|
13
|
+
import { basename, dirname, resolve } from "node:path";
|
|
14
|
+
import { CORE_EXTRACTOR_VERSION, analyzeTarget } from "@getchomp/core";
|
|
15
|
+
import { createSQLiteStorage } from "@getchomp/db";
|
|
16
|
+
import { runAllChompPlugins } from "@getchomp/mcp";
|
|
17
|
+
import { getGitInfo, resolveRepoName } from "../utils/git.js";
|
|
18
|
+
import { hydrateRepositoryPortValves } from "../ports/portHydrator.js";
|
|
19
|
+
import { seedRefGraphDiskCache } from "../server/graphLayoutState.js";
|
|
20
|
+
import { ansi, loadExcludeWorkspaces, runChompExtractionWithAnimation, } from "../utils/branding.js";
|
|
21
|
+
import { ensureGitExcludeHasChomp, resolveDefaultCliTarget, setActiveChompTarget, } from "../utils/masterContext.js";
|
|
22
|
+
/**
|
|
23
|
+
* Runs deterministic AST extraction on `targetPath` and persists the RepresentationGraph to `.chomp/graph.db`.
|
|
24
|
+
*/
|
|
25
|
+
export async function runAnalyze(targetPath, options = {}) {
|
|
26
|
+
const stat = statSync(targetPath);
|
|
27
|
+
const isDir = stat.isDirectory();
|
|
28
|
+
const repoPath = isDir ? targetPath : dirname(targetPath);
|
|
29
|
+
const repoName = resolveRepoName(repoPath);
|
|
30
|
+
const repoId = repoName.toLowerCase().replace(/[^a-z0-9_-]/g, "_");
|
|
31
|
+
const { commitSha, branchName, commitMessage } = getGitInfo(repoPath);
|
|
32
|
+
const excludeWorkspaces = loadExcludeWorkspaces(repoPath);
|
|
33
|
+
const defaultDbDir = resolve(repoPath, ".chomp");
|
|
34
|
+
const baseDir = process.env.INIT_CWD ?? process.cwd();
|
|
35
|
+
const dbPath = options.db
|
|
36
|
+
? resolve(baseDir, options.db)
|
|
37
|
+
: resolve(defaultDbDir, "graph.db");
|
|
38
|
+
const targetDbDir = dirname(dbPath);
|
|
39
|
+
if (!existsSync(targetDbDir)) {
|
|
40
|
+
mkdirSync(targetDbDir, { recursive: true });
|
|
41
|
+
}
|
|
42
|
+
if (!options.db) {
|
|
43
|
+
ensureGitExcludeHasChomp(repoPath);
|
|
44
|
+
}
|
|
45
|
+
if (!options.quiet && !options.db) {
|
|
46
|
+
setActiveChompTarget(repoPath);
|
|
47
|
+
}
|
|
48
|
+
const inspectWorkingTreeState = () => {
|
|
49
|
+
if (!existsSync(resolve(repoPath, ".git"))) {
|
|
50
|
+
return { workingTreeDirty: false, dirtyFiles: [] };
|
|
51
|
+
}
|
|
52
|
+
const env = { ...process.env };
|
|
53
|
+
delete env.GIT_DIR;
|
|
54
|
+
delete env.GIT_WORK_TREE;
|
|
55
|
+
delete env.GIT_INDEX_FILE;
|
|
56
|
+
delete env.GIT_OBJECT_DIRECTORY;
|
|
57
|
+
delete env.GIT_ALTERNATE_OBJECT_DIRECTORIES;
|
|
58
|
+
delete env.GIT_CEILING_DIRECTORIES;
|
|
59
|
+
delete env.GIT_COMMON_DIR;
|
|
60
|
+
delete env.GIT_PREFIX;
|
|
61
|
+
try {
|
|
62
|
+
const out = execFileSync("git", ["-C", repoPath, "status", "--porcelain", "--untracked-files=normal"], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], env });
|
|
63
|
+
const dirtyFiles = out
|
|
64
|
+
.split(/\r?\n/)
|
|
65
|
+
.filter((l) => l.length > 3)
|
|
66
|
+
.map((l) => l.slice(3).trim())
|
|
67
|
+
.filter((p) => Boolean(p) && !p.startsWith(".chomp/") && p !== ".chomp");
|
|
68
|
+
return {
|
|
69
|
+
workingTreeDirty: dirtyFiles.length > 0,
|
|
70
|
+
dirtyFiles: dirtyFiles.slice(0, 50),
|
|
71
|
+
};
|
|
72
|
+
}
|
|
73
|
+
catch {
|
|
74
|
+
return { workingTreeDirty: false, dirtyFiles: [] };
|
|
75
|
+
}
|
|
76
|
+
};
|
|
77
|
+
const executeExtractionAndSave = async () => {
|
|
78
|
+
const t0 = Date.now();
|
|
79
|
+
const graph = analyzeTarget(targetPath, CORE_EXTRACTOR_VERSION, commitSha, excludeWorkspaces);
|
|
80
|
+
const storage = createSQLiteStorage(dbPath);
|
|
81
|
+
const repoInfo = {
|
|
82
|
+
id: repoId,
|
|
83
|
+
name: repoName,
|
|
84
|
+
path: repoPath,
|
|
85
|
+
extractorVersion: graph.extractorVersion,
|
|
86
|
+
commitSha,
|
|
87
|
+
branchName,
|
|
88
|
+
};
|
|
89
|
+
await storage.saveRepresentationGraph(repoInfo, graph);
|
|
90
|
+
const savedGraph = (await storage.getRepresentationGraph(repoId)) ?? graph;
|
|
91
|
+
if (!options.db || basename(dirname(dbPath)) === ".chomp") {
|
|
92
|
+
try {
|
|
93
|
+
const treeState = inspectWorkingTreeState();
|
|
94
|
+
writeFileSync(resolve(dirname(dbPath), "base_snapshot.json"), JSON.stringify({
|
|
95
|
+
commitSha: commitSha ?? null,
|
|
96
|
+
analyzedAt: savedGraph.analyzedAt,
|
|
97
|
+
extractorVersion: savedGraph.extractorVersion,
|
|
98
|
+
workingTreeDirty: treeState.workingTreeDirty,
|
|
99
|
+
dirtyFiles: treeState.dirtyFiles,
|
|
100
|
+
}, null, 2) + "\n", "utf8");
|
|
101
|
+
if (isDir && !treeState.workingTreeDirty && commitSha) {
|
|
102
|
+
seedRefGraphDiskCache({
|
|
103
|
+
repoPath,
|
|
104
|
+
dbPath,
|
|
105
|
+
fullCommitSha: commitSha,
|
|
106
|
+
branchName,
|
|
107
|
+
commitMessage,
|
|
108
|
+
graph: savedGraph,
|
|
109
|
+
});
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
catch {
|
|
113
|
+
// Non-fatal if snapshot metadata cannot be written
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
let pluginOverlayCount = 0;
|
|
117
|
+
const pluginFailures = [];
|
|
118
|
+
const pluginWarnings = [];
|
|
119
|
+
if (options.plugins !== false && !options.noPlugins) {
|
|
120
|
+
try {
|
|
121
|
+
const pluginResults = await runAllChompPlugins({
|
|
122
|
+
repoPath,
|
|
123
|
+
repoId,
|
|
124
|
+
repoName,
|
|
125
|
+
storage,
|
|
126
|
+
graph: savedGraph,
|
|
127
|
+
excludeWorkspaces,
|
|
128
|
+
persist: true,
|
|
129
|
+
continueOnError: true,
|
|
130
|
+
onPluginError: (plugin, err) => {
|
|
131
|
+
pluginFailures.push({
|
|
132
|
+
pluginName: plugin.name,
|
|
133
|
+
error: err.message,
|
|
134
|
+
});
|
|
135
|
+
},
|
|
136
|
+
});
|
|
137
|
+
pluginOverlayCount = pluginResults.reduce((sum, r) => sum + r.overlayCount, 0);
|
|
138
|
+
for (const r of pluginResults) {
|
|
139
|
+
if (r.presentationWarnings.length > 0) {
|
|
140
|
+
pluginWarnings.push({
|
|
141
|
+
pluginName: r.pluginName,
|
|
142
|
+
warnings: r.presentationWarnings,
|
|
143
|
+
});
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
catch (err) {
|
|
148
|
+
pluginFailures.push({
|
|
149
|
+
pluginName: "plugin-runner",
|
|
150
|
+
error: String(err?.message ?? err),
|
|
151
|
+
});
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
let portHydratedCount = 0;
|
|
155
|
+
let portDiagnosticCount = 0;
|
|
156
|
+
if (options.verifyPorts) {
|
|
157
|
+
try {
|
|
158
|
+
const portRes = await hydrateRepositoryPortValves({
|
|
159
|
+
repoPath,
|
|
160
|
+
repoId,
|
|
161
|
+
storage,
|
|
162
|
+
graph: savedGraph,
|
|
163
|
+
});
|
|
164
|
+
portHydratedCount = portRes.hydratedCount;
|
|
165
|
+
portDiagnosticCount = portRes.diagnosticCount;
|
|
166
|
+
}
|
|
167
|
+
catch {
|
|
168
|
+
// Non-fatal: Layer 0 syntactic ports remain intact
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
await storage.close();
|
|
172
|
+
const durationMs = Date.now() - t0;
|
|
173
|
+
return {
|
|
174
|
+
graph: savedGraph,
|
|
175
|
+
durationMs,
|
|
176
|
+
pluginOverlayCount,
|
|
177
|
+
pluginFailures,
|
|
178
|
+
pluginWarnings,
|
|
179
|
+
portHydratedCount,
|
|
180
|
+
portDiagnosticCount,
|
|
181
|
+
};
|
|
182
|
+
};
|
|
183
|
+
let savedGraph;
|
|
184
|
+
let durationMs;
|
|
185
|
+
let pluginOverlayCount = 0;
|
|
186
|
+
let pluginFailures = [];
|
|
187
|
+
let pluginWarnings = [];
|
|
188
|
+
let portHydratedCount = 0;
|
|
189
|
+
let portDiagnosticCount = 0;
|
|
190
|
+
if (!options.quiet) {
|
|
191
|
+
const res = await runChompExtractionWithAnimation({
|
|
192
|
+
repoName,
|
|
193
|
+
repoPath,
|
|
194
|
+
dbPath,
|
|
195
|
+
excludeWorkspaces,
|
|
196
|
+
commitSha,
|
|
197
|
+
branchName,
|
|
198
|
+
executeExtraction: executeExtractionAndSave,
|
|
199
|
+
});
|
|
200
|
+
savedGraph = res.graph;
|
|
201
|
+
durationMs = res.durationMs;
|
|
202
|
+
pluginOverlayCount = res.pluginOverlayCount ?? 0;
|
|
203
|
+
pluginFailures = res.pluginFailures ?? [];
|
|
204
|
+
pluginWarnings = res.pluginWarnings ?? [];
|
|
205
|
+
portHydratedCount = res.portHydratedCount ?? 0;
|
|
206
|
+
portDiagnosticCount = res.portDiagnosticCount ?? 0;
|
|
207
|
+
for (const pf of pluginFailures) {
|
|
208
|
+
console.warn(` ${ansi.yellow("⚠")} Plugin '${pf.pluginName}' failed: ${pf.error} ${ansi.dim(`(.chomp/plugins/${pf.pluginName}/last-run.json)`)}`);
|
|
209
|
+
}
|
|
210
|
+
for (const pw of pluginWarnings) {
|
|
211
|
+
console.warn(` ${ansi.yellow("⚠")} Plugin '${pw.pluginName}' reported ${pw.warnings.length} presentation warning(s): ${pw.warnings[0]}`);
|
|
212
|
+
}
|
|
213
|
+
if (options.verbose) {
|
|
214
|
+
const allEntities = [...savedGraph.nodes, ...savedGraph.edges];
|
|
215
|
+
const summaryTable = allEntities.map((entity) => {
|
|
216
|
+
const ev = Array.isArray(entity.evidence)
|
|
217
|
+
? entity.evidence[0]
|
|
218
|
+
: entity.evidence;
|
|
219
|
+
return {
|
|
220
|
+
Type: entity.type,
|
|
221
|
+
ID: entity.id,
|
|
222
|
+
Name: entity.name,
|
|
223
|
+
File: ev?.filePath ?? "-",
|
|
224
|
+
Line: ev?.lineNumber ?? "-",
|
|
225
|
+
Snippet: ev?.snippet
|
|
226
|
+
? ev.snippet.length > 40
|
|
227
|
+
? `${ev.snippet.slice(0, 37)}...`
|
|
228
|
+
: ev.snippet
|
|
229
|
+
: "-",
|
|
230
|
+
};
|
|
231
|
+
});
|
|
232
|
+
console.table(summaryTable);
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
else {
|
|
236
|
+
const res = await executeExtractionAndSave();
|
|
237
|
+
savedGraph = res.graph;
|
|
238
|
+
durationMs = res.durationMs;
|
|
239
|
+
pluginOverlayCount = res.pluginOverlayCount ?? 0;
|
|
240
|
+
pluginFailures = res.pluginFailures ?? [];
|
|
241
|
+
pluginWarnings = res.pluginWarnings ?? [];
|
|
242
|
+
portHydratedCount = res.portHydratedCount ?? 0;
|
|
243
|
+
portDiagnosticCount = res.portDiagnosticCount ?? 0;
|
|
244
|
+
}
|
|
245
|
+
return {
|
|
246
|
+
repoId,
|
|
247
|
+
repoName,
|
|
248
|
+
repoPath,
|
|
249
|
+
dbPath,
|
|
250
|
+
commitSha,
|
|
251
|
+
branchName,
|
|
252
|
+
durationMs,
|
|
253
|
+
graph: savedGraph,
|
|
254
|
+
pluginOverlayCount,
|
|
255
|
+
...(pluginFailures.length > 0 ? { pluginFailures } : {}),
|
|
256
|
+
...(pluginWarnings.length > 0 ? { pluginWarnings } : {}),
|
|
257
|
+
...(options.verifyPorts
|
|
258
|
+
? { portHydratedCount, portDiagnosticCount }
|
|
259
|
+
: {}),
|
|
260
|
+
};
|
|
261
|
+
}
|
|
262
|
+
export function registerAnalyzeCommand(program) {
|
|
263
|
+
program
|
|
264
|
+
.command("analyze [path]")
|
|
265
|
+
.description("Analyze a TypeScript/JavaScript source file or directory (defaults to current directory)")
|
|
266
|
+
.option("--db <path>", "Path to SQLite database file (default: <path>/.chomp/graph.db)")
|
|
267
|
+
.option("-v, --verbose", "Print full entity evidence table after extraction", false)
|
|
268
|
+
.option("-q, --quiet", "Suppress console output (for git hooks)", false)
|
|
269
|
+
.option("--no-plugins", "Skip running analysis-time overlay plugins")
|
|
270
|
+
.option("--verify-ports", "Run TypeScript type-checker verification on function parameter and return types", false)
|
|
271
|
+
.action(async (inputPath, options) => {
|
|
272
|
+
const baseDir = process.env.INIT_CWD ?? process.cwd();
|
|
273
|
+
const { targetPath } = resolveDefaultCliTarget(inputPath, baseDir, !options.quiet);
|
|
274
|
+
if (!existsSync(targetPath)) {
|
|
275
|
+
console.error(`Error: Path does not exist: ${targetPath}`);
|
|
276
|
+
process.exit(1);
|
|
277
|
+
}
|
|
278
|
+
await runAnalyze(targetPath, { ...options, animateBanner: true });
|
|
279
|
+
});
|
|
280
|
+
}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @fileoverview Master Tether (`chomp connect`) command for switching the active Chomp target
|
|
3
|
+
* repository across the machine without installing `@getchomp/cli` into external `package.json` files.
|
|
4
|
+
*
|
|
5
|
+
* Updates `~/.chomp/context.json` so both the global MCP server (`chomp-server`) and the
|
|
6
|
+
* running Visualizer (`chomp ui`) immediately switch to the connected repository.
|
|
7
|
+
* Also ensures the global `~/.local/bin/chomp` and `~/.local/bin/chomp-research` shims are installed.
|
|
8
|
+
*
|
|
9
|
+
* @module @getchomp/cli/commands/connect
|
|
10
|
+
*/
|
|
11
|
+
import { Command } from "commander";
|
|
12
|
+
export declare function registerConnectCommand(program: Command): void;
|
|
@@ -0,0 +1,255 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @fileoverview Master Tether (`chomp connect`) command for switching the active Chomp target
|
|
3
|
+
* repository across the machine without installing `@getchomp/cli` into external `package.json` files.
|
|
4
|
+
*
|
|
5
|
+
* Updates `~/.chomp/context.json` so both the global MCP server (`chomp-server`) and the
|
|
6
|
+
* running Visualizer (`chomp ui`) immediately switch to the connected repository.
|
|
7
|
+
* Also ensures the global `~/.local/bin/chomp` and `~/.local/bin/chomp-research` shims are installed.
|
|
8
|
+
*
|
|
9
|
+
* @module @getchomp/cli/commands/connect
|
|
10
|
+
*/
|
|
11
|
+
import { execSync } from "node:child_process";
|
|
12
|
+
import { existsSync, mkdirSync } from "node:fs";
|
|
13
|
+
import { resolve } from "node:path";
|
|
14
|
+
import { Option } from "commander";
|
|
15
|
+
import { ansi, printChompBanner, scaffoldDesignSystemConfig } from "../utils/branding.js";
|
|
16
|
+
import { ensureGitExcludeHasChomp, getCanonicalChompMasterRoot, getChompMasterRoot, getGlobalContextPath, hasPrivateResearchLedger, installGlobalChompShims, isLinkedGitWorktree, listKnownTargetRepos, readMasterContext, resolveGitRepoRoot, resolveRepoName, setActiveChompTarget, } from "../utils/masterContext.js";
|
|
17
|
+
import { runAnalyze } from "./analyze.js";
|
|
18
|
+
import { runHealthCheck } from "./health.js";
|
|
19
|
+
import { installGitHooks, runInitWizard } from "./init.js";
|
|
20
|
+
function looksLikeGitUrlOrSlug(input) {
|
|
21
|
+
const trimmed = input.trim();
|
|
22
|
+
if (/^(https?:\/\/|git@|ssh:\/\/)/i.test(trimmed)) {
|
|
23
|
+
const clean = trimmed.replace(/\.git$/i, "").replace(/\/+$/, "");
|
|
24
|
+
const repoName = clean.split("/").pop()?.split(":").pop() || "cloned-repo";
|
|
25
|
+
return { isRemote: true, cloneUrl: trimmed, repoName };
|
|
26
|
+
}
|
|
27
|
+
if (/^gh:[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/i.test(trimmed)) {
|
|
28
|
+
const slug = trimmed.slice(3);
|
|
29
|
+
const repoName = slug.split("/")[1];
|
|
30
|
+
return {
|
|
31
|
+
isRemote: true,
|
|
32
|
+
cloneUrl: `https://github.com/${slug}.git`,
|
|
33
|
+
repoName,
|
|
34
|
+
};
|
|
35
|
+
}
|
|
36
|
+
if (/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/.test(trimmed) &&
|
|
37
|
+
!trimmed.startsWith(".") &&
|
|
38
|
+
!existsSync(resolve(process.env.INIT_CWD ?? process.cwd(), trimmed))) {
|
|
39
|
+
const repoName = trimmed.split("/")[1].replace(/\.git$/i, "");
|
|
40
|
+
return {
|
|
41
|
+
isRemote: true,
|
|
42
|
+
cloneUrl: `https://github.com/${trimmed.replace(/\.git$/i, "")}.git`,
|
|
43
|
+
repoName,
|
|
44
|
+
};
|
|
45
|
+
}
|
|
46
|
+
return { isRemote: false, cloneUrl: "", repoName: "" };
|
|
47
|
+
}
|
|
48
|
+
function resolveConnectTarget(inputTarget, baseDir) {
|
|
49
|
+
const masterRoot = getChompMasterRoot();
|
|
50
|
+
const trimmed = inputTarget.trim();
|
|
51
|
+
if (trimmed === "chomp" || trimmed === "master") {
|
|
52
|
+
return { repoPath: getCanonicalChompMasterRoot(masterRoot), freshlyCloned: false };
|
|
53
|
+
}
|
|
54
|
+
// 1. Direct local path relative to caller's working directory
|
|
55
|
+
const localCandidate = resolve(baseDir, trimmed);
|
|
56
|
+
if (existsSync(localCandidate)) {
|
|
57
|
+
return {
|
|
58
|
+
repoPath: resolveGitRepoRoot(localCandidate),
|
|
59
|
+
freshlyCloned: false,
|
|
60
|
+
};
|
|
61
|
+
}
|
|
62
|
+
// 2. Short name inside fixtures/cloned-repos/<name> or fixtures/test-repos/<name>
|
|
63
|
+
const clonedCandidate = resolve(masterRoot, "fixtures", "cloned-repos", trimmed);
|
|
64
|
+
if (existsSync(clonedCandidate)) {
|
|
65
|
+
return {
|
|
66
|
+
repoPath: resolveGitRepoRoot(clonedCandidate),
|
|
67
|
+
freshlyCloned: false,
|
|
68
|
+
};
|
|
69
|
+
}
|
|
70
|
+
const testRepoCandidate = resolve(masterRoot, "fixtures", "test-repos", trimmed);
|
|
71
|
+
if (existsSync(testRepoCandidate)) {
|
|
72
|
+
return {
|
|
73
|
+
repoPath: testRepoCandidate,
|
|
74
|
+
freshlyCloned: false,
|
|
75
|
+
};
|
|
76
|
+
}
|
|
77
|
+
// 3. Match against recentRepos by name or id
|
|
78
|
+
const ctx = readMasterContext();
|
|
79
|
+
const recentMatch = (ctx?.recentRepos ?? []).find((r) => r.name.toLowerCase() === trimmed.toLowerCase() ||
|
|
80
|
+
r.id.toLowerCase() === trimmed.toLowerCase());
|
|
81
|
+
if (recentMatch && existsSync(recentMatch.path)) {
|
|
82
|
+
return {
|
|
83
|
+
repoPath: recentMatch.path,
|
|
84
|
+
freshlyCloned: false,
|
|
85
|
+
};
|
|
86
|
+
}
|
|
87
|
+
// 4. Remote Git URL or GitHub owner/repo slug -> clone into fixtures/cloned-repos/<repoName>
|
|
88
|
+
const remoteSpec = looksLikeGitUrlOrSlug(trimmed);
|
|
89
|
+
if (remoteSpec.isRemote) {
|
|
90
|
+
const clonedDir = resolve(masterRoot, "fixtures", "cloned-repos", remoteSpec.repoName);
|
|
91
|
+
if (existsSync(clonedDir)) {
|
|
92
|
+
console.log(` ${ansi.green("✓")} Found existing clone at ${ansi.cyan(clonedDir)}`);
|
|
93
|
+
return { repoPath: clonedDir, freshlyCloned: false };
|
|
94
|
+
}
|
|
95
|
+
mkdirSync(resolve(masterRoot, "fixtures", "cloned-repos"), {
|
|
96
|
+
recursive: true,
|
|
97
|
+
});
|
|
98
|
+
console.log(` ${ansi.cyan("⬇")} Cloning ${ansi.bold(remoteSpec.cloneUrl)} into ${ansi.cyan(clonedDir)}...`);
|
|
99
|
+
execSync(`git clone --depth 50 "${remoteSpec.cloneUrl}" "${clonedDir}"`, {
|
|
100
|
+
stdio: "inherit",
|
|
101
|
+
});
|
|
102
|
+
return { repoPath: clonedDir, freshlyCloned: true };
|
|
103
|
+
}
|
|
104
|
+
throw new Error(hasPrivateResearchLedger()
|
|
105
|
+
? `Could not resolve target '${inputTarget}'. Pass a local path, a repo name in fixtures/cloned-repos/, 'chomp', or a Git URL / owner/repo slug.`
|
|
106
|
+
: `Could not resolve target '${inputTarget}'. Pass a local path, a connected repo name, or a Git URL / owner/repo slug.`);
|
|
107
|
+
}
|
|
108
|
+
function printMasterStatus() {
|
|
109
|
+
const shims = installGlobalChompShims();
|
|
110
|
+
const ctx = readMasterContext();
|
|
111
|
+
const known = listKnownTargetRepos();
|
|
112
|
+
console.log(`\n ${ansi.yellowBold("⚡")} ${ansi.bold("Chomp Connected Repos & Global CLI")}`);
|
|
113
|
+
console.log(` ${ansi.dim("Global CLI:")} ${ansi.cyan(shims.chompBin)}`);
|
|
114
|
+
console.log(` ${ansi.dim("Context State:")} ${ansi.cyan(getGlobalContextPath())}`);
|
|
115
|
+
if (ctx?.activeRepoPath) {
|
|
116
|
+
console.log(` ${ansi.green("●")} ${ansi.bold("Active Repo:")} ${ansi.yellowBold(ctx.activeRepoName)} ${ansi.dim(`(${ctx.activeRepoId})`)} → ${ansi.cyan(ctx.activeRepoPath)}`);
|
|
117
|
+
}
|
|
118
|
+
else {
|
|
119
|
+
console.log(` ${ansi.yellow("○")} ${ansi.bold("Active Repo:")} ${ansi.dim("None set (defaults to current workspace)")}`);
|
|
120
|
+
}
|
|
121
|
+
console.log(`\n ${ansi.bold("Known & Connected Repositories:")}`);
|
|
122
|
+
for (const repo of known) {
|
|
123
|
+
const activeBadge = repo.isActive
|
|
124
|
+
? `${ansi.green("● ACTIVE")} `
|
|
125
|
+
: ` ${ansi.dim("○")} `;
|
|
126
|
+
const dbBadge = repo.hasGraphDb
|
|
127
|
+
? ansi.green("[graph.db ready]")
|
|
128
|
+
: ansi.dim("[not analyzed]");
|
|
129
|
+
const sourceBadge = repo.source === "master"
|
|
130
|
+
? ansi.yellow("[workspace]")
|
|
131
|
+
: repo.source === "cloned-fixture"
|
|
132
|
+
? ansi.cyan("[cloned]")
|
|
133
|
+
: ansi.dim("[local]");
|
|
134
|
+
console.log(` ${activeBadge}${ansi.bold(repo.name.padEnd(20))} ${sourceBadge.padEnd(32)} ${dbBadge} ${ansi.dim(repo.path)}`);
|
|
135
|
+
}
|
|
136
|
+
console.log(`\n ${ansi.dim("Quick Commands (work from any directory on your machine):")}`);
|
|
137
|
+
console.log(` ${ansi.cyan("chomp connect .")} ${ansi.dim("Connect current directory to MCP & Chomp Map (stealth mode)")}`);
|
|
138
|
+
console.log(` ${ansi.cyan("chomp connect <name|path|url>")} ${ansi.dim("Clone/connect repo & hot-switch MCP + Chomp Map")}`);
|
|
139
|
+
console.log(` ${ansi.cyan("chomp init")} ${ansi.dim("Run the full 60s interactive setup wizard in any repo")}\n`);
|
|
140
|
+
}
|
|
141
|
+
export function registerConnectCommand(program) {
|
|
142
|
+
program
|
|
143
|
+
.command("connect [target]")
|
|
144
|
+
.description("Connect the global Chomp MCP server & Chomp Map to any local or cloned repository")
|
|
145
|
+
.option("-l, --list", "List active repo connection and known repositories", false)
|
|
146
|
+
.option("--init", "Run the full interactive 'chomp init' setup wizard on the target repository", false)
|
|
147
|
+
.option("--stealth", "Keep target repo 100% git-clean (.chomp/ hidden in .git/info/exclude; zero tracked file edits)", true)
|
|
148
|
+
.option("-a, --analyze", "Force a fresh AST extraction even if .chomp/graph.db already exists", false)
|
|
149
|
+
.option("--no-hooks", "Do not install background Git hooks (post-commit, post-merge, post-checkout) in the target repo")
|
|
150
|
+
.option("--health", "Run the 4-metric Chomp structural health check after connecting", false)
|
|
151
|
+
.addOption(new Option("-m, --measure", "Run 'chomp-research ledger pattern measure' against the connected repository")
|
|
152
|
+
.default(false)
|
|
153
|
+
.hideHelp(!hasPrivateResearchLedger()))
|
|
154
|
+
.option("-y, --yes", "Accept recommended defaults when combined with --init", false)
|
|
155
|
+
.action(async (inputTarget, options) => {
|
|
156
|
+
// Always ensure ~/.local/bin/chomp and ~/.local/bin/chomp-research are up to date
|
|
157
|
+
installGlobalChompShims();
|
|
158
|
+
const baseDir = process.env.INIT_CWD ?? process.cwd();
|
|
159
|
+
if (options.list) {
|
|
160
|
+
printMasterStatus();
|
|
161
|
+
return;
|
|
162
|
+
}
|
|
163
|
+
// If no target argument was passed:
|
|
164
|
+
// - If the user is in a directory outside the currently tethered repo, connect `.`
|
|
165
|
+
// - Otherwise, print the Master Tether status & known repos table
|
|
166
|
+
if (!inputTarget) {
|
|
167
|
+
const currentRepoRoot = resolveGitRepoRoot(baseDir);
|
|
168
|
+
const ctx = readMasterContext();
|
|
169
|
+
if (ctx?.activeRepoPath &&
|
|
170
|
+
resolve(ctx.activeRepoPath) === resolve(currentRepoRoot)) {
|
|
171
|
+
printMasterStatus();
|
|
172
|
+
return;
|
|
173
|
+
}
|
|
174
|
+
inputTarget = ".";
|
|
175
|
+
}
|
|
176
|
+
let resolved;
|
|
177
|
+
try {
|
|
178
|
+
resolved = resolveConnectTarget(inputTarget, baseDir);
|
|
179
|
+
}
|
|
180
|
+
catch (err) {
|
|
181
|
+
console.error(`\n ${ansi.red("✖")} ${err.message}\n`);
|
|
182
|
+
process.exit(1);
|
|
183
|
+
}
|
|
184
|
+
const { repoPath, freshlyCloned } = resolved;
|
|
185
|
+
const repoName = resolveRepoName(repoPath);
|
|
186
|
+
if (options.init) {
|
|
187
|
+
await runInitWizard(repoPath, {
|
|
188
|
+
yes: options.yes,
|
|
189
|
+
stealth: false,
|
|
190
|
+
});
|
|
191
|
+
return;
|
|
192
|
+
}
|
|
193
|
+
printChompBanner(`Connecting repo → ${repoName} (${repoPath})`, "open");
|
|
194
|
+
// 1. Hide .chomp/ in .git/info/exclude so the target repo stays 100% git-clean
|
|
195
|
+
const excluded = ensureGitExcludeHasChomp(repoPath);
|
|
196
|
+
if (excluded) {
|
|
197
|
+
console.log(` ${ansi.green("✓")} Added ${ansi.cyan(".chomp/")} to ${ansi.cyan(".git/info/exclude")} (stealth mode — zero .gitignore changes)`);
|
|
198
|
+
}
|
|
199
|
+
else {
|
|
200
|
+
console.log(` ${ansi.green("✓")} Verified ${ansi.cyan(".chomp/")} is ignored by Git`);
|
|
201
|
+
}
|
|
202
|
+
// 2. Install background Git hooks (post-commit, post-merge, post-checkout) inside .git/hooks
|
|
203
|
+
if (options.hooks !== false) {
|
|
204
|
+
const hookRes = installGitHooks(repoPath);
|
|
205
|
+
if (hookRes.files.length > 0) {
|
|
206
|
+
console.log(` ${ansi.green("✓")} Installed background Git sync hooks (${hookRes.files.join(", ")})`);
|
|
207
|
+
}
|
|
208
|
+
else if (hookRes.mode !== "none") {
|
|
209
|
+
console.log(` ${ansi.green("✓")} Background Git sync hooks (${hookRes.mode}) active`);
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
// 2b. Scaffold starter `designSystem` config when frontend packages are detected
|
|
213
|
+
// (writes `.chomp/plugins/design-system/config.json` in stealth mode so git stays 100% clean)
|
|
214
|
+
const dsScaffold = scaffoldDesignSystemConfig(repoPath, {
|
|
215
|
+
stealth: options.stealth !== false,
|
|
216
|
+
});
|
|
217
|
+
if (dsScaffold.written && dsScaffold.configRelPath) {
|
|
218
|
+
console.log(` ${ansi.green("✓")} Scaffolded ${ansi.cyan("designSystem")} config in ${ansi.cyan(dsScaffold.configRelPath)} (${dsScaffold.frontendPackages.join(", ")})`);
|
|
219
|
+
}
|
|
220
|
+
// 3. Extract .chomp/graph.db if missing, freshly cloned, or --analyze requested
|
|
221
|
+
const dbPath = resolve(repoPath, ".chomp", "graph.db");
|
|
222
|
+
if (!existsSync(dbPath) || freshlyCloned || options.analyze) {
|
|
223
|
+
await runAnalyze(repoPath);
|
|
224
|
+
}
|
|
225
|
+
else {
|
|
226
|
+
console.log(` ${ansi.green("✓")} Existing graph ready at ${ansi.cyan(dbPath)} ${ansi.dim("(pass --analyze to re-extract)")}`);
|
|
227
|
+
}
|
|
228
|
+
// 4. Lock Active Repo in ~/.chomp/context.json
|
|
229
|
+
const connectingWorktree = isLinkedGitWorktree(repoPath);
|
|
230
|
+
const updatedCtx = setActiveChompTarget(repoPath, { allowWorktree: true });
|
|
231
|
+
console.log(`\n ${ansi.green("⚡")} ${ansi.bold("Active Repo Connected:")} ${ansi.yellowBold(updatedCtx.activeRepoName)} ${ansi.dim(`(${updatedCtx.activeRepoId})`)}`);
|
|
232
|
+
if (connectingWorktree) {
|
|
233
|
+
console.log(` ${ansi.yellow("⚠")} ${ansi.dim("Note: connected to a linked Git worktree — running `chomp ui` from the primary checkout will still stay on the primary checkout.")}`);
|
|
234
|
+
}
|
|
235
|
+
console.log(` ${ansi.dim("•")} ${ansi.bold("MCP Server (chomp-server):")} Dynamically routed to ${ansi.cyan(dbPath)}`);
|
|
236
|
+
console.log(` ${ansi.dim("•")} ${ansi.bold("Chomp Map (chomp ui):")} Auto-switched to ${ansi.cyan(repoPath)}\n`);
|
|
237
|
+
// 5. Optional health check or pattern ledger measurement
|
|
238
|
+
if (options.health || freshlyCloned) {
|
|
239
|
+
runHealthCheck(repoPath);
|
|
240
|
+
}
|
|
241
|
+
if (options.measure) {
|
|
242
|
+
const researchBin = resolve(getChompMasterRoot(), "packages/db/node_modules/.bin/tsx");
|
|
243
|
+
const researchEntry = resolve(getChompMasterRoot(), "fixtures/research/research-cli/src/index.ts");
|
|
244
|
+
if (existsSync(researchBin) && existsSync(researchEntry)) {
|
|
245
|
+
console.log(`\n ${ansi.cyan("📊")} Running pattern ledger measurement for ${ansi.bold(repoName)}...\n`);
|
|
246
|
+
try {
|
|
247
|
+
execSync(`"${researchBin}" "${researchEntry}" ledger pattern measure --repo "${repoPath}"`, { cwd: getChompMasterRoot(), stdio: "inherit" });
|
|
248
|
+
}
|
|
249
|
+
catch {
|
|
250
|
+
// non-fatal if ledger measure exits non-zero
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
}
|
|
254
|
+
});
|
|
255
|
+
}
|