Files
codegraph/src/installer/index.ts
T
a447e1d430 feat(installer): multi-target — Claude Code, Cursor, Codex CLI, opencode (#162)
* feat(installer): multi-target — Claude Code, Cursor, Codex CLI, opencode

Closes the Claude-locked installer behind issue #137. The runtime MCP
server was already agent-agnostic (stdio); only the installer was
locked. After this refactor, `codegraph install` can write per-agent
MCP config + instructions for any combination of supported agents.

## What ships

Four agent targets, each implementing the new `AgentTarget` interface:

- **Claude Code** — `~/.claude.json`, `~/.claude/settings.json`,
  `~/.claude/CLAUDE.md` (or local equivalents). Behavior preserved
  from the original installer; existing installs upgrade in place.
- **Cursor** — `~/.cursor/mcp.json` (g) or `./.cursor/mcp.json` (l)
  + project-local `./.cursor/rules/codegraph.mdc`.
- **Codex CLI** — `~/.codex/config.toml` with `[mcp_servers.codegraph]`
  + `~/.codex/AGENTS.md`. Global only. Hand-rolled TOML serializer
  scoped to the table we own — siblings + array-of-tables preserved.
- **opencode** — `~/.config/opencode/opencode.json` (XDG) or
  `./opencode.json`.

Adding a 5th agent is a new file in `src/installer/targets/` plus
one entry in `registry.ts`.

## CLI changes

```
codegraph install                                   # interactive multi-select
codegraph install --yes                             # auto-detect, install global
codegraph install --target=cursor,claude --yes     # explicit list
codegraph install --target=auto --location=local   # detected, project-local
codegraph install --target=none                    # skip agent writes entirely
codegraph install --print-config codex             # dump snippet, no writes
```

## Backwards compat

Every export from the old `config-writer.ts` (`writeMcpConfig`,
`writePermissions`, `writeClaudeMd`, `hasMcpConfig`, `hasPermissions`,
`hasClaudeMdSection`) is preserved as a `@deprecated` shim that
delegates to per-file helpers in `targets/claude.ts`. Existing Claude
users see byte-identical on-disk layout — `detect()` reports
`alreadyConfigured: true`, re-running is a no-op.

## Tests

+47 new tests in `__tests__/installer-targets.test.ts`:
- Parameterized contract test across all 4 targets × supported
  locations (install → unchanged on re-run, sibling preservation,
  uninstall reverses install, printConfig writes nothing).
- Codex partial-state recovery, locked-block contract for the
  codegraph table, full TOML serializer suite.
- Registry: getTarget, resolveTargetFlag (auto/all/none/csv).

`__tests__/installer.test.ts` relaxed one assertion: the new code
returns `unchanged` for byte-identical re-runs instead of `updated`;
the surrounding-custom-content contract is unchanged.

## Uninstall behavior change

`bin/uninstall.ts` now loops `ALL_TARGETS.uninstall('global')` on
`npm uninstall -g`. A user who manually configured
`~/.codex/config.toml` with our block will have only that block
removed on package uninstall — we only touch the dotted-key table
we own.

Based on andreinknv/codegraph@c5165e4. Issue #137.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* chore(scripts): add local-install.sh for hands-on branch testing

Builds the current branch and `npm link`s it as the global
`codegraph` binary. `--undo` unlinks and reinstalls the published
version. Mirrors the style of scripts/release.sh.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* feat(installer): move agent picker to the first prompt

Reorders runInstallerWithOptions so the multi-select for agents
(Claude / Cursor / Codex / opencode) is step 1 — before the
global-npm-install confirm and before the location prompt. Bare
`npx @colbymchenry/codegraph` now opens with "Which agents should
CodeGraph configure?", which is the answer most users want first.

Side effects of the reorder:

- Early exit if zero targets selected — skips global-install and
  location prompts entirely, exits with "nothing to do."
- Multiselect labels drop the per-location "will skip" hint (location
  isn't known yet) and replace it with a static "global only" badge
  for targets like Codex that have no project-local config concept.
- If every selected target is global-only, the location prompt is
  skipped and global is forced (no point asking).
- Detection probes the user-provided location if known via flag,
  else 'global' as the most common default — labels are a hint
  about what's installed locally, not load-bearing.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix(installer): disambiguate "global" wording in install prompts

Two prompts both said "global" but meant different things — users
read them as duplicates. Renamed for clarity:

- Step 2 (npm install -g): "Install codegraph globally?" →
  "Install the codegraph CLI on your PATH? (Required so agents can
  launch the MCP server)". Spinner messages match.
- Step 3 (config location): "Where would you like to install?" with
  "Global"/"Local" → "Apply agent configs to all your projects, or
  just this one?" with "All projects" (~/.claude, ~/.cursor, etc.)
  / "Just this project" (./.claude, ./.cursor, etc.).
- All-global-only fallback: "Using global install" → "Writing
  user-wide configs (selected agents have no project-local config)."

Underlying `Location` values ('global' / 'local') unchanged; only
the UI strings shift, so no test or flag breakage.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix(installer/cursor): inject --path so workspace-aware queries work

Cursor launches MCP-server subprocesses with cwd != workspace root,
AND does not pass rootUri or workspaceFolders in the MCP initialize
call. The codegraph MCP server's process.cwd() fallback misses the
workspace's .codegraph/ and reports "not initialized" on every tool
call. Codex and Claude don't have this issue (Codex launches with
cwd=workspace, Claude passes rootUri).

Fix: inject `--path` into the args we write for Cursor.

- local install (./.cursor/mcp.json): hardcode the absolute project
  path — known at install time.
- global install (~/.cursor/mcp.json): use `${workspaceFolder}` so
  Cursor expands it per-workspace. One global config now drives
  every project the user opens, without per-project re-install.

No test breakage — the parameterized contract tests check
idempotency / sibling preservation, not the exact args content.
File-header comment documents the rationale so the next person
doesn't strip the arg as boilerplate.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* feat(init): auto-wire project-local agent surfaces

Closes the global-Cursor UX gap: `~/.cursor/mcp.json` registers the
MCP server, but Cursor's agent only learns to *prefer* codegraph
over native grep when it sees `.cursor/rules/codegraph.mdc` — a
project-local file that global install can't write. Previously the
user had to re-run `codegraph install --target=cursor --location=local`
for every new project. Now `codegraph init` does it automatically.

## What changed

- New optional `AgentTarget.wireProjectSurfaces()` returning a
  WriteResult of project-local files to drop. Most targets omit
  it (their global config is complete). Cursor implements it to
  write the rules file.
- New `wireProjectSurfacesForGlobalAgents()` orchestrator in
  installer/index.ts — iterates ALL_TARGETS, detects which are
  configured globally, calls their wireProjectSurfaces, returns
  what was written.
- `codegraph init` calls the orchestrator in both branches:
  - Fresh init: write surfaces after CodeGraph.init succeeds.
  - Already-initialized re-init: write surfaces too, so re-running
    `init` is the documented recovery path for a project missing
    its rules file.

## Steady-state UX

  1. Once, ever: `codegraph install` (writes global agent configs)
  2. Per project: `codegraph init -i` (builds the index + auto-wires
     project-local agent surfaces — currently Cursor's rules file)

No new tests — wireProjectSurfaces delegates to writeRulesEntry,
which is already covered by the parameterized contract tests.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* feat(installer): agent-agnostic instructions template

The old template was inherited from the Claude-only era and
prescribed "ALWAYS spawn an Explore agent" — a Claude Code-specific
concept (subagents via the Task tool). When Cursor's agent read
this it had no Explore agent to spawn, got confused, and fell back
to native grep/read even for structural queries the codegraph MCP
tools answer in one call.

This rewrite:

- Frames each tool by the question it answers (search vs callers
  vs impact vs context vs explore vs node vs files vs status).
- Tells the agent explicitly to TRUST codegraph results and not
  re-verify them with grep — the over-grep-after-codegraph
  behavior was the main symptom we saw on Cursor.
- Reframes "spawn Explore agent" as an OPTIONAL pattern for
  harnesses that support parallel subagents — Claude Code still
  gets the hint, Cursor / Codex / opencode just skip it.
- Trims the "if not initialized" section to one prescriptive line.

Same marker delimiters (`<!-- CODEGRAPH_START/END -->`) so existing
installs upgrade in place via the marker-based section swap. No
test changes needed — the parameterized contract tests check
marker placement + sibling preservation, not the literal body.

Effective surfaces: ~/.claude/CLAUDE.md (Claude), .cursor/rules/
codegraph.mdc (Cursor, project-local), ~/.codex/AGENTS.md (Codex).
Users get the new copy by re-running `codegraph install` for
global writes, or `codegraph init` for Cursor's project rules.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* docs(readme): reflect multi-agent support at the top + accurate flow

- Tagline now reads "Supercharge Claude Code, Cursor & Codex" instead
  of Claude-only — multi-agent support is what the PR is about, the
  README should say so above the fold.
- New badge row (Claude Code / Cursor / Codex CLI / opencode) in the
  same shields.io style as the OS row.
- Install-flow bullets reordered to match the actual prompt order
  (agent picker first, then PATH install, then location).
- `codegraph init -i` step now mentions that init wires up
  project-local agent surfaces (Cursor rules file etc.) so global
  install works in every project without a re-run.
- Agent-agnostic phrasing in the closing line ("your agent" not
  "Claude Code").

Headline-level brand decision left intentionally in this PR — the
existing Claude-only positioning predates multi-agent support.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: andreinknv <andrei.nknv@outlook.com>
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-17 19:26:09 -05:00

351 lines
12 KiB
TypeScript

/**
* CodeGraph Interactive Installer
*
* Multi-target: writes MCP server config + instructions for the
* agents the user picks (Claude Code, Cursor, Codex CLI, opencode).
* Defaults to the Claude-only behavior for backwards compatibility
* when no targets are explicitly chosen and nothing else is detected.
*
* Uses @clack/prompts for the interactive UI; `runInstallerWithOptions`
* is the non-interactive entry point used by the `--target` /
* `--print-config` CLI flags.
*/
import { execSync } from 'child_process';
import * as path from 'path';
import * as fs from 'fs';
import {
ALL_TARGETS,
detectAll,
getTarget,
resolveTargetFlag,
} from './targets/registry';
import type { AgentTarget, Location, WriteResult } from './targets/types';
// Backwards-compat: keep these named exports — downstream code may
// import them. The shim in `config-writer.ts` continues to re-export
// them too.
export {
writeMcpConfig,
writePermissions,
writeClaudeMd,
hasMcpConfig,
hasPermissions,
hasClaudeMdSection,
} from './config-writer';
export type { InstallLocation } from './config-writer';
// Dynamic import helper — tsc compiles import() to require() in CJS mode,
// which fails for ESM-only packages. This bypasses the transformation.
// eslint-disable-next-line @typescript-eslint/no-implied-eval
const importESM = new Function('specifier', 'return import(specifier)') as
(specifier: string) => Promise<typeof import('@clack/prompts')>;
function formatNumber(n: number): string {
return n.toLocaleString();
}
function getVersion(): string {
try {
const packageJsonPath = path.join(__dirname, '..', '..', 'package.json');
const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf-8'));
return packageJson.version;
} catch {
return '0.0.0';
}
}
export interface RunInstallerOptions {
/** Comma-separated target list, or `auto` / `all` / `none`. */
target?: string;
/** Skip the location prompt; use this value directly. */
location?: Location;
/** Skip the auto-allow prompt; use this value directly. */
autoAllow?: boolean;
/**
* Skip every confirm and use defaults: location=global,
* autoAllow=true, target=auto. For scripting / CI.
*/
yes?: boolean;
}
/**
* Interactive entry point — preserves the historical UX (`codegraph
* install` with no args goes through the prompts), but now starts
* the targets multi-select pre-populated with detected agents.
*/
export async function runInstaller(): Promise<void> {
return runInstallerWithOptions({});
}
export async function runInstallerWithOptions(opts: RunInstallerOptions): Promise<void> {
const clack = await importESM('@clack/prompts');
clack.intro(`CodeGraph v${getVersion()}`);
// --yes implies all defaults; explicit flags still win.
const useDefaults = opts.yes === true;
// Step 1: which agent targets? Asked FIRST so the user knows what
// they're committing to before we touch npm or disk. Detection
// probes the user-provided location if known, else 'global' as the
// most common default — labels are a hint, not load-bearing.
const detectionLocation: Location = opts.location ?? 'global';
const targets = await resolveTargets(clack, opts, detectionLocation, useDefaults);
if (targets.length === 0) {
clack.outro('No agent targets selected — nothing to do.');
return;
}
// Step 2: install the codegraph npm package on PATH (always offered;
// matches existing behavior). Skipped when --yes (assume present).
if (!useDefaults) {
const shouldInstallGlobally = await clack.confirm({
message: 'Install the codegraph CLI on your PATH? (Required so agents can launch the MCP server)',
initialValue: true,
});
if (clack.isCancel(shouldInstallGlobally)) {
clack.cancel('Installation cancelled.');
process.exit(0);
}
if (shouldInstallGlobally) {
const s = clack.spinner();
s.start('Installing codegraph CLI...');
try {
execSync('npm install -g @colbymchenry/codegraph', { stdio: 'pipe' });
s.stop('Installed codegraph CLI on PATH');
} catch {
s.stop('Could not install (permission denied)');
clack.log.warn('Try: sudo npm install -g @colbymchenry/codegraph');
}
} else {
clack.log.info('Skipped CLI install — agents will not be able to launch the MCP server without it');
}
}
// Step 3: where the per-agent config files should land.
let location: Location;
if (opts.location) {
location = opts.location;
} else if (useDefaults) {
location = 'global';
} else {
// If every selected target is global-only (e.g. Codex), skip the
// prompt and force user-wide — project-local would just produce
// skip warnings.
const allGlobalOnly = targets.every((t) => !t.supportsLocation('local'));
if (allGlobalOnly) {
location = 'global';
clack.log.info('Writing user-wide configs (selected agents have no project-local config).');
} else {
const sel = await clack.select({
message: 'Apply agent configs to all your projects, or just this one?',
options: [
{ value: 'global' as const, label: 'All projects', hint: '~/.claude, ~/.cursor, etc.' },
{ value: 'local' as const, label: 'Just this project', hint: './.claude, ./.cursor, etc.' },
],
initialValue: 'global' as const,
});
if (clack.isCancel(sel)) {
clack.cancel('Installation cancelled.');
process.exit(0);
}
location = sel;
}
}
// Step 4: auto-allow permissions (only meaningful for Claude;
// skipped silently by other targets).
let autoAllow: boolean;
if (opts.autoAllow !== undefined) {
autoAllow = opts.autoAllow;
} else if (useDefaults) {
autoAllow = true;
} else if (targets.some((t) => t.id === 'claude')) {
const ans = await clack.confirm({
message: 'Auto-allow CodeGraph commands? (Skips permission prompts in Claude Code)',
initialValue: true,
});
if (clack.isCancel(ans)) {
clack.cancel('Installation cancelled.');
process.exit(0);
}
autoAllow = ans;
} else {
autoAllow = false;
}
// Step 5: per-target install loop.
for (const target of targets) {
if (!target.supportsLocation(location)) {
clack.log.warn(
`${target.displayName}: skipped — does not support --location=${location}.`,
);
continue;
}
const result = target.install(location, { autoAllow });
for (const file of result.files) {
const verb = file.action === 'unchanged'
? 'Unchanged'
: file.action === 'created' ? 'Created' : 'Updated';
clack.log.success(`${target.displayName}: ${verb} ${tildify(file.path)}`);
}
for (const note of result.notes ?? []) {
clack.log.info(`${target.displayName}: ${note}`);
}
}
// Step 6: for local install, initialize the project.
if (location === 'local') {
await initializeLocalProject(clack);
}
if (location === 'global') {
clack.note('cd your-project\ncodegraph init -i', 'Quick start');
}
const finalNote = targets.length > 0
? `Done! Restart your agent${targets.length > 1 ? 's' : ''} to use CodeGraph.`
: 'Done!';
clack.outro(finalNote);
}
/**
* For every target that has a global config and exposes
* `wireProjectSurfaces`, write its project-local surfaces (e.g.
* Cursor's `.cursor/rules/codegraph.mdc`). Idempotent — runs
* silently when there's nothing to write.
*
* Called by `codegraph init` so that a user who ran
* `codegraph install` once globally doesn't have to re-run it per
* project to get full agent support.
*
* Returns the list of `(target, file)` pairs that were created or
* updated — caller decides how to surface them.
*/
export function wireProjectSurfacesForGlobalAgents(): Array<{
target: AgentTarget;
file: WriteResult['files'][number];
}> {
const written: Array<{ target: AgentTarget; file: WriteResult['files'][number] }> = [];
for (const target of ALL_TARGETS) {
if (typeof target.wireProjectSurfaces !== 'function') continue;
const detection = target.detect('global');
if (!detection.alreadyConfigured) continue;
const result = target.wireProjectSurfaces();
for (const file of result.files) {
if (file.action === 'created' || file.action === 'updated') {
written.push({ target, file });
}
}
}
return written;
}
/**
* Replace home-directory prefix in a path with `~/` for cleaner log
* lines. Pure cosmetic.
*/
function tildify(p: string): string {
const home = require('os').homedir();
if (p.startsWith(home + path.sep)) return '~' + p.substring(home.length);
return p;
}
async function resolveTargets(
clack: typeof import('@clack/prompts'),
opts: RunInstallerOptions,
location: Location,
useDefaults: boolean,
): Promise<AgentTarget[]> {
// Explicit --target flag wins.
if (opts.target !== undefined) {
return resolveTargetFlag(opts.target, location);
}
// --yes implies auto-detect.
if (useDefaults) {
return resolveTargetFlag('auto', location);
}
// Interactive multi-select.
const detected = detectAll(location);
const initialValues = detected
.filter(({ detection }) => detection.installed)
.map(({ target }) => target.id);
// If nothing detected, default to Claude alone (matches the
// historical default and the smallest-surprise outcome).
const initial = initialValues.length > 0 ? initialValues : ['claude'];
const choice = await clack.multiselect<string>({
message: 'Which agents should CodeGraph configure?',
options: ALL_TARGETS.map((t) => {
const det = detected.find(({ target }) => target.id === t.id)!.detection;
const flag = det.installed ? '(detected)' : '(not found)';
const globalOnly = !t.supportsLocation('local') ? ' — global only' : '';
return {
value: t.id,
label: `${t.displayName} ${flag}${globalOnly}`,
};
}),
initialValues: initial,
required: false,
});
if (clack.isCancel(choice)) {
clack.cancel('Installation cancelled.');
process.exit(0);
}
return choice
.map((id) => getTarget(id))
.filter((t): t is AgentTarget => t !== undefined);
}
/**
* Initialize CodeGraph in the current project (for local installs).
* Unchanged from the pre-refactor version — agent-agnostic by nature.
*/
async function initializeLocalProject(clack: typeof import('@clack/prompts')): Promise<void> {
const projectPath = process.cwd();
let CodeGraph: typeof import('../index').default;
try {
CodeGraph = (await import('../index')).default;
} catch (err) {
const msg = err instanceof Error ? err.message : String(err);
clack.log.error(`Could not load native modules: ${msg}`);
clack.log.info('Skipping project initialization. Run "codegraph init -i" later.');
return;
}
// Check if already initialized
if (CodeGraph.isInitialized(projectPath)) {
clack.log.info('CodeGraph already initialized in this project');
return;
}
// Initialize
const cg = await CodeGraph.init(projectPath);
clack.log.success('Created .codegraph/ directory');
// Index the project with shimmer progress (worker thread for smooth animation)
const { createShimmerProgress } = await import('../ui/shimmer-progress');
process.stdout.write(`\x1b[2m│\x1b[0m\n`);
const progress = createShimmerProgress();
const result = await cg.indexAll({
onProgress: progress.onProgress,
});
await progress.stop();
if (result.filesErrored > 0) {
clack.log.success(`Indexed ${formatNumber(result.filesIndexed)} files (${formatNumber(result.filesErrored)} failed, ${formatNumber(result.nodesCreated)} symbols)`);
} else {
clack.log.success(`Indexed ${formatNumber(result.filesIndexed)} files (${formatNumber(result.nodesCreated)} symbols)`);
}
cg.close();
}