@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,654 @@
1
+ import { CORE_EXTRACTOR_VERSION, analyzeTarget } from "@getchomp/core";
2
+ import { execSync } from "node:child_process";
3
+ import { chmodSync, existsSync, mkdirSync, readFileSync, unlinkSync, writeFileSync, } from "node:fs";
4
+ import { homedir } from "node:os";
5
+ import { dirname, resolve } from "node:path";
6
+ import { ansi, confirmPrompt, detectWorkspacePackages, loadExcludeWorkspaces, multiSelectPrompt, playChompBannerAnimation, printChompBanner, printDetectedWorkspaceTable, printWelcomeMessage, runChompExtractionWithAnimation, runDiscoveryTicker, saveExcludeWorkspaces, scaffoldDesignSystemConfig, } from "../utils/branding.js";
7
+ import { getGitInfo, resolveRepoName } from "../utils/git.js";
8
+ import { ensureGitExcludeHasChomp, getChompMasterRoot, installGlobalChompShims, isChompMasterMonorepo, resolveGlobalChompBinary, setActiveChompTarget, } from "../utils/masterContext.js";
9
+ import { runAnalyze } from "./analyze.js";
10
+ import { startUiServer } from "./ui.js";
11
+ export const HARNESS_TEXT = `
12
+ # --- BEGIN CHOMP HARNESS ---
13
+ You are working in a Chomp-enabled workspace. Use the live codebase map first instead of guessing structure with grep or blind file scans:
14
+ 1. Resolve target node IDs with chomp_get_nodes (using search_term / packageName) BEFORE reading source files. When the user asks an architectural question, queries how a flow works, or requests a visual walkthrough, IMMEDIATELY call chomp_create_view (passing viewLevel: "system" | "package") to spotlight the flow on Chomp Map and share the returned viewUrl link. Do NOT call chomp_create_view on routine coding or implementation prompts.
15
+ 2. Call chomp_get_blast_radius (with create_view: false during coding tasks, or create_view: true when answering impact questions) BEFORE modifying a function, class, or route to check upstream callers, downstream dependencies, and input/output types, and use chomp_get_edges to trace call paths.
16
+ 3. Call chomp_audit_health, chomp_find_redundancies, and chomp_check_boundaries to find unresolved calls, pass-through wrappers, duplicate flows, and boundary issues. Use chomp_get_conventions to match standard project patterns, and chomp_local_shims to add Bridges for dynamic or dependency-injected calls. For frontend CSS, Tailwind, or React UI edits, call chomp_audit_design_system before writing and chomp_diff_design_system after editing.
17
+ 4. Call chomp_get_diff BEFORE finishing code changes to verify the exact structural impact against the saved map. Read the map first.
18
+ # --- END CHOMP HARNESS ---
19
+ `.trim() + "\n";
20
+ export const CHOMP_HOOK_BLOCK = `
21
+ # --- BEGIN CHOMP HOOK ---
22
+ # Automatically keep .chomp/graph.db in sync after git operations (non-blocking)
23
+ if [ -x "$HOME/.local/bin/chomp" ]; then
24
+ "$HOME/.local/bin/chomp" analyze . --quiet >/dev/null 2>&1 || true
25
+ elif command -v chomp >/dev/null 2>&1; then
26
+ chomp analyze . --quiet >/dev/null 2>&1 || true
27
+ elif command -v pnpm >/dev/null 2>&1 && grep -q '"chomp":' package.json 2>/dev/null; then
28
+ pnpm chomp analyze . --quiet >/dev/null 2>&1 || true
29
+ else
30
+ npx --no-install @getchomp/cli analyze . --quiet >/dev/null 2>&1 || true
31
+ fi
32
+ # --- END CHOMP HOOK ---
33
+ `.trim() + "\n";
34
+ const GIT_HOOK_NAMES = ["post-commit", "post-merge", "post-checkout"];
35
+ function ensureGitignoreHasChomp(repoRoot) {
36
+ const gitignorePath = resolve(repoRoot, ".gitignore");
37
+ if (existsSync(gitignorePath)) {
38
+ const content = readFileSync(gitignorePath, "utf8");
39
+ const lines = content.split(/\r?\n/).map((l) => l.trim());
40
+ if (lines.includes(".chomp") ||
41
+ lines.includes(".chomp/") ||
42
+ lines.includes("/.chomp") ||
43
+ lines.includes("/.chomp/")) {
44
+ return false;
45
+ }
46
+ const sep = content.endsWith("\n") || content.length === 0 ? "" : "\n";
47
+ writeFileSync(gitignorePath, `${content}${sep}\n# --- BEGIN CHOMP IGNORE ---\n.chomp/\n# --- END CHOMP IGNORE ---\n`, "utf8");
48
+ return true;
49
+ }
50
+ else {
51
+ writeFileSync(gitignorePath, `# --- BEGIN CHOMP IGNORE ---\n.chomp/\n# --- END CHOMP IGNORE ---\n`, "utf8");
52
+ return true;
53
+ }
54
+ }
55
+ export function installGitHooks(repoRoot) {
56
+ const huskyDir = resolve(repoRoot, ".husky");
57
+ const gitHooksDir = resolve(repoRoot, ".git", "hooks");
58
+ const useHusky = existsSync(huskyDir);
59
+ const targetDir = useHusky
60
+ ? huskyDir
61
+ : existsSync(resolve(repoRoot, ".git"))
62
+ ? gitHooksDir
63
+ : null;
64
+ if (!targetDir) {
65
+ return { mode: "none", files: [] };
66
+ }
67
+ if (!existsSync(targetDir)) {
68
+ try {
69
+ mkdirSync(targetDir, { recursive: true });
70
+ }
71
+ catch {
72
+ return { mode: "none", files: [] };
73
+ }
74
+ }
75
+ // If a legacy .husky/pre-commit had a bare `pnpm chomp analyze .`, remove that line
76
+ // so commits are never slowed down or spammed by pre-commit extraction.
77
+ const legacyPreCommit = resolve(targetDir, "pre-commit");
78
+ if (existsSync(legacyPreCommit)) {
79
+ try {
80
+ const rawPre = readFileSync(legacyPreCommit, "utf8");
81
+ const cleanedLines = rawPre
82
+ .split(/\r?\n/)
83
+ .filter((line) => !/^\s*(pnpm|npx)\s+chomp\s+analyze\b/.test(line));
84
+ const cleaned = cleanedLines.join("\n").trim();
85
+ if (cleaned !== rawPre.trim()) {
86
+ if (!cleaned || cleaned === "#!/bin/sh" || cleaned === "#!/usr/bin/env sh") {
87
+ unlinkSync(legacyPreCommit);
88
+ }
89
+ else {
90
+ writeFileSync(legacyPreCommit, cleaned + "\n", "utf8");
91
+ }
92
+ }
93
+ }
94
+ catch {
95
+ // ignore if hook dir is write-protected
96
+ }
97
+ }
98
+ const updatedFiles = [];
99
+ const hookBlockRegex = /# --- BEGIN CHOMP HOOK ---\r?\n[\s\S]*?# --- END CHOMP HOOK ---\r?\n?/;
100
+ for (const hookName of GIT_HOOK_NAMES) {
101
+ const hookPath = resolve(targetDir, hookName);
102
+ let content = existsSync(hookPath) ? readFileSync(hookPath, "utf8") : "";
103
+ try {
104
+ if (!content.includes("# --- BEGIN CHOMP HOOK ---")) {
105
+ const prefix = content.trim().length > 0
106
+ ? content.trimEnd() + "\n\n"
107
+ : useHusky
108
+ ? ""
109
+ : "#!/bin/sh\n\n";
110
+ writeFileSync(hookPath, prefix + CHOMP_HOOK_BLOCK, "utf8");
111
+ try {
112
+ chmodSync(hookPath, 0o755);
113
+ }
114
+ catch {
115
+ // ignore chmod errors on Windows
116
+ }
117
+ updatedFiles.push(useHusky ? `.husky/${hookName}` : `.git/hooks/${hookName}`);
118
+ }
119
+ else if (!content.includes("$HOME/.local/bin/chomp")) {
120
+ const upgraded = content.replace(hookBlockRegex, CHOMP_HOOK_BLOCK);
121
+ writeFileSync(hookPath, upgraded, "utf8");
122
+ try {
123
+ chmodSync(hookPath, 0o755);
124
+ }
125
+ catch {
126
+ // ignore chmod errors on Windows
127
+ }
128
+ updatedFiles.push(useHusky ? `.husky/${hookName}` : `.git/hooks/${hookName}`);
129
+ }
130
+ }
131
+ catch {
132
+ // ignore EPERM if running inside a write-protected sandbox
133
+ }
134
+ }
135
+ return {
136
+ mode: useHusky ? "husky" : "git-hooks",
137
+ files: updatedFiles,
138
+ };
139
+ }
140
+ export const KIRO_AUTO_APPROVE_TOOLS = [
141
+ "chomp_get_nodes",
142
+ "chomp_get_edges",
143
+ "chomp_get_diff",
144
+ "chomp_create_view",
145
+ "chomp_audit_health",
146
+ "chomp_find_redundancies",
147
+ "chomp_check_boundaries",
148
+ "chomp_get_blast_radius",
149
+ "chomp_get_conventions",
150
+ "chomp_audit_design_system",
151
+ "chomp_diff_design_system",
152
+ ];
153
+ export const KIRO_STEALTH_EXCLUDE_ENTRIES = [
154
+ ".kiro/settings/mcp.json",
155
+ ".kiro/steering/chomp-architecture.md",
156
+ ".kiro/hooks/chomp-sync.kiro.hook",
157
+ ".kiro/powers/chomp/",
158
+ ];
159
+ export function detectAgentIntegrations(repoRoot, env = process.env) {
160
+ const cursorDir = resolve(repoRoot, ".cursor");
161
+ const cursorRules = resolve(repoRoot, ".cursorrules");
162
+ const claudeMd = resolve(repoRoot, "CLAUDE.md");
163
+ const claudeMcp = resolve(repoRoot, ".mcp.json");
164
+ const agentsMd = resolve(repoRoot, "AGENTS.md");
165
+ const windsurfRules = resolve(repoRoot, ".windsurfrules");
166
+ const kiroDir = resolve(repoRoot, ".kiro");
167
+ const agyMcpConfig = resolve(homedir(), ".gemini", "antigravity", "mcp_config.json");
168
+ const cursorDetected = existsSync(cursorDir) || existsSync(cursorRules);
169
+ const claudeDetected = existsSync(claudeMd) || existsSync(claudeMcp);
170
+ const agyDetected = existsSync(agentsMd) ||
171
+ existsSync(resolve(homedir(), ".gemini", "antigravity"));
172
+ const windsurfDetected = existsSync(windsurfRules);
173
+ const kiroDetected = existsSync(kiroDir) ||
174
+ Boolean(env.KIRO_PID) ||
175
+ Boolean(env.TERM_PROGRAM?.toLowerCase().includes("kiro"));
176
+ const anyDetected = cursorDetected ||
177
+ claudeDetected ||
178
+ agyDetected ||
179
+ windsurfDetected ||
180
+ kiroDetected;
181
+ return [
182
+ {
183
+ id: "cursor",
184
+ label: "Cursor",
185
+ hint: ".cursor/mcp.json + .cursorrules",
186
+ detected: cursorDetected || !anyDetected,
187
+ ruleFile: ".cursorrules",
188
+ mcpConfigPath: resolve(repoRoot, ".cursor", "mcp.json"),
189
+ },
190
+ {
191
+ id: "kiro",
192
+ label: "Kiro",
193
+ hint: ".kiro/settings/mcp.json + steering + hook + power",
194
+ detected: kiroDetected,
195
+ ruleFile: ".kiro/steering/chomp-architecture.md",
196
+ mcpConfigPath: resolve(repoRoot, ".kiro", "settings", "mcp.json"),
197
+ },
198
+ {
199
+ id: "claude",
200
+ label: "Claude Code",
201
+ hint: ".mcp.json + CLAUDE.md",
202
+ detected: claudeDetected,
203
+ ruleFile: "CLAUDE.md",
204
+ mcpConfigPath: claudeMcp,
205
+ },
206
+ {
207
+ id: "antigravity",
208
+ label: "Antigravity / AGENTS.md",
209
+ hint: "AGENTS.md + mcp_config.json",
210
+ detected: agyDetected || !anyDetected,
211
+ ruleFile: "AGENTS.md",
212
+ mcpConfigPath: existsSync(dirname(agyMcpConfig))
213
+ ? agyMcpConfig
214
+ : undefined,
215
+ },
216
+ {
217
+ id: "windsurf",
218
+ label: "Windsurf",
219
+ hint: ".windsurfrules",
220
+ detected: windsurfDetected,
221
+ ruleFile: ".windsurfrules",
222
+ },
223
+ ];
224
+ }
225
+ function buildChompMcpServerEntry(repoRoot, options) {
226
+ const masterRoot = getChompMasterRoot();
227
+ const inMasterMonorepo = isChompMasterMonorepo(masterRoot);
228
+ const globalChompBin = resolveGlobalChompBinary();
229
+ const masterTsx = [
230
+ resolve(masterRoot, "packages/db/node_modules/.bin/tsx"),
231
+ resolve(masterRoot, "packages/cli/node_modules/.bin/tsx"),
232
+ resolve(masterRoot, "node_modules/.bin/tsx"),
233
+ ].find((p) => existsSync(p));
234
+ const masterCliEntry = resolve(masterRoot, "packages/cli/src/index.ts");
235
+ let baseEntry;
236
+ if (globalChompBin) {
237
+ baseEntry = {
238
+ command: globalChompBin,
239
+ args: ["mcp", repoRoot],
240
+ };
241
+ }
242
+ else if (inMasterMonorepo && masterTsx && existsSync(masterCliEntry)) {
243
+ baseEntry = {
244
+ command: masterTsx,
245
+ args: [masterCliEntry, "mcp", repoRoot],
246
+ };
247
+ }
248
+ else {
249
+ baseEntry = {
250
+ command: "npx",
251
+ args: ["-y", "@getchomp/cli", "mcp", repoRoot],
252
+ };
253
+ }
254
+ if (options?.kiro) {
255
+ return {
256
+ ...baseEntry,
257
+ disabled: false,
258
+ autoApprove: [...KIRO_AUTO_APPROVE_TOOLS],
259
+ };
260
+ }
261
+ return baseEntry;
262
+ }
263
+ export function upsertMcpServerConfig(mcpJsonPath, repoRoot, options) {
264
+ try {
265
+ let rootObj = {};
266
+ if (existsSync(mcpJsonPath)) {
267
+ try {
268
+ rootObj = JSON.parse(readFileSync(mcpJsonPath, "utf8"));
269
+ }
270
+ catch {
271
+ return false;
272
+ }
273
+ }
274
+ if (!rootObj.mcpServers || typeof rootObj.mcpServers !== "object") {
275
+ rootObj.mcpServers = {};
276
+ }
277
+ // Preserve existing custom chomp-server config if already present
278
+ if (rootObj.mcpServers["chomp-server"]) {
279
+ return false;
280
+ }
281
+ rootObj.mcpServers["chomp-server"] = buildChompMcpServerEntry(repoRoot, options);
282
+ const parentDir = dirname(mcpJsonPath);
283
+ if (!existsSync(parentDir)) {
284
+ mkdirSync(parentDir, { recursive: true });
285
+ }
286
+ writeFileSync(mcpJsonPath, JSON.stringify(rootObj, null, 2) + "\n", "utf8");
287
+ return true;
288
+ }
289
+ catch {
290
+ return false;
291
+ }
292
+ }
293
+ export function installKiroIntegration(repoRoot, options) {
294
+ const isStealth = Boolean(options?.stealth);
295
+ const mcpPath = resolve(repoRoot, ".kiro", "settings", "mcp.json");
296
+ const hadExistingMcpFile = existsSync(mcpPath);
297
+ const mcpUpdated = upsertMcpServerConfig(mcpPath, repoRoot, { kiro: true });
298
+ // 1. .kiro/steering/chomp-architecture.md with `inclusion: always` frontmatter
299
+ const steeringPath = resolve(repoRoot, ".kiro", "steering", "chomp-architecture.md");
300
+ mkdirSync(dirname(steeringPath), { recursive: true });
301
+ let steeringUpdated = false;
302
+ const existingSteering = existsSync(steeringPath)
303
+ ? readFileSync(steeringPath, "utf8")
304
+ : "";
305
+ if (!existingSteering.includes("# --- BEGIN CHOMP HARNESS ---")) {
306
+ if (existingSteering.trim().length > 0) {
307
+ writeFileSync(steeringPath, `${existingSteering.trimEnd()}\n\n${HARNESS_TEXT}`, "utf8");
308
+ }
309
+ else {
310
+ const steeringDoc = [
311
+ "---",
312
+ "inclusion: always",
313
+ "---",
314
+ "",
315
+ "# Chomp Architecture & Structural Navigation",
316
+ "",
317
+ HARNESS_TEXT.trimEnd(),
318
+ ].join("\n") + "\n";
319
+ writeFileSync(steeringPath, steeringDoc, "utf8");
320
+ }
321
+ steeringUpdated = true;
322
+ }
323
+ // 2. .kiro/hooks/chomp-sync.kiro.hook
324
+ const hookPath = resolve(repoRoot, ".kiro", "hooks", "chomp-sync.kiro.hook");
325
+ mkdirSync(dirname(hookPath), { recursive: true });
326
+ const hookManifest = {
327
+ enabled: true,
328
+ name: "Chomp Structural Graph Sync",
329
+ description: "Keep .chomp/graph.db synchronized when TypeScript or JavaScript source files are edited.",
330
+ version: "1",
331
+ when: {
332
+ type: "fileEdited",
333
+ patterns: ["**/*.{ts,tsx,js,jsx}"],
334
+ },
335
+ then: {
336
+ type: "runCommand",
337
+ command: "chomp analyze . --quiet",
338
+ },
339
+ };
340
+ writeFileSync(hookPath, JSON.stringify(hookManifest, null, 2) + "\n", "utf8");
341
+ const hookUpdated = true;
342
+ // 3. .kiro/powers/chomp/POWER.md + .kiro/powers/chomp/mcp.json
343
+ const powerDir = resolve(repoRoot, ".kiro", "powers", "chomp");
344
+ mkdirSync(powerDir, { recursive: true });
345
+ const powerMdPath = resolve(powerDir, "POWER.md");
346
+ const powerMcpPath = resolve(powerDir, "mcp.json");
347
+ const powerMd = [
348
+ "---",
349
+ 'name: "chomp"',
350
+ 'displayName: "Chomp Codebase Map"',
351
+ 'description: "The live map of your codebase — blast-radius impact, Spotlight views, design system checks, and architectural health tools for AI coding agents."',
352
+ 'keywords: ["architecture", "codebase-map", "blast-radius", "design-system", "mcp"]',
353
+ "---",
354
+ "",
355
+ "# Chomp Codebase Map Power",
356
+ "",
357
+ "Provides deterministic codebase map tools (`chomp-server`) for map-first navigation, pre-edit blast radius checks, Spotlight views, design system audits, and post-edit verification.",
358
+ "",
359
+ "## Core Workflow",
360
+ "",
361
+ "1. **Map-First Navigation:** Call `chomp_get_nodes` (`search_term` / `packageName`) and `chomp_get_edges` before reading files.",
362
+ "2. **Pre-Edit Impact:** Call `chomp_get_blast_radius` (`create_view: false` during coding tasks) before modifying functions, classes, or routes.",
363
+ "3. **Spotlight Views (Questions Only):** Call `chomp_create_view` only when answering architectural questions or walkthrough requests.",
364
+ "4. **Health, Boundaries & Design System:** Call `chomp_audit_health`, `chomp_find_redundancies`, `chomp_check_boundaries`, `chomp_get_conventions`, `chomp_local_shims`, and `chomp_audit_design_system` (for frontend work).",
365
+ "5. **Post-Edit Verification:** Call `chomp_get_diff` (and `chomp_diff_design_system` for frontend changes) before completing code changes.",
366
+ ].join("\n") + "\n";
367
+ writeFileSync(powerMdPath, powerMd, "utf8");
368
+ writeFileSync(powerMcpPath, JSON.stringify({
369
+ mcpServers: {
370
+ "chomp-server": buildChompMcpServerEntry(repoRoot, { kiro: true }),
371
+ },
372
+ }, null, 2) + "\n", "utf8");
373
+ const powerUpdated = true;
374
+ if (isStealth) {
375
+ const excludeItems = KIRO_STEALTH_EXCLUDE_ENTRIES.filter((entry) => !(entry === ".kiro/settings/mcp.json" && hadExistingMcpFile));
376
+ ensureGitExcludeHasChomp(repoRoot, [...excludeItems]);
377
+ }
378
+ return {
379
+ mcpUpdated,
380
+ steeringUpdated,
381
+ hookUpdated,
382
+ powerUpdated,
383
+ };
384
+ }
385
+ function injectRuleHarness(repoRoot, ruleFile) {
386
+ const filePath = resolve(repoRoot, ruleFile);
387
+ const content = existsSync(filePath) ? readFileSync(filePath, "utf8") : "";
388
+ if (content.includes("# --- BEGIN CHOMP HARNESS ---") ||
389
+ content.includes("Software Representation Engine (`chomp`) — Agent Guidelines")) {
390
+ return false;
391
+ }
392
+ const separator = content.trim().length > 0 ? "\n\n" : "";
393
+ writeFileSync(filePath, content.trim() + separator + HARNESS_TEXT, "utf8");
394
+ return true;
395
+ }
396
+ export async function runInitWizard(inputPath, options = {}) {
397
+ const baseDir = process.env.INIT_CWD ?? process.cwd();
398
+ const targetPath = resolve(baseDir, inputPath ?? ".");
399
+ const repoName = resolveRepoName(targetPath);
400
+ const isDryRun = Boolean(options.dryRun || options.sandbox);
401
+ const isStealth = Boolean(options.stealth);
402
+ // 0. Brand Banner (static Frame 1 on init; animation runs during code analysis)
403
+ if (options.logo) {
404
+ if (process.stdout.isTTY) {
405
+ await playChompBannerAnimation(`Initializing Chomp in ${repoName} (${targetPath})`, { cycles: 3, frameMs: 200 });
406
+ }
407
+ else {
408
+ printChompBanner(`Frame 1 — Open Mouth Logo (${repoName})`, "open");
409
+ printChompBanner(`Frame 2 — Chomping Animation Frame (${repoName})`, "chomp");
410
+ }
411
+ return;
412
+ }
413
+ printChompBanner(isDryRun
414
+ ? `[SANDBOX DRY-RUN] Previewing Chomp setup in ${repoName} (zero file writes)`
415
+ : `Initializing Chomp in ${repoName} (${targetPath})`, "open");
416
+ printWelcomeMessage(repoName, isDryRun);
417
+ if (!existsSync(targetPath)) {
418
+ console.error(` ${ansi.red("✖")} Path does not exist: ${targetPath}`);
419
+ process.exit(1);
420
+ }
421
+ if (!isDryRun) {
422
+ installGlobalChompShims();
423
+ }
424
+ // Paced discovery ticker right beneath the welcome message so the user can view
425
+ // the brand mark while Chomp inspects package.json and monorepo layout
426
+ await runDiscoveryTicker(repoName);
427
+ const isInteractive = Boolean(process.stdin.isTTY && process.stdout.isTTY) && !options.yes;
428
+ const printStepDivider = () => {
429
+ console.log(`\n ${ansi.dim("┄".repeat(66))}\n`);
430
+ };
431
+ // 1. Create .chomp/ and .chomp/plugins/ and update .gitignore (or .git/info/exclude in stealth mode) + Detect Workspace Packages
432
+ const chompDir = resolve(targetPath, ".chomp");
433
+ const chompPluginsDir = resolve(chompDir, "plugins");
434
+ const vaultNotes = [];
435
+ if (isDryRun) {
436
+ vaultNotes.push(`${ansi.cyan("○")} ${ansi.dim("[Sandbox]")} Would create ${ansi.cyan(".chomp/")} (${ansi.cyan(".chomp/plugins/")}) and update ${ansi.cyan(isStealth ? ".git/info/exclude" : ".gitignore")}`);
437
+ }
438
+ else {
439
+ if (!existsSync(chompDir)) {
440
+ mkdirSync(chompPluginsDir, { recursive: true });
441
+ vaultNotes.push(`${ansi.green("✓")} Created ${ansi.cyan(".chomp/")} and ${ansi.cyan(".chomp/plugins/")} local storage`);
442
+ }
443
+ else {
444
+ mkdirSync(chompPluginsDir, { recursive: true });
445
+ vaultNotes.push(`${ansi.green("✓")} Verified ${ansi.cyan(".chomp/")} and ${ansi.cyan(".chomp/plugins/")} local storage`);
446
+ }
447
+ ensureGitExcludeHasChomp(targetPath);
448
+ if (isStealth) {
449
+ vaultNotes.push(`${ansi.green("✓")} Hidden ${ansi.cyan(".chomp/")} in ${ansi.cyan(".git/info/exclude")} (stealth mode — zero .gitignore edits)`);
450
+ }
451
+ else if (ensureGitignoreHasChomp(targetPath)) {
452
+ vaultNotes.push(`${ansi.green("✓")} Added ${ansi.cyan(".chomp/")} to ${ansi.cyan(".gitignore")}`);
453
+ }
454
+ }
455
+ const detectedPackages = detectWorkspacePackages(targetPath);
456
+ let dryRunExclusions;
457
+ // Render detected workspace configuration in a read-only box table
458
+ printDetectedWorkspaceTable(repoName, detectedPackages, vaultNotes);
459
+ // 2. Optional Package Exclusions Prompt
460
+ if (detectedPackages.length > 1 && isInteractive) {
461
+ printStepDivider();
462
+ const wantCustomizePackages = await confirmPrompt("Exclude any packages?", false, "Chomp analyzes all detected packages by default.");
463
+ if (wantCustomizePackages) {
464
+ console.log("");
465
+ const includedNames = await multiSelectPrompt("Select packages to analyze", "Up/Down to move · Space to toggle · 'a' to toggle all · Enter to confirm", detectedPackages.map((p) => ({
466
+ value: p.name,
467
+ label: `${p.name} (${p.relPath})`,
468
+ hint: p.frameworks.length > 0 ? `[${p.frameworks.join(", ")}]` : undefined,
469
+ selected: !p.currentlyExcluded,
470
+ })));
471
+ const includedSet = new Set(includedNames);
472
+ const excluded = detectedPackages
473
+ .filter((p) => !includedSet.has(p.name))
474
+ .map((p) => p.name);
475
+ if (isDryRun) {
476
+ dryRunExclusions = excluded;
477
+ console.log(excluded.length > 0
478
+ ? ` ${ansi.cyan("○")} ${ansi.dim("[Sandbox]")} Would exclude ${excluded.length} package(s) in ${ansi.cyan("chomp.config.json")}: ${excluded.join(", ")}`
479
+ : ` ${ansi.cyan("○")} ${ansi.dim("[Sandbox]")} All ${detectedPackages.length} packages selected`);
480
+ }
481
+ else {
482
+ saveExcludeWorkspaces(targetPath, excluded);
483
+ if (excluded.length > 0) {
484
+ console.log(` ${ansi.green("✓")} Excluded ${excluded.length} package(s) in ${ansi.cyan("chomp.config.json")}: ${excluded.join(", ")}`);
485
+ }
486
+ else {
487
+ console.log(` ${ansi.green("✓")} Analyzing all ${detectedPackages.length} packages`);
488
+ }
489
+ }
490
+ }
491
+ }
492
+ // 2b. Scaffold starter `designSystem` plugin config when frontend packages are detected
493
+ const dsScaffold = scaffoldDesignSystemConfig(targetPath, {
494
+ stealth: isStealth,
495
+ dryRun: isDryRun,
496
+ excludeWorkspaces: dryRunExclusions,
497
+ });
498
+ if (dsScaffold.wouldWrite && dsScaffold.configRelPath) {
499
+ console.log(` ${ansi.cyan("○")} ${ansi.dim("[Sandbox]")} Would scaffold ${ansi.cyan("designSystem")} config in ${ansi.cyan(dsScaffold.configRelPath)} (${dsScaffold.frontendPackages.join(", ")})`);
500
+ }
501
+ else if (dsScaffold.written && dsScaffold.configRelPath) {
502
+ console.log(` ${ansi.green("✓")} Scaffolded ${ansi.cyan("designSystem")} config in ${ansi.cyan(dsScaffold.configRelPath)} (${dsScaffold.frontendPackages.join(", ")})`);
503
+ }
504
+ // 3. Git Hooks (post-commit, post-merge, post-checkout)
505
+ printStepDivider();
506
+ const shouldInstallHooks = isInteractive
507
+ ? await confirmPrompt("Keep Chomp in sync with Git?", true, "Updates your graph in the background after commits, merges, and branch switches without slowing down Git.")
508
+ : true;
509
+ if (shouldInstallHooks) {
510
+ if (isDryRun) {
511
+ console.log(` ${ansi.cyan("○")} ${ansi.dim("[Sandbox]")} Would add background Git hooks (post-commit, post-merge, post-checkout)`);
512
+ }
513
+ else {
514
+ const hookRes = installGitHooks(targetPath);
515
+ if (hookRes.files.length > 0) {
516
+ console.log(` ${ansi.green("✓")} Added background Git hooks (${hookRes.files.join(", ")})`);
517
+ }
518
+ else if (hookRes.mode !== "none") {
519
+ console.log(` ${ansi.green("✓")} Git hooks (${hookRes.mode}) already up to date`);
520
+ }
521
+ }
522
+ }
523
+ // 3b. Global CLI Installation (when invoked via `npx @getchomp/cli init` without global `chomp`)
524
+ if (!isChompMasterMonorepo() && !resolveGlobalChompBinary()) {
525
+ printStepDivider();
526
+ const shouldInstallGlobal = isInteractive
527
+ ? await confirmPrompt("Install 'chomp' CLI globally?", true, "Installs @getchomp/cli globally (npm install -g @getchomp/cli) so 'chomp ui', git hooks, and MCP start instantly in any repo while keeping project state inside .chomp/.")
528
+ : false;
529
+ if (shouldInstallGlobal) {
530
+ if (isDryRun) {
531
+ console.log(` ${ansi.cyan("○")} ${ansi.dim("[Sandbox]")} Would run ${ansi.cyan("npm install -g @getchomp/cli")} so ${ansi.bold("chomp")} is available globally`);
532
+ }
533
+ else {
534
+ try {
535
+ console.log(` ${ansi.cyan("⬇")} Installing ${ansi.bold("@getchomp/cli")} globally...`);
536
+ execSync("npm install -g @getchomp/cli", { stdio: "inherit" });
537
+ console.log(` ${ansi.green("✓")} Installed ${ansi.bold("chomp")} globally (${ansi.cyan(resolveGlobalChompBinary() ?? "chomp")})`);
538
+ }
539
+ catch {
540
+ console.log(` ${ansi.yellow("⚠")} Global install skipped — falling back to ${ansi.cyan("npx -y @getchomp/cli")} for MCP and git hooks.`);
541
+ }
542
+ }
543
+ }
544
+ }
545
+ // 4. AI Agent & MCP Server Configuration
546
+ printStepDivider();
547
+ const integrations = detectAgentIntegrations(targetPath);
548
+ let selectedAgentIds;
549
+ if (isInteractive) {
550
+ selectedAgentIds = await multiSelectPrompt("Connect AI coding agents", "Adds Chomp MCP tools and navigation rules to selected agents · Space to toggle · Enter to confirm", integrations.map((agent) => ({
551
+ value: agent.id,
552
+ label: agent.label,
553
+ hint: agent.hint,
554
+ selected: agent.detected,
555
+ })));
556
+ }
557
+ else {
558
+ selectedAgentIds = integrations
559
+ .filter((a) => a.detected)
560
+ .map((a) => a.id);
561
+ }
562
+ for (const agent of integrations) {
563
+ if (!selectedAgentIds.includes(agent.id))
564
+ continue;
565
+ if (isDryRun) {
566
+ console.log(` ${ansi.cyan("○")} ${ansi.dim("[Sandbox]")} Would connect ${ansi.bold(agent.label)} (${ansi.cyan(agent.ruleFile)}${agent.mcpConfigPath ? ` + ${ansi.cyan(agent.mcpConfigPath)}` : ""})`);
567
+ continue;
568
+ }
569
+ if (agent.id === "kiro") {
570
+ const kiroRes = installKiroIntegration(targetPath, {
571
+ stealth: isStealth,
572
+ });
573
+ console.log(` ${ansi.green("✓")} Configured ${ansi.bold("Kiro")} (${ansi.cyan(".kiro/settings/mcp.json")}, ${ansi.cyan(".kiro/steering/chomp-architecture.md")}, ${ansi.cyan(".kiro/hooks/chomp-sync.kiro.hook")}, ${ansi.cyan(".kiro/powers/chomp/")})${isStealth ? ansi.dim(" [hidden in .git/info/exclude]") : ""}`);
574
+ if (!kiroRes.mcpUpdated) {
575
+ console.log(` ${ansi.green("✓")} Preserved existing ${ansi.bold("chomp-server")} entry in ${ansi.cyan(".kiro/settings/mcp.json")}`);
576
+ }
577
+ continue;
578
+ }
579
+ if (isStealth) {
580
+ console.log(` ${ansi.green("✓")} Stealth mode: skipped modifying tracked rule file ${ansi.cyan(agent.ruleFile)}`);
581
+ }
582
+ else if (injectRuleHarness(targetPath, agent.ruleFile)) {
583
+ console.log(` ${ansi.green("✓")} Added Chomp rules to ${ansi.cyan(agent.ruleFile)}`);
584
+ }
585
+ else {
586
+ console.log(` ${ansi.green("✓")} Verified Chomp rules in ${ansi.cyan(agent.ruleFile)}`);
587
+ }
588
+ if (agent.mcpConfigPath && (!isStealth || agent.id === "antigravity")) {
589
+ if (upsertMcpServerConfig(agent.mcpConfigPath, targetPath)) {
590
+ console.log(` ${ansi.green("✓")} Connected ${ansi.bold("chomp-server")} MCP in ${ansi.cyan(agent.mcpConfigPath)}`);
591
+ }
592
+ }
593
+ }
594
+ // 5. Run Initial Extraction with Live Chomping Animation & Event Feed
595
+ printStepDivider();
596
+ if (isDryRun) {
597
+ const { commitSha, branchName } = getGitInfo(targetPath);
598
+ const excludeWorkspaces = dryRunExclusions ?? loadExcludeWorkspaces(targetPath);
599
+ await runChompExtractionWithAnimation({
600
+ repoName,
601
+ repoPath: targetPath,
602
+ dbPath: `${resolve(targetPath, ".chomp", "graph.db")} (sandbox dry-run)`,
603
+ commitSha,
604
+ branchName,
605
+ excludeWorkspaces,
606
+ isSandbox: true,
607
+ executeExtraction: async () => {
608
+ const t0 = Date.now();
609
+ const graph = analyzeTarget(targetPath, CORE_EXTRACTOR_VERSION, commitSha, excludeWorkspaces);
610
+ const durationMs = Date.now() - t0;
611
+ return { graph, durationMs };
612
+ },
613
+ });
614
+ }
615
+ else {
616
+ await runAnalyze(targetPath);
617
+ const ctx = setActiveChompTarget(targetPath);
618
+ console.log(` ${ansi.green("✓")} Active repo connected: ${ansi.bold(ctx.activeRepoId)} (${ansi.cyan(ctx.activeRepoPath)}) — MCP & Chomp Map set to this repo`);
619
+ }
620
+ console.log(isDryRun
621
+ ? ` ${ansi.green("🎉")} ${ansi.bold("Sandbox preview complete.")} ${ansi.dim("Run 'chomp init' without --sandbox to apply.")}`
622
+ : ` ${ansi.green("🎉")} ${ansi.bold("Chomp is ready!")} ${ansi.dim("Run 'chomp uninstall' anytime to remove Chomp files and hooks.")}`);
623
+ // 6. Offer to Launch Chomp Map
624
+ if (options.ui !== false && isInteractive) {
625
+ printStepDivider();
626
+ const launchNow = await confirmPrompt("Open Chomp Map now?", true, `Starts the local server at http://localhost:${options.port ?? "5555"} and opens your codebase map in the browser.`);
627
+ if (launchNow) {
628
+ if (isDryRun) {
629
+ console.log(` ${ansi.cyan("○")} ${ansi.dim("[Sandbox]")} Would open Chomp Map at ${ansi.cyan(`http://localhost:${options.port ?? "5555"}`)}`);
630
+ }
631
+ else {
632
+ await startUiServer(targetPath, {
633
+ port: options.port ?? "5555",
634
+ open: true,
635
+ watch: true,
636
+ });
637
+ }
638
+ }
639
+ }
640
+ }
641
+ export function registerInitCommand(program) {
642
+ program
643
+ .command("init [path]")
644
+ .description("Guided 60-second installer: configure packages, git hooks, AI agent MCP harness, and launch Chomp Map.")
645
+ .option("-y, --yes", "Accept recommended defaults without interactive prompts", false)
646
+ .option("--no-ui", "Do not prompt or launch Chomp Map after setup")
647
+ .option("-p, --port <number>", "Port for the local Chomp Map server", "5555")
648
+ .option("--logo", "Preview the Chomp Unicode terminal banner and exit", false)
649
+ .option("--stealth", "Keep target repo git-clean: hide .chomp/ in .git/info/exclude and skip modifying .gitignore or tracked rule files", false)
650
+ .option("--dry-run, --sandbox", "Run the interactive init wizard in sandbox mode without modifying any files or databases", false)
651
+ .action(async (inputPath, options) => {
652
+ await runInitWizard(inputPath, options);
653
+ });
654
+ }
@@ -0,0 +1,2 @@
1
+ import { Command } from "commander";
2
+ export declare function registerMcpCommand(program: Command): void;
@@ -0,0 +1,12 @@
1
+ import { runMcpServer } from "@getchomp/mcp";
2
+ import { resolve } from "node:path";
3
+ export function registerMcpCommand(program) {
4
+ program
5
+ .command("mcp [path]")
6
+ .description("Start the Chomp MCP Server for Agentic Querying")
7
+ .action(async (inputPath) => {
8
+ const baseDir = process.env.INIT_CWD ?? process.cwd();
9
+ const targetPath = inputPath ? resolve(baseDir, inputPath) : baseDir;
10
+ await runMcpServer(targetPath);
11
+ });
12
+ }