Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,10 @@ and adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).

- `codegraph-vba upgrade` no longer rewrites agent instruction files, MCP entries or the Claude prompt hook by default. Add `--refresh-agents` to refresh them. (#332)

### New Features

- Windows: `scripts/compat/install-codegraph-shim.ps1` builds and installs a canonical `codegraph` launcher that resolves to the installed `@aroman22/codegraph-vba` package, for tools that expect the `codegraph` command (such as gentle-ai). It takes structured argv (no `cmd /c`), honours an absolute `CODEGRAPH_NPM_SHIM`, never hangs on a stalled npm, keeps your existing user `PATH` entries intact when adding itself, and tells you to stop a running MCP server if it cannot replace an in-use `codegraph.exe`.

### Fixes

- `install` no longer adds a CodeGraph block to an agent instruction file that gentle-ai manages, and reports that file as skipped. A CodeGraph block left in such a file by an earlier install stays there; remove it by hand. (#332)
Expand Down
14 changes: 14 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -152,6 +152,20 @@ codegraph-vba uninstall

---

### Canonical `codegraph` shim (Windows)

The fork's npm binary is `codegraph-vba`. Tools that expect the canonical `codegraph` command (for example the gentle-ai installer) can use a small launcher that resolves `codegraph` to the installed `@aroman22/codegraph-vba` package:

```powershell
pwsh scripts/compat/install-codegraph-shim.ps1
```

The script builds `scripts/compat/codegraph-launcher.go` (Go required) into `%LOCALAPPDATA%\codegraph-vba-compat\bin` (override with `CODEGRAPH_SHIM_DIR`) and appends that directory to your user `PATH` if it is not already there, keeping your existing `PATH` entries (including `%VAR%` ones) unchanged. The launcher finds the package through `npm root -g` first (given up after 2 seconds), then common npm/pnpm install locations. Set `CODEGRAPH_NPM_SHIM` to an absolute `npm-shim.js` path to override the lookup; a relative path is rejected.

- **Another `codegraph` wins?** The directory is appended, so a `codegraph` found earlier on `PATH` takes precedence. Check with `where.exe codegraph`; remove or uninstall the other one, or move the `codegraph-vba-compat\bin` entry above it in your user `PATH` (Environment Variables dialog).
- **Access denied when re-running?** A running `codegraph` (an MCP server started by your agent) is holding `codegraph.exe`. Close the agent or stop that MCP server, then run the script again.
- **Removal:** delete the directory (`Remove-Item -Recurse "$env:LOCALAPPDATA\codegraph-vba-compat"`) and remove the `codegraph-vba-compat\bin` entry from your user `Path` in *Settings → System → About → Advanced system settings → Environment Variables*, then restart your terminal.

## Why CodeGraph?

When an AI agent needs to understand code — to answer a question or make a change — it discovers structure the slow way: grep, glob, and Read, one file at a time, rebuilding call paths and dependencies by hand. That's a pile of tool calls and round-trips before it even starts the real work.
Expand Down
191 changes: 191 additions & 0 deletions scripts/compat/codegraph-launcher.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,191 @@
// codegraph-launcher — Compatibility shim that resolves the canonical `codegraph`
// CLI to the user's installed @aroman22/codegraph-vba fork (npm or pnpm) without
// relying on broken symlinks to the fork's working tree.
//
// Search order (first match wins):
// 1. %CODEGRAPH_NPM_SHIM% — must be an absolute path; a relative value is
// rejected. When set, it is authoritative: an unusable value is an error.
// 2. `npm root -g` + /@aroman22/codegraph-vba/npm-shim.js — the CURRENT global
// install. Bounded by a 2s timeout; on timeout or error the launcher falls
// through to the fixed candidates. It runs first on purpose so a stale old
// install under %USERPROFILE%\node_modules never wins over it.
// 3. Fixed candidates: %APPDATA%\npm, pnpm global, %USERPROFILE%\node_modules,
// then common Linux / macOS prefixes.
//
// Every candidate is verified with os.Stat and resolved with
// filepath.EvalSymlinks, so dead symlinks are skipped and node receives the real
// path. node is resolved via exec.LookPath so the user's PATH wins; no shell, no
// cmd.exe double-expansion. Exit codes are propagated verbatim so MCP server
// failures surface as MCP errors, not silent 0.
package main

import (
"context"
"fmt"
"os"
"os/exec"
"path/filepath"
"strings"
"time"
)

// npmRootTimeout bounds `npm root -g` so a stalled npm never hangs the MCP server.
const npmRootTimeout = 2 * time.Second

// npmRootWaitDelay bounds how long we wait for npm's pipes after the timeout
// kills it. On Windows npm is npm.cmd -> cmd.exe -> node; killing cmd.exe leaves
// node holding stdout open, and without WaitDelay Output() would block on it.
const npmRootWaitDelay = 500 * time.Millisecond

func main() {
npmShim, err := findNpmShim()
if err != nil {
fmt.Fprintf(os.Stderr, "codegraph compatibility error: %v\n", err)
os.Exit(9009)
}

node, err := exec.LookPath("node")
if err != nil {
// On Windows, LookPath("node") still finds node.exe via PATHEXT, so this
// error path is the same on every platform: the user has no Node runtime
// on PATH at all.
fmt.Fprintln(os.Stderr, "codegraph compatibility error: node was not found on PATH.")
os.Exit(9009)
}

child := exec.Command(node, append([]string{npmShim}, os.Args[1:]...)...)
child.Stdin = os.Stdin
child.Stdout = os.Stdout
child.Stderr = os.Stderr
child.Env = os.Environ()
if dir, derr := os.Getwd(); derr == nil {
child.Dir = dir
}

if err := child.Run(); err != nil {
if exitErr, ok := err.(*exec.ExitError); ok {
os.Exit(exitErr.ExitCode())
}
fmt.Fprintf(os.Stderr, "codegraph compatibility error: %v\n", err)
os.Exit(1)
}
}

// shimLookup holds the inputs of the shim search so tests can inject them.
type shimLookup struct {
home string
override string
npmRoot func() (string, error)
}

func findNpmShim() (string, error) {
home, herr := os.UserHomeDir()
if herr != nil || home == "" {
home = os.Getenv("USERPROFILE")
}
return shimLookup{
home: home,
override: strings.TrimSpace(os.Getenv("CODEGRAPH_NPM_SHIM")),
npmRoot: discoverNpmRoot,
}.find()
}

func (l shimLookup) find() (string, error) {
if l.override != "" {
if !filepath.IsAbs(l.override) {
return "", fmt.Errorf("CODEGRAPH_NPM_SHIM must be an absolute path to npm-shim.js, got %q", l.override)
}
resolved, ok, err := resolveShim(l.override)
if err != nil {
return "", fmt.Errorf("CODEGRAPH_NPM_SHIM=%s: %w", l.override, err)
}
if ok {
return resolved, nil
}
}

if l.home == "" {
return "", fmt.Errorf("could not resolve user home directory")
}

// First try the real npm global root via `npm root -g`. This respects any
// custom npm prefix and keeps a stale install at a fixed path from winning.
if l.npmRoot != nil {
if npmRoot, err := l.npmRoot(); err == nil && npmRoot != "" {
if shim, ok, _ := resolveShim(filepath.Join(npmRoot, "@aroman22", "codegraph-vba", "npm-shim.js")); ok {
return shim, nil
}
}
}

home := l.home
candidates := []string{
// Windows
filepath.Join(home, "AppData", "Roaming", "npm", "node_modules", "@aroman22", "codegraph-vba", "npm-shim.js"),
filepath.Join(home, "AppData", "Local", "pnpm", "global", "5", "node_modules", "@aroman22", "codegraph-vba", "npm-shim.js"),
filepath.Join(home, "node_modules", "@aroman22", "codegraph-vba", "npm-shim.js"),
// Linux / macOS
filepath.Join(home, ".npm-global", "lib", "node_modules", "@aroman22", "codegraph-vba", "npm-shim.js"),
filepath.Join(home, ".local", "lib", "node_modules", "@aroman22", "codegraph-vba", "npm-shim.js"),
filepath.Join(home, ".npm", "lib", "node_modules", "@aroman22", "codegraph-vba", "npm-shim.js"),
"/usr/local/lib/node_modules/@aroman22/codegraph-vba/npm-shim.js",
"/usr/lib/node_modules/@aroman22/codegraph-vba/npm-shim.js",
}

for _, raw := range candidates {
resolved, ok, err := resolveShim(raw)
if err != nil {
continue
}
if ok {
return resolved, nil
}
}

return "", fmt.Errorf("npm-shim.js not found for @aroman22/codegraph-vba. Tried: npm root -g; %s", strings.Join(candidates, "; "))
}

func discoverNpmRoot() (string, error) {
npm, err := exec.LookPath("npm")
if err != nil {
return "", err
}
return npmRootVia(npm, npmRootTimeout)
}

// npmRootVia runs `<npm> root -g` and gives up after timeout.
func npmRootVia(npm string, timeout time.Duration) (string, error) {
ctx, cancel := context.WithTimeout(context.Background(), timeout)
defer cancel()
cmd := exec.CommandContext(ctx, npm, "root", "-g")
cmd.WaitDelay = npmRootWaitDelay
out, err := cmd.Output()
if ctx.Err() != nil {
return "", fmt.Errorf("npm root -g timed out after %s", timeout)
}
if err != nil {
return "", err
}
return strings.TrimSpace(string(out)), nil
}

func resolveShim(path string) (string, bool, error) {
info, err := os.Stat(path)
if err != nil {
return "", false, err
}
if info.IsDir() {
return "", false, fmt.Errorf("%s is a directory", path)
}
resolved, err := filepath.EvalSymlinks(path)
if err != nil {
// Stat followed the path, so this is unexpected; fall back to the
// original path because the launcher still needs to error cleanly.
return path, true, nil
}
if rinfo, serr := os.Stat(resolved); serr != nil || rinfo.IsDir() {
// Symlink target is broken or a directory; treat as missing.
return "", false, fmt.Errorf("symlink target %q is unusable", resolved)
}
return resolved, true, nil
}
137 changes: 137 additions & 0 deletions scripts/compat/codegraph-launcher_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,137 @@
package main

import (
"errors"
"os"
"path/filepath"
"runtime"
"strings"
"testing"
"time"
)

func writeShim(t *testing.T, path string) string {
t.Helper()
if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(path, []byte("// stub\n"), 0o644); err != nil {
t.Fatal(err)
}
real, err := filepath.EvalSymlinks(path)
if err != nil {
t.Fatal(err)
}
return real
}

func shimUnder(root string) string {
return filepath.Join(root, "@aroman22", "codegraph-vba", "npm-shim.js")
}

// sleepingNpm writes a stub `npm` that sleeps far longer than any test timeout.
// On Windows it is a .cmd whose grandchild (ping) inherits stdout, mirroring
// npm.cmd -> cmd.exe -> node.
func sleepingNpm(t *testing.T) string {
t.Helper()
dir := t.TempDir()
if runtime.GOOS == "windows" {
p := filepath.Join(dir, "npm.cmd")
if err := os.WriteFile(p, []byte("@echo off\r\nping -n 30 127.0.0.1\r\n"), 0o755); err != nil {
t.Fatal(err)
}
return p
}
p := filepath.Join(dir, "npm")
if err := os.WriteFile(p, []byte("#!/bin/sh\nsleep 30\n"), 0o755); err != nil {
t.Fatal(err)
}
return p
}

func TestRelativeOverrideIsRejected(t *testing.T) {
_, err := shimLookup{home: t.TempDir(), override: filepath.Join("rel", "npm-shim.js")}.find()
if err == nil || !strings.Contains(err.Error(), "CODEGRAPH_NPM_SHIM must be an absolute path") {
t.Fatalf("expected absolute-path error, got %v", err)
}
}

func TestAbsoluteOverrideResolvesSymlinks(t *testing.T) {
dir := t.TempDir()
real := writeShim(t, filepath.Join(dir, "real", "npm-shim.js"))
link := filepath.Join(dir, "link.js")
if err := os.Symlink(real, link); err != nil {
t.Skipf("symlink creation not permitted here: %v", err)
}
got, err := shimLookup{home: dir, override: link}.find()
if err != nil {
t.Fatal(err)
}
if got != real {
t.Fatalf("got %q, want resolved target %q", got, real)
}
}

func TestMissingAbsoluteOverrideIsAnError(t *testing.T) {
dir := t.TempDir()
_, err := shimLookup{home: dir, override: filepath.Join(dir, "missing.js")}.find()
if err == nil || !strings.Contains(err.Error(), "CODEGRAPH_NPM_SHIM=") {
t.Fatalf("expected override error, got %v", err)
}
}

func TestNpmRootWinsOverStaleCandidate(t *testing.T) {
home := t.TempDir()
writeShim(t, shimUnder(filepath.Join(home, "node_modules"))) // stale install
globalRoot := t.TempDir()
want := writeShim(t, shimUnder(globalRoot))
got, err := shimLookup{home: home, npmRoot: func() (string, error) { return globalRoot, nil }}.find()
if err != nil {
t.Fatal(err)
}
if got != want {
t.Fatalf("got %q, want npm root -g shim %q", got, want)
}
}

func TestNpmRootErrorFallsThroughToCandidates(t *testing.T) {
home := t.TempDir()
want := writeShim(t, shimUnder(filepath.Join(home, "AppData", "Roaming", "npm", "node_modules")))
got, err := shimLookup{home: home, npmRoot: func() (string, error) { return "", errors.New("boom") }}.find()
if err != nil {
t.Fatal(err)
}
if got != want {
t.Fatalf("got %q, want %q", got, want)
}
}

func TestSleepingNpmTimesOutWithoutHanging(t *testing.T) {
npm := sleepingNpm(t)
start := time.Now()
_, err := npmRootVia(npm, 300*time.Millisecond)
elapsed := time.Since(start)
if err == nil || !strings.Contains(err.Error(), "timed out") {
t.Fatalf("expected timeout error, got %v", err)
}
if elapsed > 5*time.Second {
t.Fatalf("npmRootVia hung for %s", elapsed)
}
}

func TestNpmTimeoutFallsThroughToCandidates(t *testing.T) {
npm := sleepingNpm(t)
home := t.TempDir()
want := writeShim(t, shimUnder(filepath.Join(home, "node_modules")))
start := time.Now()
got, err := shimLookup{home: home, npmRoot: func() (string, error) { return npmRootVia(npm, 300*time.Millisecond) }}.find()
if err != nil {
t.Fatal(err)
}
if got != want {
t.Fatalf("got %q, want %q", got, want)
}
if elapsed := time.Since(start); elapsed > 5*time.Second {
t.Fatalf("lookup hung for %s", elapsed)
}
}
3 changes: 3 additions & 0 deletions scripts/compat/go.mod
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
module github.com/ardelperal/codegraph-vba/scripts/compat

go 1.22
Loading