agents/openai.yaml
interface:
display_name: "CodeGraph + ast-grep"
short_description: "Set up, update, or diagnose semantic and structural tooling"
icon_small: "./assets/openai-icon.png"
icon_large: "./assets/openai-icon.png"
default_prompt: "Use $codegraph-ast-grep for my request. When intent, root, scope, and authority are clear, announce only the selected setup, update, or doctor workflow and its rationale, do not enumerate unselected workflows, and proceed. For a bare or materially ambiguous request or an explicit options request, show setup, update, and doctor in order and ask only when a choice is needed. An options-only request authorizes no repository or tool inspection and no execution. Preserve installer provenance and protected state, keep doctor non-repairing, require exact-root approval before graph diagnostics that may migrate metadata, and persist repository guidance after setup."
policy:
products:
- CODEX
allow_implicit_invocation: false
references/ast-grep-rule-recipes.md
# ast-grep Rule Recipes
Use this reference for structural search, reusable rules/tests, outline, or a reviewed rewrite. Verify installed help before using any version-sensitive option.
These are internal coding behaviors after a ready setup, not public skill workflows. An ordinary coding request may authorize a bounded rule or source edit; broad, destructive, or scope-expanding rewrites retain their normal approval boundary.
## Contents
- [Capability and quoting checks](#capability-and-quoting-checks)
- [Narrow patterns](#narrow-patterns)
- [Result bounding](#result-bounding)
- [Reusable YAML rules](#reusable-yaml-rules)
- [Positive and negative tests](#positive-and-negative-tests)
- [Outline](#outline)
- [Rewrite sequence](#rewrite-sequence)
- [Debugging misses](#debugging-misses)
## Capability and quoting checks
```bash
ast-grep --version
ast-grep --help
ast-grep run --help 2>/dev/null || true
ast-grep scan --help 2>/dev/null || true
ast-grep test --help 2>/dev/null || true
ast-grep outline --help 2>/dev/null || true
```
Use single quotes around shell patterns containing `$` metavariables:
```bash
ast-grep run -p 'console.log($$$ARGS)' -l ts src
```
Double quotes can expand `$NAME` before ast-grep sees it. On Linux use `ast-grep`, not the ambiguous `sg` command.
## Narrow patterns
Find React hooks with empty dependency arrays:
```bash
ast-grep run -p 'useEffect($FN, [])' -l tsx src
```
Find direct environment reads:
```bash
ast-grep run -p 'process.env.$KEY' -l ts src
```
Find a named import source while capturing imported bindings:
```bash
ast-grep run -p 'import { $$$NAMES } from "$PKG"' -l ts src
```
Find a function call regardless of arguments:
```bash
ast-grep run -p 'deprecatedApi($$$ARGS)' -l ts packages/target
```
Start against one known file, then one directory, then the approved repository scope. Specify `-l` when extension inference is ambiguous or input comes from stdin.
Before claiming coverage, inventory syntax variants such as namespace/default imports, aliases, optional chaining, JSX/TSX, wrappers, computed properties, macros, and generated sources.
## Result bounding
No result-limit flag is universal across every ast-grep subcommand/version.
Bound `run` by exact paths, language, and include/exclude globs exposed by installed help. Use JSON only when downstream processing is useful:
```bash
ast-grep run -p 'process.env.$KEY' -l ts --json=stream src/server
```
For `scan`, use `--max-results` only when `ast-grep scan --help` exposes it:
```bash
ast-grep scan --rule rules/no-direct-env.yml --max-results 100 src
```
Report total/representative results without pasting hundreds of lines. If a limit truncates output, say so and do not present the sample as full coverage.
## Reusable YAML rules
Minimal rule:
```yaml
id: no-direct-env-read
message: Read environment values through the approved configuration boundary.
severity: warning
language: TypeScript
rule:
pattern: process.env.$KEY
```
Relational rule—find an awaited expression inside `Promise.all`:
```yaml
id: no-await-inside-promise-all
message: Build promises before passing them to Promise.all.
severity: warning
language: TypeScript
rule:
pattern: Promise.all($ARGS)
has:
pattern: await $_
stopBy: end
```
Composite rule—find server-action functions that call `revalidatePath`:
```yaml
id: server-action-revalidate-path
message: Review cache invalidation from server actions.
severity: warning
language: TypeScript
rule:
all:
- pattern: async function $NAME($$$ARGS) { $$$BODY }
- has:
pattern: "'use server'"
stopBy: end
- has:
pattern: revalidatePath($$$ARGS)
stopBy: end
```
Use YAML when relational/composite logic, shared utilities, CI reuse, messages, or rule tests justify committed configuration. Do not create rule/config files for a one-off ad-hoc pattern unless the user asks.
## Positive and negative tests
Configure rule and test directories in an existing or approved `sgconfig.yml`:
```yaml
ruleDirs:
- rules
testConfigs:
- testDir: rule-tests
```
Match the test `id` to the rule:
```yaml
id: no-direct-env-read
valid:
- config.read('DATABASE_URL')
- const env = getValidatedEnvironment()
invalid:
- process.env.DATABASE_URL
- const url = process.env['DATABASE_URL']
```
The second invalid example may reveal that the first rule does not cover computed access. Refine the rule or document the unsupported variant; do not call the rule complete while a known invalid fixture fails.
Run tests without accepting changed snapshots automatically:
```bash
ast-grep test --skip-snapshot-tests
ast-grep test
```
If snapshots are intentional, inspect them interactively and review the diff. Never use a snapshot update-all flag as routine validation or as proof that changed output is correct.
## Outline
Use outline only when installed help exposes it. It is a lightweight structural fallback, not semantic call analysis.
```bash
ast-grep outline src/parser.ts --view digest
ast-grep outline src --type class,function --match Parser
ast-grep outline src --json=stream
```
If `outline` is absent, use runtime-native LSP symbols, a narrower ast-grep pattern, or targeted file reads. Do not require an update solely to obtain outline when the existing path is sufficient; offer the stable update through the normal itemized checkpoint.
## Rewrite sequence
Use this exact order:
1. **Match inventory:** identify every known syntax variant and the exact paths in scope.
2. **Positive/negative test:** prove intended matches and non-matches.
3. **Preview:** run match-only and record count plus representative results.
4. **Exact bounded scope:** freeze rule/pattern, language, paths/globs, and expected count.
5. **Explicit consent:** ask for the reviewed rewrite unless the user already approved this exact unchanged scope.
6. **Apply:** use interactive rewrite or create a normal patch; never silently broaden.
7. **Diff review:** inspect every changed file and rerun the match to explain remaining occurrences.
8. **Repository-native validation:** run the actual targeted tests, typecheck, lint, or build.
9. **Rollback:** keep the patch reviewable and use normal version-control reversal only with user authority.
Example preview and interactive rewrite, only after installed help confirms the options:
```bash
ast-grep run -p 'oldApi($ARG)' -l ts src/target
ast-grep run -p 'oldApi($ARG)' -r 'newApi($ARG)' -l ts --interactive src/target
```
Do not run a broad non-interactive rewrite because a pattern matched one sample. Do not treat prior approval as covering a different path, rule, replacement, or count.
## Debugging misses
- Confirm the language (`ts`, `tsx`, `js`, `jsx`, or another installed language id).
- Reduce to one known positive file and the smallest pattern.
- Inspect installed `--debug-query`, `--inspect`, AST-dump, or playground options only when exposed.
- Check whether the desired node is inside embedded/multi-language syntax.
- Add `stopBy: end` only when a relational search should traverse the full enclosing node.
- Compare pattern context: expression versus statement, declaration versus call, and TS versus TSX.
- Add the missed shape to `invalid` fixtures before broadening the repository scan.
## Primary sources
- [ast-grep CLI reference](https://ast-grep.github.io/reference/cli.html)
- [Test rules](https://ast-grep.github.io/guide/test-rule.html)
- [Outline reference](https://ast-grep.github.io/reference/cli/outline.html)
references/codegraph-capability-guide.md
# CodeGraph Capability Guide
Use this reference for semantic exploration, graph freshness, current/legacy command selection, or CodeGraph project-root issues. The installed executable and exposed MCP tools are the command contract.
Use it only for a known repository root. In `doctor`, project-opening diagnostics still need exact-root approval because generated metadata may migrate. A selected `setup` or `update` workflow already covers required in-root initialization/migration when that write scope was announced.
Reviewed command baseline: CodeGraph 1.4.1 on 2026-07-12. A [v1.6.2 release-note check](https://github.com/colbymchenry/codegraph/releases/tag/v1.6.2) was made on 2026-10-29; it is not a live command or project-index test. Neither date sets a runtime version floor. Verify installed help and MCP exposure before using a version-specific capability.
## Contents
- [Discover capabilities](#discover-capabilities)
- [Select MCP or CLI behavior](#select-mcp-or-cli-behavior)
- [Initialize and keep the graph fresh](#initialize-and-keep-the-graph-fresh)
- [Choose the project root](#choose-the-project-root)
- [Use optional project configuration](#use-optional-project-configuration)
- [Bound and qualify evidence](#bound-and-qualify-evidence)
## Discover capabilities
Start with commands reviewed across legacy and current releases:
```bash
codegraph --version
codegraph --help
```
`codegraph status`, MCP graph queries, and other project-opening diagnostics can migrate generated index metadata in some versions. Explain the generated-state boundary and obtain affirmative approval for the selected root, or use an approved disposable graph copy. Under a strict no-write instruction, stop at version/help and filesystem/config inspection unless the disposable-copy path was approved. After approval, run only the needed command, for example:
```bash
codegraph status
```
Then inspect only the help needed for the task:
```bash
codegraph help init 2>/dev/null || true
codegraph help install 2>/dev/null || true
codegraph help explore 2>/dev/null || true
codegraph help query 2>/dev/null || true
codegraph help context 2>/dev/null || true
codegraph help callers 2>/dev/null || true
codegraph help callees 2>/dev/null || true
codegraph help impact 2>/dev/null || true
codegraph help affected 2>/dev/null || true
codegraph help node 2>/dev/null || true
codegraph help files 2>/dev/null || true
```
Do not infer support from version alone. Record each capability as `available`, `absent`, or `not verified`.
Typical capability branches:
| Need | Preferred when discovered | Degraded/legacy branch |
| ---------------------------------- | -------------------------------- | -------------------------------------------------------------- |
| Natural-language semantic question | Exposed MCP `codegraph_explore` | CLI `codegraph explore`, then help-confirmed `context`/`query` |
| Symbol/source details | Consolidated explore result | Help-confirmed `node` or targeted source read |
| Call relationships | Consolidated explore call paths | Help-confirmed `callers`/`callees` |
| Blast radius/tests | Consolidated explore result | Help-confirmed `impact`/`affected` plus project tests |
| File inventory | Explore result or targeted reads | Help-confirmed `files` |
| No usable CodeGraph path | Runtime-native LSP | ast-grep outline/structural search, then bounded text search |
## Select MCP or CLI behavior
Enumerate the runtime's actual CodeGraph MCP tools before calling one. Tool enumeration itself does not authorize a graph query; reuse the selected-root or disposable-copy approval from the project-opening gate above.
- If `codegraph_explore` is exposed, use it first for semantic questions.
- If it is not exposed, use only the granular MCP tools that are present.
- If MCP is unavailable, use `codegraph explore` only when installed CLI help lists it.
- On a legacy CLI without `explore`, use help-confirmed `context`, `query`, `callers`, `callees`, `impact`, `affected`, `node`, or `files` as needed.
- Never assume a remembered MCP tool such as `codegraph_trace` exists.
Ask one focused semantic question. Avoid repeating a successful consolidated result through every granular operation. Use a narrow follow-up only for missing evidence or a decision that affects the patch.
Example, only after installed help confirms the command:
```bash
codegraph explore "How does request validation reach persistence?"
```
Legacy examples must remain capability-gated:
```bash
# Run only when installed help lists these commands/options.
codegraph query ValidationService
codegraph callers ValidationService
codegraph impact ValidationService
```
Treat semantic results as an index-backed hypothesis, not compiler proof. Read the exact source before editing and run project-native checks afterward.
## Initialize and keep the graph fresh
Do not infer initialization from state-directory existence alone. Record the selected project root and effective state directory (`CODEGRAPH_DIR`, default `.codegraph`) together.
```bash
codegraph help init
```
After the generated-state boundary is affirmatively approved for the selected root, or an approved disposable copy is selected, use `codegraph status` to inspect initialization and freshness. Run it with the same effective `CODEGRAPH_DIR` and executable provenance as the MCP server. Do not substitute disclosure alone for approval.
After approval, use the installed form:
```bash
# Current help may say init builds the initial graph directly.
codegraph init
# Help-confirmed legacy form only.
codegraph init -i
```
Do not globally ban the legacy `-i` form and do not make it the unconditional default.
Freshness depends on how CodeGraph is running:
| State | Appropriate behavior |
| ------------------------------------------------------------ | --------------------------------------------------------------------------------- |
| Active MCP server with watcher and no pending/stale evidence | Trust watcher/connect-sync; do not run manual sync ceremonially |
| Pending files reported | Wait for debounce or use targeted source; sync only if the pending state persists |
| CLI/script outside an agent session | An approved pre-flight `codegraph sync` may be appropriate |
| Watcher disabled/blocked or `CODEGRAPH_NO_DAEMON=1` | Use approved manual sync before relying on graph results |
| Config/extraction engine changed or graph is corrupt | Inspect help/status and propose the minimum sync or full re-index separately |
Auto-sync is conditional on an active supported watcher. Manual sync remains valid for CLI-only workflows, disabled watchers, CI/scripts, persistent stale state, and recovery.
Never delete the effective state directory as the first repair. Preserve it, inspect approved status/log evidence, and ask before sync, index, uninit, or removal.
## Choose the project root
Confirm the root used by both the index and MCP server:
- top-level monorepo versus a package/service root;
- nested Git repositories or submodules;
- linked worktrees that should not be indexed as duplicate source;
- a stable path for project-local MCP config;
- Windows versus WSL ownership of the index.
Use one graph when cross-package relationships are the goal and the repository size/support is reasonable. Use separate graphs when packages are independent, paths/config differ, or a single graph creates irrelevant noise. Report which root was chosen.
Do not point Windows and WSL processes at the same SQLite index. Run the client, CodeGraph, ast-grep, package manager, and repository in one environment or configure separate state directories after approval. For current versions that document `CODEGRAPH_DIR`, use plain project-root names such as `.codegraph-win` for native Windows and `.codegraph-wsl` for WSL; put the matching value in that environment's MCP entry and every CLI invocation. If the installed version does not establish `CODEGRAPH_DIR` support, do not rely on it.
When a client launches MCP from the wrong working directory, pass an approved project path if current server help supports it. Prefer client roots/workspace variables over a public hardcoded absolute path.
## Use optional project configuration
The effective state directory (`CODEGRAPH_DIR`, default `.codegraph/`) is local generated index state. Root `codegraph.json` is optional project configuration in current releases that document it; it does not choose the state directory.
Use no config when defaults are sufficient. Consider `codegraph.json` only for a concrete need such as:
- custom file extensions for a supported language;
- excluding tracked first-party-irrelevant paths;
- including explicitly selected ignored first-party source;
- including selected nested repositories.
Inspect the installed/current configuration schema, show the proposed file/diff, and obtain approval. Some configuration changes require a full index rather than an incremental sync.
Never invent `.codegraph/config.json` and never edit index database/state files directly.
## Bound and qualify evidence
For every semantic result, record:
- project root and graph status/freshness;
- MCP tool or CLI command used;
- relevant symbols/files/call paths;
- unsupported/dynamic/generated boundaries;
- targeted source corroboration;
- what remains unverified.
Use `confirmed` only when graph evidence and targeted source/structural evidence agree. Use `partial` when dynamic dispatch, unsupported languages, stale/pending files, generated code, or missing tools limit coverage. Use `unavailable` when no semantic surface could be verified.
If output is broad, narrow the question, symbol, path, or depth rather than dumping the graph. Do not claim that absence from the graph proves absence from the repository.
## Primary sources
- [CodeGraph v1.6.2 release notes](https://github.com/colbymchenry/codegraph/releases/tag/v1.6.2)
- [CodeGraph 1.4.1 README](https://github.com/colbymchenry/codegraph/blob/v1.4.1/README.md)
- [CodeGraph CLI reference](https://github.com/colbymchenry/codegraph/blob/v1.4.1/site/src/content/docs/reference/cli.md)
- [CodeGraph indexing guide](https://github.com/colbymchenry/codegraph/blob/v1.4.1/site/src/content/docs/guides/indexing.md)
- [CodeGraph configuration](https://github.com/colbymchenry/codegraph/blob/v1.4.1/site/src/content/docs/getting-started/configuration.md)
references/extensions-and-escalation.md
# Extensions and Escalation
CodeGraph and ast-grep are the only core tools. Read this reference only when the core workflow and native runtime capabilities cannot safely express the task. Selecting an extension does not authorize installation or execution.
Use this only after the repository root and core-tool limitation are known. Extension installation or execution is a separately authorized scope expansion and never becomes part of normal `setup`, `update`, or `doctor`.
## Selection order
1. Use existing runtime-native language-server/compiler navigation before adding another semantic server.
2. Use CodeGraph plus ast-grep for normal exploration, impact, structural search, and reviewed rewrites.
3. Select one optional extension only when its threshold below is met.
4. Do not turn optional-extension evaluation into a stable-version lookup for unrelated tools.
5. Apply provenance review, explicit approval, bounded execution, diff review, and project validation to a selected extension.
6. Keep a valid degraded path when the user declines or the extension is unavailable.
## Decision matrix
| Need | Optional choice | Select only when | Do not imply |
| ----------------------------------------------------------------------------------------------- | ------------------- | ----------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------- |
| Symbols/references/types missing from CodeGraph but supported by the project's language tooling | Native LSP/compiler | Already available in the runtime/project | No extra server or install is required |
| Dedicated cross-client symbol navigation or refactoring backend | Serena | Native LSP is unavailable to the agent or a reusable MCP semantic backend is explicitly wanted | Serena is optional, not a CodeGraph prerequisite |
| Multi-step, parameterized, resumable, or programmatic migration | Codemod CLI/JSSG | Declarative ast-grep replacement is insufficient and fixture-tested orchestration adds value | Registry codemods or `npx` are trusted by default |
| Security/taint/policy rule | Semgrep | The request is explicitly security/policy focused and its selected engine can support the required analysis | CodeGraph/ast-grep provide taint proof, or Semgrep CE is automatically interfile proof |
| Complex JavaScript/TypeScript syntax rewrite | jscodeshift | Recast-style JS/TS transform code is more suitable than a declarative rule | It is language-neutral or has an official MCP requirement |
| Type-aware TypeScript transform | ts-morph | The change needs TypeScript compiler/type-checker information | It is a ready-made codemod runner |
| Format-preserving Python migration | LibCST | Python CST fidelity and codemod fixtures are required | It applies outside Python |
| JVM/framework/build migration | OpenRewrite | Java/Kotlin/JVM recipes and type-attributed project builds justify its setup cost | Every recipe/language is covered by the same open-source license |
| Existing indexed enterprise code platform | Sourcegraph/SCIP | The organization already operates it and the task can use that existing index | A new upload/service is needed for ordinary local work |
| Existing Grit/Biome migration rules | Grit | The repository already adopted it and reuse is cheaper than translation | It should be installed as a second default structural engine |
## Preferred advanced migration extension
Codemod CLI with JSSG is the preferred optional advanced extension when a migration needs more than a single ast-grep rule:
- multi-file creation/deletion/moves;
- ordered transformation steps;
- parameters or reusable workflows;
- programmatic ast-grep traversal/transformation;
- fixture-based whole-directory comparison;
- resumable or CI-oriented migration execution.
Before selection, define why ast-grep CLI plus a reviewed patch is insufficient. Before execution, review the exact transform/workflow source, version, requested capabilities, filesystem/network permissions, target paths, fixtures, dry-run behavior, and rollback. Do not execute a registry transform merely from its name or popularity.
## Semantic extension boundary
Prefer native language tools/LSP first. Select Serena only when the agent needs a dedicated MCP-accessible semantic backend across clients or CodeGraph lacks required symbol operations for the language/task.
Serena can expose retrieval and editing tools. Enable only the minimum required tools and keep editing disabled for read-only exploration. Treat its project config, memory, telemetry, package runner, language-server downloads, and shell/edit capabilities as separate trust surfaces. A semantic backend does not replace project typecheck/tests.
## Security/policy boundary
Route explicit vulnerability, taint, organization-policy, or security autofix work to an appropriate security workflow and consider Semgrep only as that workflow's selected analyzer.
- Confirm whether the available engine supports intrafile or interfile analysis needed by the claim.
- Use official/local rules with tests and pin remote rule sources.
- Run match/report mode before autofix.
- Treat autofix as a reviewed rewrite with exact scope and project validation.
- Do not describe absence of a finding as proof of security.
For ordinary structural matching, stay with ast-grep.
## Language-specific specialists
Use a specialist only when its semantic/fidelity advantage is material:
- **jscodeshift:** JS/TS AST transforms with Recast formatting and fixture tests.
- **ts-morph:** TypeScript compiler/type-checker navigation and type-aware manipulation.
- **LibCST:** lossless Python CST transforms and codemod tests.
- **OpenRewrite:** type-attributed JVM/framework/build recipes and recipe tests.
Keep generated transform code in the target repository's normal source/test conventions, not inside this installed skill. Require a dry run or patch preview and project-native validation.
## Existing-adoption-only tools
Sourcegraph/SCIP and Grit may be useful when the repository or organization already depends on them. Do not recommend provisioning an enterprise index, uploading private source, or adding a redundant structural DSL for a normal CodeGraph/ast-grep task.
Do not add Comby, raw Tree-sitter queries, or CodeQL to the general setup:
- Comby overlaps the structural role with a weaker/staler default fit.
- Raw Tree-sitter is grammar/parser infrastructure, not a safe user-facing rewrite workflow.
- CodeQL is a security-analysis platform with database/query setup, not a general refactor dependency.
## Approval and update inheritance
Once an extension is selected:
- include it in the analysis-stack update check exactly once for the task;
- identify its authoritative stable source and installation provenance;
- show an itemized install/update/execute checkpoint;
- preserve project pins and sandbox/capability restrictions;
- do not install another optional tool as its dependency unless separately approved;
- report when the user declines and continue through the core/degraded path.
## Primary sources
- [Serena](https://github.com/oraios/serena)
- [Codemod CLI/JSSG](https://docs.codemod.com/cli)
- [Semgrep documentation](https://semgrep.dev/docs/)
- [jscodeshift](https://github.com/facebook/jscodeshift)
- [ts-morph](https://ts-morph.com/)
- [LibCST codemods](https://libcst.readthedocs.io/en/latest/codemods.html)
- [OpenRewrite](https://docs.openrewrite.org/)
- [GritQL](https://github.com/biomejs/gritql)
references/setup-and-mcp-config.md
# Setup and MCP Configuration
Use this reference for the idempotent `setup` workflow: installation/reconciliation, MCP setup, project initialization, and persisted repository guidance. Use [update-and-provenance.md](update-and-provenance.md) for the `update` workflow.
Precondition: `setup` was selected from clear user intent or explicit choice and the exact root/write scope was announced. That selection covers ordinary in-root package, runtime-config, graph, and guidance reconciliation; privilege escalation, installer-channel/scope changes, telemetry, destructive replacement, and unrelated writes remain separate.
## Contents
- [Setup principles](#setup-principles)
- [Read-only preflight](#read-only-preflight)
- [Choose an installation scope](#choose-an-installation-scope)
- [Install channels](#install-channels)
- [CodeGraph runtime configuration](#codegraph-runtime-configuration)
- [Project initialization and configuration](#project-initialization-and-configuration)
- [ast-grep project setup](#ast-grep-project-setup)
- [Experimental ast-grep MCP](#experimental-ast-grep-mcp)
- [Authorization and verification](#authorization-and-verification)
## Setup principles
1. Prefer a healthy existing install.
2. Discover the installed command surface before choosing examples.
3. Preserve the user's current package manager, installer channel, scope, trust policy, and declarative configuration.
4. Show exact versions, destinations, remote execution, lifecycle scripts, telemetry behavior, and rollback limits before approval. Treat update-network permission and telemetry consent separately; default-on telemetry is not affirmative consent.
5. Keep CLI/package, MCP registration, agent guidance, project initialization, and repository config as separately reported changes even when the selected setup scope authorizes them together.
6. Never install a package manager just to install either tool unless the user asks.
`npx`, `uvx`, package installs, archive extraction, MCP registration, `codegraph install`, graph initialization, configuration writes, and ignore-file edits are side-effectful. Do not run them from diagnostic intent.
## Read-only preflight
Start from the intended project root. Avoid echoing full runtime config or unrelated environment variables; the non-secret CodeGraph state-directory selector is relevant here.
```bash
pwd
git status --short 2>/dev/null || true
printf 'Configured CODEGRAPH_DIR: %s\n' "${CODEGRAPH_DIR:-<default .codegraph>}"
for tool in codegraph ast-grep pnpm npm yarn bun brew port cargo pip pipx uv nix codex cursor-agent claude; do
command -v "$tool" >/dev/null 2>&1 && printf '%s: %s\n' "$tool" "$(command -v "$tool")"
done
```
Probe installed tools without assuming newer subcommands:
```bash
codegraph --version 2>/dev/null || true
codegraph --help 2>/dev/null || true
codegraph help init 2>/dev/null || true
codegraph help install 2>/dev/null || true
ast-grep --version 2>/dev/null || true
ast-grep --help 2>/dev/null || true
```
`codegraph --version` is the portable first probe across reviewed legacy and current releases. Use `codegraph version` only after help exposes it. Prefix skill-invoked CodeGraph commands with `CODEGRAPH_TELEMETRY=0` unless the user separately chose to keep telemetry enabled for that action. Preserve `DO_NOT_TRACK=1` when present or requested; do not weaken it merely to permit an update lookup.
Version/help probes are the safest no-write checks. `codegraph status`, MCP graph queries, and other project-opening diagnostics can repair or migrate metadata in the effective state directory (`CODEGRAPH_DIR`, default `.codegraph/`) in some versions. Explain that boundary and obtain affirmative approval for the selected root before running one, or use an approved disposable copy. Under a strict no-write request, skip project-opening commands unless the disposable-copy path was approved.
Inspect only relevant config names and paths before reading content:
```bash
find . -maxdepth 3 \
\( -path '*/.codex/config.toml' -o -path '*/.cursor/mcp.json' -o -name '.mcp.json' \
-o -name 'codegraph.json' -o -name 'sgconfig.yml' -o -name 'sgconfig.yaml' \) \
-print 2>/dev/null
```
When content inspection is necessary, redact credentials, headers, private service URLs, customer names, and unrelated server entries before reporting it.
## Choose an installation scope
Select and announce the applicable installation scope inside the `setup` workflow. This is not another public workflow. Ask only when the installation scope or authority is ambiguous or expands beyond the requested setup outcome.
| Installation scope | CLI/tool scope | MCP/config scope | Best fit |
| ------------------ | ------------------------------------------------------------------------- | -------------------------------- | ------------------------------------------------------ |
| Personal | Existing or user-wide installation | User/global runtime config | One trusted workstation across many repositories |
| Team-pinned | Project dependency, Nix/devbox/toolchain pin, or documented exact release | Project runtime config | Reproducible team and CI behavior |
| Ephemeral | Exact package or verified archive in a temp/sandbox path | Printed or temporary config only | CI, evaluation, locked-down hosts |
| Diagnostics-only | Existing executables only | No writes | Exploration or repair assessment before setup approval |
The CodeGraph index is always per selected project root even when the CLI/MCP registration is user-wide. ast-grep can be user-wide for ad-hoc use or project-local when rules/CI require a reproducible version.
## Install channels
Resolve `<version>` from an authoritative stable source and local policy before proposing a command. Do not use an unqualified mutable `latest` in an approved persistent install.
### CodeGraph
Preferred choices, in order:
1. Existing working executable.
2. Existing npm-family channel with an exact package version.
3. Exact standalone GitHub release asset plus its published `SHA256SUMS`.
4. Approved one-time `npx` execution when persistence is unwanted and remote execution is acceptable.
Exact npm-family examples:
```bash
npm install -g @colbymchenry/codegraph@<version>
pnpm add -g @colbymchenry/codegraph@<version>
```
For project/declarative setups, use the repository's existing package/toolchain mechanism rather than inventing a global install. For an approved Team-pinned npm-family setup, save an exact manifest pin and the matching lockfile resolution:
```bash
pnpm add --save-dev --save-exact @colbymchenry/codegraph@<version>
npm install --save-dev --save-exact @colbymchenry/codegraph@<version>
```
These are separate alternatives, not commands to run together. They write the manifest and lockfile and can run package lifecycle scripts; show that scope and the package manager's trust policy before approval. On POSIX, verify the exact project-local shim rather than a bare package-manager `exec`, which can fall through to another binary on `PATH`:
```bash
project_root="<approved-project-root>"
codegraph_bin="$project_root/node_modules/.bin/codegraph"
if [ -x "$codegraph_bin" ]; then
CODEGRAPH_TELEMETRY=0 "$codegraph_bin" --version
else
printf 'Missing project-local CodeGraph shim: %s\n' "$codegraph_bin" >&2
false
fi
```
Native Windows equivalent:
```powershell
$projectRoot = "<approved-project-root>"
$codegraphBin = Join-Path $projectRoot "node_modules\.bin\codegraph.cmd"
if (-not (Test-Path -LiteralPath $codegraphBin -PathType Leaf)) {
throw "Missing project-local CodeGraph shim: $codegraphBin"
}
$env:CODEGRAPH_TELEMETRY = "0"
& $codegraphBin --version
if ($LASTEXITCODE -ne 0) { throw "Project-local CodeGraph version check failed" }
```
Confirm that the reported CLI version equals the approved pin and that the manifest/lockfile diff contains only the reviewed dependency change. Use this exact shim for `--help`, `help init`, and `serve --help` too. Never fall back to a global `codegraph` when the local shim is missing.
A reviewable Linux standalone download looks like this; select the asset for the actual architecture and inspect the archive before extraction:
```bash
set -euo pipefail
version=vX.Y.Z
asset=codegraph-linux-x64.tar.gz
base="https://github.com/colbymchenry/codegraph/releases/download/${version}"
workdir="$(mktemp -d)"
cd "$workdir"
curl -fL -o "$asset" "$base/$asset"
curl -fL -o SHA256SUMS "$base/SHA256SUMS"
grep " $asset\$" SHA256SUMS | sha256sum -c -
tar -tzf "$asset"
printf 'Verified archive: %s/%s\n' "$workdir" "$asset"
```
Archive extraction and PATH linking require a second approved write step with the chosen destination. On macOS, use the matching Darwin asset and verify the selected checksum with `shasum -a 256` before inspecting the archive. On Windows, download the matching ZIP and `SHA256SUMS`, compare `Get-FileHash -Algorithm SHA256`, inspect the ZIP, then extract only after approval.
Do not default to upstream `curl ... | sh` or `irm ... | iex`. A one-time runner such as `npx @colbymchenry/codegraph@<version>` is also remote code execution and requires approval.
### ast-grep CLI
Choose the channel already trusted by the user or repository:
| Channel | Exact/setup form | Important policy |
| ----------------- | ----------------------------------------------------------------- | ----------------------------------------------------------------------- |
| Project pnpm | `pnpm add -D @ast-grep/cli@<version>` | Includes manifest/lockfile writes and may require build-script approval |
| Project npm | `npm install --save-dev @ast-grep/cli@<version>` | Includes manifest/lockfile writes |
| User pnpm | `pnpm add -g --allow-build=@ast-grep/cli @ast-grep/cli@<version>` | Do not bypass pnpm build policy silently |
| User npm | `npm install -g @ast-grep/cli@<version>` | Writes to configured npm prefix |
| Cargo | `cargo install ast-grep --locked --version <version>` | Compiles locally; preserve Cargo's install root |
| pipx | `pipx install 'ast-grep-cli==<version>'` | Isolated Python CLI environment |
| pip | `python -m pip install 'ast-grep-cli==<version>'` | Use only in the explicitly selected environment |
| Homebrew/MacPorts | Formula/port install | Usually tracks repository channel; disclose weak exact pin/rollback |
| Nix/declarative | Edit the existing input/package declaration | Do not imperatively mutate a declarative environment |
The npm package materializes the native executable through its install lifecycle. If a package manager blocks that step, report it and ask before changing trust/build policy. On Linux, use `ast-grep`; `sg` can resolve to the system `setgroups` utility.
For either project npm-family install, verify the exact local shim. Do not use bare `pnpm exec` or `npm exec`: a missing shim must fail instead of searching `PATH`, fetching a package, or executing anything other than the approved `@ast-grep/cli` dependency.
```bash
project_root="<approved-project-root>"
ast_grep_bin="$project_root/node_modules/.bin/ast-grep"
if [ -x "$ast_grep_bin" ]; then
"$ast_grep_bin" --version
else
printf 'Missing project-local ast-grep shim: %s\n' "$ast_grep_bin" >&2
false
fi
```
On native Windows, require `<approved-project-root>\node_modules\.bin\ast-grep.cmd` with `Test-Path -PathType Leaf`, then invoke that exact path with `& $astGrepBin --version`.
## CodeGraph runtime configuration
First inspect generated MCP configuration without changing runtime config when the installed version supports it:
```bash
DO_NOT_TRACK=1 codegraph install --print-config codex
DO_NOT_TRACK=1 codegraph install --print-config cursor
DO_NOT_TRACK=1 codegraph install --print-config claude
```
`--print-config` shows an MCP snippet, not every side effect of `codegraph install`. Reviewed CodeGraph 1.4.1 installer behavior can also alter runtime config, legacy instruction markers/hooks, permissions, telemetry choices, global package state, or a Claude prompt hook. Prefer runtime-native MCP-only configuration when that is the user's intent.
Generic stdio shape for a verified executable already on the runtime's `PATH`:
```json
{
"command": "codegraph",
"args": ["serve", "--mcp"]
}
```
Add `--path <approved-project-root>` only when the client does not reliably provide roots/current working directory. Do not persist private absolute paths in public examples.
For a Team-pinned project dependency, do not use bare `codegraph`, `npx`, or bare package-manager `exec`. After installed help confirms `serve --mcp --path`, configure the selected runtime with the exact local shim verified above:
| Runtime environment | `command` | `args` |
| -------------------- | --------------------------------------------------------- | --------------------------------------------------------- |
| POSIX, including WSL | `<approved-project-root>/node_modules/.bin/codegraph` | `["serve", "--mcp", "--path", "<approved-project-root>"]` |
| Native Windows | `<approved-project-root>\node_modules\.bin\codegraph.cmd` | `["serve", "--mcp", "--path", "<approved-project-root>"]` |
Use the same native absolute project path in the shim and `--path`; this makes local dependency resolution independent of the client's launch directory and fails if the reviewed dependency is absent. Set `CODEGRAPH_DIR` to the approved plain directory name and `CODEGRAPH_TELEMETRY=0` in the MCP environment unless the user separately opted into telemetry. Before writing runtime config, run the platform-specific version check from the Team-pinned install section. After writing it, reconnect/restart and verify both the stored command/args/environment and the exposed CodeGraph tool list. If the project moves, regenerate the path after approval. If the runtime does not expose a server version, report that limitation instead of claiming MCP itself returned one.
For native Windows JSON/TOML, use a correctly serialized absolute path: forward slashes or escaped backslashes, never a raw backslash string copied from PowerShell output.
### Codex
- Project scope: trusted `.codex/config.toml`.
- User scope: `~/.codex/config.toml` or `codex mcp add` after approval.
- Verify with `codex mcp list`, `codex mcp get codegraph`, and `/mcp` when the TUI is available.
Project/user TOML shape:
```toml
[mcp_servers.codegraph]
command = "codegraph"
args = ["serve", "--mcp"]
```
Approved Team-pinned POSIX project shape; use the native Windows shim from the table when applicable:
```toml
[mcp_servers.codegraph]
command = "<approved-project-root>/node_modules/.bin/codegraph"
args = ["serve", "--mcp", "--path", "<approved-project-root>"]
env = { CODEGRAPH_DIR = "<approved-state-directory>", CODEGRAPH_TELEMETRY = "0" }
```
Codex also supports an MCP `cwd`, but the exact absolute shim above does not depend on launch-directory behavior and binds execution to the reviewed project dependency. Project `.codex/config.toml` is loaded only for a trusted project.
CodeGraph v1.6.0 added `codegraph install --location=local` for project-scoped Codex setup. Its [release notes](https://github.com/colbymchenry/codegraph/releases/tag/v1.6.0) say this writes the project `.codex/config.toml` and a CodeGraph block in `AGENTS.md`; `--init` additionally builds the project index. Inspect installed help, the target files, and the full write scope before choosing that installer. For MCP-only intent, prefer the reviewed runtime-native entry above. Earlier reviewed 1.4.1 Codex installer behavior was user/global, so do not assume the newer flag exists on an older installation.
### Cursor
- Project scope: `.cursor/mcp.json`.
- User scope: `~/.cursor/mcp.json`.
- Verify with Cursor's MCP settings or `cursor-agent mcp list`/`cursor-agent mcp list-tools codegraph` when available.
Cursor may launch MCP subprocesses outside the project root. Use the runtime's workspace variable for global config or an approved absolute project path for local config only after current Cursor behavior is verified. Reviewed CodeGraph 1.4.1 first-party Cursor output accounts for this with `--path`; inspect it before writing.
Approved Team-pinned POSIX project shape; use the native Windows shim from the table when applicable:
```json
{
"mcpServers": {
"codegraph": {
"command": "<approved-project-root>/node_modules/.bin/codegraph",
"args": ["serve", "--mcp", "--path", "<approved-project-root>"],
"env": {
"CODEGRAPH_DIR": "<approved-state-directory>",
"CODEGRAPH_TELEMETRY": "0"
}
}
}
}
```
### Claude Code
- Project/team scope: `.mcp.json` through current `claude mcp add --scope project` behavior.
- Local/user behavior: inspect current `claude mcp` help and `~/.claude.json` rather than guessing its storage boundary.
- Verify with `claude mcp list`, `claude mcp get codegraph`, or `/mcp` when available.
Reviewed first-party CodeGraph setup can touch `CLAUDE.md`, permissions, legacy hooks, or a prompt hook in addition to MCP configuration. Use runtime-native MCP-only configuration when those writes were not requested. This path is documentation-verified when a Claude CLI is unavailable locally.
For a Team-pinned Claude project, use the same approved JSON `mcpServers.codegraph` entry shown for Cursor in project `.mcp.json`, then verify the stored entry and connected tools with current Claude CLI/UI behavior. Do not translate the Codex TOML shape into Claude JSON.
### Other MCP clients
Read the client's current MCP documentation, choose its project/user scope, show the stdio entry and destination, and verify the server/tool list. Do not transpose Codex TOML, Cursor JSON, or Claude scope commands into another client.
## Project initialization and configuration
Select the actual indexed root before initialization. In a monorepo, decide whether one root graph or separate package graphs best matches the task.
Current CodeGraph versions that document `CODEGRAPH_DIR` accept only a plain directory name in the project root; the default is `.codegraph`. Record the effective value with the project root and use it in every CLI invocation and MCP environment. If installed/current documentation does not establish this capability, do not assume the override works: use one environment only or offer an approved version update.
When native Windows and WSL share one working tree, never share one index. After separate config approval, use distinct names such as `.codegraph-win` for the native Windows client/CLI and `.codegraph-wsl` for the WSL client/CLI. Keep each runtime, package manager, repository path, `CODEGRAPH_DIR`, and ast-grep invocation in that same environment.
```bash
codegraph help init
```
Then run only the form installed help documents. For example:
```bash
# Current releases where init performs indexing:
codegraph init
# Help-confirmed legacy releases where -i requests the initial index:
codegraph init -i
```
For an approved Team-pinned POSIX initialization, validate the state-directory value before CodeGraph can fall back to its default, require the exact local shim, and stop on the first failure:
```bash
set -euo pipefail
project_root="<approved-project-root>"
codegraph_dir="<approved-state-directory>"
codegraph_dir="${codegraph_dir#"${codegraph_dir%%[![:space:]]*}"}"
codegraph_dir="${codegraph_dir%"${codegraph_dir##*[![:space:]]}"}"
case "$codegraph_dir" in
""|"."|*..*|*/*|*\\*)
printf 'Invalid CODEGRAPH_DIR: plain directory name required\n' >&2
exit 1
;;
esac
codegraph_bin="$project_root/node_modules/.bin/codegraph"
if [ ! -x "$codegraph_bin" ]; then
printf 'Missing project-local CodeGraph shim: %s\n' "$codegraph_bin" >&2
exit 1
fi
CODEGRAPH_TELEMETRY=0 CODEGRAPH_DIR="$codegraph_dir" \
"$codegraph_bin" init "$project_root"
```
Use the help-confirmed legacy `-i` form only with a legacy pin. Native Windows validates the selected state directory and exact shim before initialization and checks the command result:
```powershell
$projectRoot = "<approved-project-root>"
$codegraphDir = ("<approved-state-directory>").Trim()
if ([string]::IsNullOrWhiteSpace($codegraphDir) -or $codegraphDir -eq "." -or $codegraphDir.Contains("..") -or $codegraphDir.Contains("/") -or $codegraphDir.Contains("\")) {
throw "CODEGRAPH_DIR must be a plain directory name"
}
$codegraphBin = Join-Path $projectRoot "node_modules\.bin\codegraph.cmd"
if (-not (Test-Path -LiteralPath $codegraphBin -PathType Leaf)) {
throw "Missing project-local CodeGraph shim: $codegraphBin"
}
$env:CODEGRAPH_DIR = $codegraphDir
$env:CODEGRAPH_TELEMETRY = "0"
& $codegraphBin init $projectRoot
if ($LASTEXITCODE -ne 0) { throw "Project-local CodeGraph initialization failed" }
```
Only after project-opening status verification is separately approved, restate the exact approved root and state directory and bind the executable to that root again:
```bash
set -euo pipefail
project_root="<approved-project-root>"
codegraph_dir="<approved-state-directory>"
codegraph_dir="${codegraph_dir#"${codegraph_dir%%[![:space:]]*}"}"
codegraph_dir="${codegraph_dir%"${codegraph_dir##*[![:space:]]}"}"
case "$codegraph_dir" in
""|"."|*..*|*/*|*\\*) exit 1 ;;
esac
codegraph_bin="$project_root/node_modules/.bin/codegraph"
[ -x "$codegraph_bin" ]
CODEGRAPH_TELEMETRY=0 CODEGRAPH_DIR="$codegraph_dir" \
"$codegraph_bin" status "$project_root"
```
```powershell
$projectRoot = "<approved-project-root>"
$codegraphDir = ("<approved-state-directory>").Trim()
if ([string]::IsNullOrWhiteSpace($codegraphDir) -or $codegraphDir -eq "." -or $codegraphDir.Contains("..") -or $codegraphDir.Contains("/") -or $codegraphDir.Contains("\")) {
throw "CODEGRAPH_DIR must be a plain directory name"
}
$codegraphBin = Join-Path $projectRoot "node_modules\.bin\codegraph.cmd"
if (-not (Test-Path -LiteralPath $codegraphBin -PathType Leaf)) {
throw "Missing project-local CodeGraph shim: $codegraphBin"
}
$env:CODEGRAPH_DIR = $codegraphDir
$env:CODEGRAPH_TELEMETRY = "0"
& $codegraphBin status $projectRoot
if ($LASTEXITCODE -ne 0) { throw "Project-local CodeGraph status failed" }
```
Initialization creates index state in the effective directory. In the same environment where the approved `CODEGRAPH_DIR` is set, validate that it is a plain name, then inspect that exact path rather than assuming `.codegraph/`:
```bash
codegraph_dir="${CODEGRAPH_DIR:-}"
codegraph_dir="${codegraph_dir#"${codegraph_dir%%[![:space:]]*}"}"
codegraph_dir="${codegraph_dir%"${codegraph_dir##*[![:space:]]}"}"
: "${codegraph_dir:=.codegraph}"
case "$codegraph_dir" in
"."|*..*|*/*|*\\*)
printf 'Invalid CODEGRAPH_DIR: plain directory name required\n' >&2
exit 1
;;
*) git check-ignore -q -- "$codegraph_dir/" ||
git status --short --untracked-files=all -- "$codegraph_dir/" ;;
esac
```
Native PowerShell equivalent:
```powershell
$codegraphDir = if ([string]::IsNullOrWhiteSpace($env:CODEGRAPH_DIR)) { ".codegraph" } else { $env:CODEGRAPH_DIR.Trim() }
if ($codegraphDir -eq "." -or $codegraphDir.Contains("..") -or $codegraphDir.Contains("/") -or $codegraphDir.Contains("\")) {
throw "CODEGRAPH_DIR must be a plain directory name"
}
git check-ignore -q -- "$codegraphDir/"
if ($LASTEXITCODE -ne 0) { git status --short --untracked-files=all -- "$codegraphDir/" }
```
Ask before editing `.gitignore`. Never delete, reinitialize, or share an existing index just because its version differs.
When installed/current documentation exposes root `codegraph.json`, use it only for a real project need such as custom extensions, tracked-source excludes, explicitly included first-party ignored source, or selected nested repositories. Show the proposed diff and obtain approval. Configuration changes can require a full re-index; inspect installed help before proposing it.
Do not create `.codegraph/config.json`.
## ast-grep project setup
Inspect existing config first:
```bash
test -f sgconfig.yml && sed -n '1,220p' sgconfig.yml
test -f sgconfig.yaml && sed -n '1,220p' sgconfig.yaml
find . -maxdepth 4 -type d \( -name rules -o -name rule-tests -o -name tests \) -print
```
Do not create `sgconfig.yml`, rule directories, or test fixtures for an ad-hoc search. Create them only when the user wants reusable rules/CI, show the intended paths, and follow existing repository conventions.
## Experimental ast-grep MCP
Prefer ast-grep CLI. The upstream ast-grep MCP server is experimental, has no stable release line, requires Python plus ast-grep on `PATH`, and is excluded from normal `setup` and `update`. It should not be persisted from an unpinned Git branch.
For an approved experiment:
1. review and select a full upstream commit;
2. clone/check out that commit into the approved scope;
3. run `uv sync --locked` in the reviewed checkout;
4. configure the runtime to launch that checkout;
5. record the commit and ast-grep CLI version;
6. verify exposed tools and keep CLI fallback.
Do not publish an unpinned `uvx --from git+...` MCP entry as a durable default.
## Authorization and verification
An explicit `setup` request for the announced root authorizes the ordinary agent-complete actions below. Keep each effect visible, and stop for a new approval when the effective action crosses the listed boundary.
| Action | Covered setup scope | Separate boundary | Verify afterward |
| -------------------------------------------------- | ---------------------------------------------------- | ------------------------------------------------------ | -------------------------------------------------- |
| Install/reconcile CLI package or archive | Existing approved project/declarative channel | Privilege, global scope, channel/trust-policy change | Executable path, version, help, install provenance |
| Register/edit MCP server | Named runtime and announced config scope | Another runtime, user-wide expansion, secret material | Server list, tool list, restart/reconnect |
| Run `codegraph install` | Only when every known side effect was announced | Undisclosed instruction/hook/global mutation | Every touched config/instruction/hook surface |
| Initialize/migrate/sync graph | Exact announced root and generated state | Destructive rebuild, deletion, or another root | Root, `status`, freshness, ignore state |
| Create/edit project config and repository guidance | Minimal idempotent setup files in the announced root | Unrelated source, policy, or broad instruction rewrite | Diff, parse/test, discovery and behavior |
After setup, report exact installed versions and scopes, runtime verification, graph readiness, ast-grep availability, persisted guidance discovery, any unverified path, and the next safe usage command. Do not claim setup complete from file presence alone.
references/troubleshooting.md
# Troubleshooting
The `doctor` workflow diagnoses the smallest failing layer: executable/provenance, runtime MCP connection, selected project root, CodeGraph index/watch state, ast-grep parser/rule, repository guidance, or project validation. It never repairs.
Precondition: the exact root is known. A deep diagnostic needs affirmative exact-root approval when it opens a project or can migrate generated state; without approval, skip it and report the evidence gap.
## Contents
- [Update state is unavailable](#update-state-is-unavailable)
- [Wrong or shadowed executable](#wrong-or-shadowed-executable)
- [MCP server is missing or disconnected](#mcp-server-is-missing-or-disconnected)
- [CodeGraph is uninitialized, stale, or on the wrong root](#codegraph-is-uninitialized-stale-or-on-the-wrong-root)
- [CodeGraph misses symbols or files](#codegraph-misses-symbols-or-files)
- [ast-grep is missing or cannot materialize its binary](#ast-grep-is-missing-or-cannot-materialize-its-binary)
- [ast-grep matches nothing or too much](#ast-grep-matches-nothing-or-too-much)
- [Semantic and structural evidence disagree](#semantic-and-structural-evidence-disagree)
- [An update or config refresh failed](#an-update-or-config-refresh-failed)
## Update state is unavailable
Check whether the user/environment intentionally disables lookup:
```bash
test -n "${DO_NOT_TRACK:-}" && printf 'DO_NOT_TRACK is set\n'
test -n "${CODEGRAPH_NO_UPDATE_CHECK:-}" && printf 'CODEGRAPH_NO_UPDATE_CHECK is set\n'
```
Do not print values beyond presence. If offline/opt-out applies, report `not checked` and continue. If an allowed lookup fails, do not retry through a second API/registry during the task.
For current CodeGraph, use `upgrade --check` only when installed help exposes it and external lookup is allowed. For legacy CodeGraph or ast-grep without a built-in check, use official channel metadata only when available; never invent an updater.
## Wrong or shadowed executable
```bash
command -v codegraph 2>/dev/null || true
which -a codegraph 2>/dev/null || true
codegraph --version 2>/dev/null || true
command -v ast-grep 2>/dev/null || true
which -a ast-grep 2>/dev/null || true
ast-grep --version 2>/dev/null || true
```
Compare the winning path with package-manager/declarative provenance. Do not update a different installation and call the problem fixed. Propose removing, reordering, or updating a shadowing install only after showing the paths and obtaining approval.
On Linux, `sg` may be the system `setgroups` utility; use `ast-grep` explicitly.
## MCP server is missing or disconnected
Verify the runtime's own state rather than copying another client's config:
- Codex: `codex mcp list`, `codex mcp get codegraph`, and `/mcp`.
- Cursor: MCP settings or current `cursor-agent mcp` help/list commands.
- Claude Code: current `claude mcp` help/list/get or `/mcp`.
- Other clients: their server/tool inventory.
Then verify the configured command resolves from the same environment that launches the client. For a user-wide executable:
```bash
command -v codegraph
codegraph --version
codegraph --help
```
For a Team-pinned dependency on POSIX, require and invoke the exact configured project-local shim. Do not use bare package-manager `exec`; it can fall through to another binary on `PATH`:
```bash
project_root="<approved-project-root>"
codegraph_bin="$project_root/node_modules/.bin/codegraph"
if [ -x "$codegraph_bin" ]; then
CODEGRAPH_TELEMETRY=0 "$codegraph_bin" --version
else
printf 'Missing project-local CodeGraph shim: %s\n' "$codegraph_bin" >&2
false
fi
```
On native Windows, require and invoke `<approved-project-root>\node_modules\.bin\codegraph.cmd`. Compare the result with the approved dependency pin, then verify the runtime stored the same exact shim, `--path`, `CODEGRAPH_DIR`, and telemetry environment before reconnecting and listing tools.
Common causes:
- runtime needs restart/reconnect after config change;
- global CLI path is absent from GUI/runtime environment;
- project-local config contains a moved absolute path;
- Cursor/another client launches from the wrong working directory and needs an approved `--path`/workspace-root binding;
- Windows and WSL paths/environments are mixed;
- current server exposes a different MCP tool set than old instructions assume.
Inspect generated config with `codegraph install --print-config <target>` only when installed help exposes it. Remember that the snippet does not disclose every first-party installer side effect.
## CodeGraph is uninitialized, stale, or on the wrong root
Start with checks that do not open the graph:
```bash
pwd
codegraph --version
codegraph help init 2>/dev/null || true
```
`codegraph status`, MCP graph queries, and other project-opening diagnostics can migrate generated index metadata in some versions. Explain the generated-state boundary and obtain affirmative approval for the selected root, or use an approved disposable copy. Under a strict no-write instruction, skip the command unless that copy was approved. After approval, run:
```bash
codegraph status
```
The bare command above applies only to a verified user-wide executable. For a Team-pinned setup, invoke the exact local shim established in the MCP section and carry the same `CODEGRAPH_DIR`; do not let diagnostics fall through to a global binary or the default state directory.
If no valid graph exists, ask before running the help-confirmed init form. If status points at the wrong root, fix runtime/project-path selection before creating another index.
For freshness:
- active MCP watcher with no pending state: wait for debounce and avoid ceremonial sync;
- persistent pending/stale state: inspect watcher/root and propose the minimum approved sync;
- CLI/script, disabled daemon, sandboxed watcher, or CI: a manual sync can be valid;
- changed `codegraph.json` extraction/exclude/include behavior: installed help/current docs may require full index.
Do not delete the effective state directory (`CODEGRAPH_DIR`, default `.codegraph/`) as the default fix. Preserve the index and logs until the failure is understood. Run every approved status/sync/repair command with the same state-directory value used by the MCP server.
Do not share one index between Windows and WSL processes. Use one environment or, on a version that documents `CODEGRAPH_DIR`, separately configure plain directory names such as `.codegraph-win` and `.codegraph-wsl` after approval.
## CodeGraph misses symbols or files
Check:
1. selected root and graph status;
2. supported language/extension in installed/current docs;
3. `.gitignore`, built-in excludes, and root `codegraph.json` when supported;
4. generated/vendor/nested-repository/worktree boundaries;
5. dynamic dispatch, reflection, macros, dependency injection, route registration, or string-based loading;
6. pending watcher state.
Use help-confirmed file/query commands or targeted source/text search to test the named gap. Absence from the graph is not proof of absence from source.
If a current stable release contains a relevant parser/framework fix, offer it through the itemized update checkpoint; do not silently update.
## ast-grep is missing or cannot materialize its binary
```bash
command -v ast-grep 2>/dev/null || true
ast-grep --version 2>/dev/null || true
```
Inspect how it was installed. npm-family packages may need an allowed install lifecycle to materialize the native binary. Report the package manager's current trust/build policy and ask before changing it or reinstalling.
Do not install through a different channel just because the existing channel needs repair. Preserve project-local versus user-wide scope.
## ast-grep matches nothing or too much
- Test one known file before the repository.
- Confirm language and TS versus TSX/JS versus JSX.
- Quote `$` metavariables with single quotes in the shell.
- Reduce the pattern to the smallest expected node.
- Inspect parser/AST debug options only when installed help exposes them.
- Check expression versus statement context and embedded-language boundaries.
- Add known positives and negatives to rule tests.
- Use `stopBy: end` only when relational traversal should reach the full enclosing node.
- Bound paths/globs before adding relational complexity.
If a result cap truncates output, say so. If a known syntax variant cannot be represented, document the gap and use targeted corroboration rather than overstating coverage.
## Semantic and structural evidence disagree
1. Recheck graph root/freshness/pending files.
2. Recheck ast-grep language, rule, and fixtures.
3. Inspect dynamic/generated/ignored/unsupported code.
4. Use runtime-native LSP or one bounded literal search for the named discrepancy.
5. Read the exact source and report which evidence remains partial.
Do not resolve disagreement by automatically taking the union and calling it impact. The union may be a conservative review scope, but label it as such.
## An update or config refresh failed
Stop additional update/config actions. Capture the redacted command/error and verify what still resolves:
```bash
which -a codegraph 2>/dev/null || true
codegraph --version 2>/dev/null || true
which -a ast-grep 2>/dev/null || true
ast-grep --version 2>/dev/null || true
```
Do not open the graph merely to verify a binary/config rollback. Run `codegraph status` only if graph diagnosis is separately necessary and its generated-state boundary was affirmatively approved for that root or an approved disposable copy.
Check for:
- a stale PATH winner;
- partial package/archive install;
- package lifecycle/build policy failure;
- runtime config or prompt-hook changes that exceeded the approved scope;
- required client restart;
- project manifest/lockfile drift.
Use only the rollback disclosed before approval. If rollback is weak or unavailable, preserve config/index/source and present a separate repair proposal. Never delete an index or overwrite runtime config merely to make the new version appear healthy.
references/update-and-provenance.md
# Stable Updates and Installation Provenance
Use this reference for the selected `update` workflow. It preserves installer provenance while updating stable core tools, running required migrations, reconnecting the client, and verifying readiness. External version lookup and telemetry remain separate choices.
Precondition: `update` was selected from clear user intent or explicit choice and the exact root/write scope was announced. That selection authorizes ordinary in-root stable core updates and required migrations; privilege escalation, channel/scope changes, telemetry, destructive rebuilds, unrelated dependencies, and external services remain separate.
## Contents
- [Scope and frequency](#scope-and-frequency)
- [Respect network and privacy policy](#respect-network-and-privacy-policy)
- [Discover installed provenance](#discover-installed-provenance)
- [Resolve the stable target](#resolve-the-stable-target)
- [Execution manifest](#execution-manifest)
- [Update execution](#update-execution)
- [Configuration, migration, and reconnect](#configuration-migration-and-reconnect)
- [Verification and rollback](#verification-and-rollback)
## Scope and frequency
Perform the stable-version lookup **at most once per core tool in the update workflow**, then reuse the result.
Include only the selected analysis stack:
- installed/required CodeGraph;
- installed/required ast-grep;
- configured MCP helpers relevant to the task;
- an optional semantic, codemod, or policy tool only after it is selected for the task.
Exclude:
- unused optional tools;
- application frameworks and dependencies;
- package-manager self-updates;
- Codex, Claude Code, or Cursor client updates unless a concrete compatibility blocker makes one relevant.
When a tool is missing, route to setup. Do not install it merely to learn a version.
## Respect network and privacy policy
Before external lookup, inspect explicit policy and user intent. Do not override:
- offline or air-gapped operation;
- `DO_NOT_TRACK`;
- `CODEGRAPH_NO_UPDATE_CHECK`;
- corporate registry/mirror restrictions;
- repository/declarative version pins;
- a user instruction not to browse or check updates.
CodeGraph's explicit `upgrade --check` can still contact GitHub even when its background-update environment flags are set. The skill must enforce the opt-out before invoking the command.
Permission to query public release metadata does not enable CodeGraph telemetry. Unless the user separately chose to keep telemetry enabled for the check, run the CodeGraph process with `CODEGRAPH_TELEMETRY=0`. Do not infer consent from CodeGraph's default-on state. If `DO_NOT_TRACK` or `CODEGRAPH_NO_UPDATE_CHECK` blocks lookup, report `not checked`; do not replace the opt-out with a narrower telemetry override just to reach GitHub.
If lookup is disallowed or fails:
1. report `remote update state: not checked` with the reason;
2. continue from installed version/help;
3. do not retry through another registry/API during the task;
4. do not imply that the installed version is current.
Only public package identifiers and release metadata may leave the machine. Never send repository paths, source, symbols, queries, config, or customer data to an update source.
## Discover installed provenance
Record, without mutation:
- resolved executable path and all PATH duplicates where shadowing is plausible;
- tool-reported version;
- package/declarative owner and scope;
- project manifest/lockfile pin when present;
- lifecycle/build trust policy;
- MCP command and pinned helper source when relevant.
Examples of read-only provenance checks; run only those matching the environment:
```bash
command -v codegraph 2>/dev/null || true
command -v ast-grep 2>/dev/null || true
which -a codegraph ast-grep 2>/dev/null || true
codegraph --version 2>/dev/null || true
ast-grep --version 2>/dev/null || true
npm list -g --depth=0 @colbymchenry/codegraph @ast-grep/cli 2>/dev/null || true
pnpm list -g --depth=0 2>/dev/null || true
cargo install --list 2>/dev/null || true
python -m pip show ast-grep-cli 2>/dev/null || true
brew list --versions ast-grep 2>/dev/null || true
```
Native Windows provenance checks:
```powershell
Get-Command codegraph, ast-grep -All -ErrorAction SilentlyContinue |
Select-Object Name, CommandType, Source
$codegraphCommand = Get-Command codegraph -CommandType Application -ErrorAction SilentlyContinue |
Select-Object -First 1
$astGrepCommand = Get-Command ast-grep -CommandType Application -ErrorAction SilentlyContinue |
Select-Object -First 1
if ($codegraphCommand) { & $codegraphCommand.Source --version }
if ($astGrepCommand) { & $astGrepCommand.Source --version }
npm list -g --depth=0 @colbymchenry/codegraph @ast-grep/cli
pnpm list -g --depth=0
python -m pip show ast-grep-cli
```
Do not treat a package-manager command as authoritative if the resolved executable comes from a different channel. If provenance is ambiguous, report it and do not propose an update until the winning executable/channel is understood.
## Resolve the stable target
Use the installed channel's official metadata when possible, then the upstream official release as corroboration. Apply repository pins/freshness policy before deciding an update is eligible.
Dated upstream check (2026-10-29): official releases were [CodeGraph v1.6.2](https://github.com/colbymchenry/codegraph/releases/tag/v1.6.2) and [ast-grep 0.51.0](https://github.com/ast-grep/ast-grep/releases/tag/0.51.0). These are observations, not permanent pins or evidence of an installed version. Recheck the selected installer channel when an actual setup or update runs.
| Tool/channel | Read-only stable source |
| ------------------------------------------- | -------------------------------------------------------------------------------------------- |
| CodeGraph with current upgrade capability | Existing MCP/status notice, then `codegraph upgrade --check` when external lookup is allowed |
| CodeGraph npm-family | Official `@colbymchenry/codegraph` registry metadata and GitHub release |
| CodeGraph standalone | Official GitHub release assets plus `SHA256SUMS` |
| ast-grep npm-family | Official `@ast-grep/cli` registry metadata and GitHub release |
| ast-grep Cargo/Python/Homebrew/MacPorts/Nix | Matching official channel metadata, constrained by the active environment |
| Optional selected tool | Its official release/registry source recorded in the extension decision |
Examples when their channel is selected and network checks are allowed:
```bash
codegraph help upgrade 2>/dev/null || true
CODEGRAPH_TELEMETRY=0 codegraph upgrade --check
npm view @colbymchenry/codegraph version dist-tags --json
npm view @ast-grep/cli version dist-tags --json
```
Native Windows equivalent for the CodeGraph check; use the already-verified exact project-local shim instead of `Get-Command` when provenance is Team-pinned:
```powershell
if ($env:DO_NOT_TRACK -or $env:CODEGRAPH_NO_UPDATE_CHECK) {
throw "CodeGraph remote update lookup is disabled by policy"
}
$codegraphCommand = Get-Command codegraph -CommandType Application -ErrorAction Stop |
Select-Object -First 1
$previousTelemetry = [Environment]::GetEnvironmentVariable("CODEGRAPH_TELEMETRY", "Process")
try {
$env:CODEGRAPH_TELEMETRY = "0"
& $codegraphCommand.Source help upgrade
if ($LASTEXITCODE -ne 0) { throw "CodeGraph upgrade help probe failed" }
& $codegraphCommand.Source upgrade --check
if ($LASTEXITCODE -ne 0) { throw "CodeGraph stable update check failed" }
} finally {
[Environment]::SetEnvironmentVariable("CODEGRAPH_TELEMETRY", $previousTelemetry, "Process")
}
```
`codegraph upgrade --check` is a check only in versions whose installed help says so. It does not authorize or perform an update, but reviewed CodeGraph 1.4.1 includes every `upgrade` invocation in its telemetry flush path. Keep the `CODEGRAPH_TELEMETRY=0` override unless telemetry was separately approved for this action, so a default-on process cannot flush buffered telemetry. Do not use the override to bypass `DO_NOT_TRACK` or `CODEGRAPH_NO_UPDATE_CHECK`.
Select the newest **stable** version that is compatible with the active package/declarative policy. Ignore prereleases. Mention a prerelease only when a documented blocker has no stable fix and the user explicitly asks to evaluate prereleases.
Filter release notes locally for relevant languages, frameworks, platforms, parser fixes, MCP behavior, update/install changes, and known regressions. Do not claim a security reason unless an authoritative advisory or release note supports it.
## Execution manifest
If no eligible stable update exists, report the checked state briefly and continue with migration/readiness reconciliation when needed.
Before mutation, present one compact execution manifest. Include every field:
| Component | Installed | Stable target/source | Why it matters | Exact action | Scope and expected mutation | Restart/reindex | Rollback |
| --------- | -------------------------- | --------------------------------- | --------------------------- | --------------------- | --------------------------------------------- | -------------------------- | ------------------------- |
| `<tool>` | `<version, path, channel>` | `<version, official URL/channel>` | `<relevant fix/capability>` | `<versioned command>` | `<global/project files, network, privileges>` | `<required/none/separate>` | `<command or limitation>` |
State explicitly:
- every selected core-tool update is itemized even when the explicit update request authorizes the whole unchanged manifest;
- the announced update scope covers required in-root config/index/schema migrations and reconnects, but not prompt-hook, telemetry, destructive rebuild, or unrelated dependency expansion;
- the exact CodeGraph action shows `CODEGRAPH_TELEMETRY=0` unless telemetry was separately approved for that action; default-on telemetry is not approval;
- project-local actions include the named manifest/lockfile writes;
- declining or excluding one item does not block diagnosis or other authorized items;
- a declined item will not be re-asked during the task.
Never offer or run a blanket `update all` operation.
## Update execution
Before execution, re-check that the exact proposed version, channel, scope, and command still match the announced manifest. If the target changed materially, stop and re-present the affected item.
### CodeGraph
When installed help exposes a pinned upgrade and the detected channel is safe to update through it, a binary-only current-release action must disable agent-config refresh, Claude prompt-hook changes, and telemetry unless telemetry was separately approved for that action:
```bash
CODEGRAPH_TELEMETRY=0 \
CODEGRAPH_NO_INSTALL_REFRESH=1 \
CODEGRAPH_NO_PROMPT_HOOK=1 \
codegraph upgrade <version>
```
Native Windows equivalent, after resolving `$codegraphBin` to the approved installation rather than an alias or another PATH copy:
```powershell
$codegraphBin = (Get-Command codegraph -CommandType Application -ErrorAction Stop |
Select-Object -First 1).Source
$previousTelemetry = [Environment]::GetEnvironmentVariable("CODEGRAPH_TELEMETRY", "Process")
$previousRefresh = [Environment]::GetEnvironmentVariable("CODEGRAPH_NO_INSTALL_REFRESH", "Process")
$previousPromptHook = [Environment]::GetEnvironmentVariable("CODEGRAPH_NO_PROMPT_HOOK", "Process")
try {
$env:CODEGRAPH_TELEMETRY = "0"
$env:CODEGRAPH_NO_INSTALL_REFRESH = "1"
$env:CODEGRAPH_NO_PROMPT_HOOK = "1"
& $codegraphBin upgrade <version>
if ($LASTEXITCODE -ne 0) { throw "CodeGraph binary update failed" }
} finally {
[Environment]::SetEnvironmentVariable("CODEGRAPH_TELEMETRY", $previousTelemetry, "Process")
[Environment]::SetEnvironmentVariable("CODEGRAPH_NO_INSTALL_REFRESH", $previousRefresh, "Process")
[Environment]::SetEnvironmentVariable("CODEGRAPH_NO_PROMPT_HOOK", $previousPromptHook, "Process")
}
```
Reviewed CodeGraph 1.4.1 can flush buffered telemetry when `upgrade` starts, before the update action completes. Omit `CODEGRAPH_TELEMETRY=0` only when the user separately chose to keep telemetry enabled for this exact action; neither update approval nor CodeGraph's default-on state is sufficient.
Before using this path, disclose that upstream standalone upgrade logic can execute its installer and may not verify the published SHA-256. For provenance-sensitive standalone installs, prefer the exact asset plus `SHA256SUMS` workflow from [setup-and-mcp-config.md](setup-and-mcp-config.md).
For an existing user/global npm-family installation, preserve that scope and use the exact package version through its detected manager:
```bash
npm install -g @colbymchenry/codegraph@<version>
pnpm add -g @colbymchenry/codegraph@<version>
```
For a Team-pinned project dependency, preserve project scope, the existing manager, and the reviewed manifest/lockfile mutation:
```bash
npm install --save-dev --save-exact @colbymchenry/codegraph@<version>
pnpm add --save-dev --save-exact @colbymchenry/codegraph@<version>
```
These are alternatives. Never substitute a global command for an approved project-local update, and never switch managers merely to obtain a version.
If the npm launcher can download a missing platform bundle and strict provenance/offline behavior is required, set `CODEGRAPH_NO_DOWNLOAD=1` and fail visibly rather than silently fetching a fallback.
Do not update a source checkout or `npx`-ephemeral execution as if it were a normal global package. Report the correct source/declarative action instead.
### ast-grep
Use the same approved channel and exact target when the channel supports it:
```bash
pnpm add -D @ast-grep/cli@<version>
npm install --save-dev @ast-grep/cli@<version>
pnpm add -g --allow-build=@ast-grep/cli @ast-grep/cli@<version>
npm install -g @ast-grep/cli@<version>
cargo install ast-grep --locked --version <version>
pipx install --force 'ast-grep-cli==<version>'
python -m pip install --upgrade 'ast-grep-cli==<version>'
```
For Homebrew, MacPorts, Nix, or another declarative channel, show that channel's actual update and rollback limitations. Do not switch to npm/Cargo just to obtain an exact version.
### Optional selected tools
Use only the version, channel, permissions, and sandbox/dry-run behavior approved when the tool was selected. Registry codemods, `npx`, `uvx`, and Git sources remain remote code execution even when invoked for one task.
## Configuration, migration, and reconnect
The selected `update` workflow includes configuration/index/schema migration and client reconnect when the installed-to-target version requires them and they stay within the announced root and runtime scope.
After a CodeGraph update, inspect current generated/runtime config and diff it against existing config. Include every required migration in the execution receipt. The [CodeGraph v1.6.2 release notes](https://github.com/colbymchenry/codegraph/releases/tag/v1.6.2) call for re-indexing existing projects after upgrading so graph fixes take effect. The earlier [v1.6.0 notes](https://github.com/colbymchenry/codegraph/releases/tag/v1.6.0) describe `codegraph index` for each existing project. Treat that as an announced generated-index write within the approved root, verify the installed command/help and index result, and do not perform it during an options-only request or unapproved `doctor` check. Reviewed CodeGraph 1.4.1 `install --refresh` can rewrite multiple previously configured targets and locations; `--target` does not reliably narrow that refresh path. Prefer a runtime-native, reviewed MCP-only change when narrower behavior is required.
Report these as distinct effects and ask again only when they exceed the announced update scope:
- MCP server restart/reconnect;
- Claude prompt hook or runtime instructions;
- permissions/auto-allow lists;
- telemetry consent;
- `codegraph sync` or full re-index;
- `codegraph.json`, `sgconfig`, rule, manifest, or lockfile edits not already listed in the update item.
## Verification and rollback
Verify immediately after each approved item before proceeding to the next:
```bash
command -v codegraph 2>/dev/null || true
which -a codegraph 2>/dev/null || true
codegraph --version 2>/dev/null || true
codegraph --help 2>/dev/null || true
command -v ast-grep 2>/dev/null || true
ast-grep --version 2>/dev/null || true
ast-grep --help 2>/dev/null || true
```
Native Windows equivalent; for Team-pinned installs, bind these variables to the exact `.cmd` shims under the approved project root:
```powershell
$codegraphBin = (Get-Command codegraph -CommandType Application -ErrorAction Stop |
Select-Object -First 1).Source
$astGrepBin = (Get-Command ast-grep -CommandType Application -ErrorAction Stop |
Select-Object -First 1).Source
$previousTelemetry = [Environment]::GetEnvironmentVariable("CODEGRAPH_TELEMETRY", "Process")
try {
$env:CODEGRAPH_TELEMETRY = "0"
& $codegraphBin --version
if ($LASTEXITCODE -ne 0) { throw "CodeGraph version verification failed" }
& $codegraphBin --help
if ($LASTEXITCODE -ne 0) { throw "CodeGraph help verification failed" }
& $astGrepBin --version
if ($LASTEXITCODE -ne 0) { throw "ast-grep version verification failed" }
& $astGrepBin --help
if ($LASTEXITCODE -ne 0) { throw "ast-grep help verification failed" }
} finally {
[Environment]::SetEnvironmentVariable("CODEGRAPH_TELEMETRY", $previousTelemetry, "Process")
}
```
Do not run `codegraph status` as binary-only verification. It opens the selected project and some versions can migrate generated index metadata. Run it only after affirmative approval for that root or in an approved disposable copy; skip it under a strict no-write instruction unless that copy was approved.
Then verify, as applicable:
- the PATH-resolved binary is the updated one;
- MCP reconnects and exposes only expected tools;
- after the separate project-opening boundary is affirmatively approved or an approved disposable copy is selected, existing graph status can be read without deletion/reinitialization;
- ast-grep config parses and reusable rules pass positive/negative tests;
- project manifests/lockfiles contain only the approved change;
- no runtime config, instructions, hooks, or telemetry state changed unexpectedly.
Record the previous version before execution. Provide an exact same-channel downgrade when supported. If the channel cannot reliably restore an old version—commonly a rolling formula/port—say so before approval.
On failure:
1. stop remaining updates;
2. preserve indexes, config, and user source;
3. report the failing command without secrets;
4. verify whether the prior executable still works;
5. roll back only through the pre-disclosed safe path;
6. otherwise leave a precise repair proposal for separate approval.
references/usage-playbook.md
# Usage Playbook
Use CodeGraph for semantic scope, ast-grep CLI for syntax-exact coverage, targeted source reads for confirmation, and project-native validation for correctness. These are internal coding behaviors after setup, not public skill workflows.
Persist the following concise rule, adapted to the target repository's existing instruction format: “For repository-scale coding, use CodeGraph for semantic symbols, callers, call paths, and impact; use ast-grep CLI for structural syntax evidence; reconcile both before broad edits.” Do not duplicate an equivalent rule on repeated setup.
## Contents
- [Optional visualizations and actions](#optional-visualizations-and-actions)
- [Choose the smallest evidence path](#choose-the-smallest-evidence-path)
- [Semantic exploration](#semantic-exploration)
- [Structural search and rules](#structural-search-and-rules)
- [Impact and refactor planning](#impact-and-refactor-planning)
- [Evidence reconciliation](#evidence-reconciliation)
- [Fallback ladder](#fallback-ladder)
- [Output discipline](#output-discipline)
## Choose the smallest evidence path
| User need | First useful evidence | Follow-up only when needed |
| -------------------------- | ----------------------------------------------- | --------------------------------------------- |
| Explain a flow | Focused CodeGraph explore result | Targeted source and one narrow call follow-up |
| Change a shared symbol | CodeGraph callers/impact surface | ast-grep variants, project tests/typecheck |
| Find an exact code shape | Narrow ast-grep pattern | YAML rule/tests and semantic ownership |
| Author a reusable rule | Known positive/negative examples | Repo scan and CI/project validation |
| Plan a mechanical refactor | Semantic ownership plus structural inventory | Bounded patch batches and validation |
| Diagnose setup | Current state/capabilities | Recommend `setup` or `update`; do not repair |
| Perform a reviewed rewrite | Tested match inventory and approved exact scope | Diff review, project validation, rollback |
Do not run every tool because it exists. Use only evidence that changes the answer, scope, or safety decision.
## Semantic exploration
1. Confirm the project root and graph health.
2. Enumerate the actual MCP/CLI capabilities.
3. Ask one focused question through exposed `codegraph_explore` or help-confirmed CLI fallback.
4. Capture the relevant entry point, symbols, call paths, likely dependents/tests, and unsupported/dynamic boundaries.
5. Read only source needed to confirm the explanation or prepare an edit.
Good questions identify a behavior and boundary:
- “How does request validation reach persistence?”
- “What calls this authorization decision, and which tests are in its blast radius?”
- “Where does this route enter the application and hand off to domain logic?”
Avoid “dump the whole architecture.” Narrow broad results by symbol, path, route, or subsystem.
## Structural search and rules
1. Identify one known positive source example and its language.
2. Start with the smallest ast-grep CLI pattern against one file or directory.
3. Inventory syntax variants: imports, aliases, optional chaining, wrappers, JSX/TSX, generated code, or language-specific shapes.
4. Bound paths and output. Do not assume every subcommand supports the same result-limit flag.
5. Convert to YAML only when `inside`, `has`, `follows`, `precedes`, `all`, `any`, `not`, utilities, or reuse justifies it.
6. Add positive and negative rule fixtures before claiming complete coverage.
7. Run the rule across the approved scope and report counts/paths plus parser gaps.
Use [ast-grep-rule-recipes.md](ast-grep-rule-recipes.md) for exact examples.
## Impact and refactor planning
Use this sequence for changes that are more than a local edit:
1. **Ownership:** CodeGraph identifies the entry point, implementation, callers, dependents, and likely tests.
2. **Exact inventory:** ast-grep counts the syntax forms that will or will not change.
3. **Disagreement check:** graph and structural/path evidence are reconciled before scope is fixed.
4. **Patch boundary:** group the smallest reviewable file/symbol batches and identify shared-contract or generated-code boundaries.
5. **Rewrite proof:** for a mechanical rewrite, add rule fixtures and preview the exact reviewed scope.
6. **Approval:** obtain approval for the proposed files/pattern/rewrite, not a generic repository-wide permission.
7. **Apply and inspect:** make the smallest patch, inspect `git diff`, and verify no unrelated matches changed.
8. **Project validation:** run actual repository scripts such as targeted tests, typecheck, lint, or build.
If approval was already granted for the exact tested rewrite and unchanged scope, do not ask again. Any expanded path, rule, target version, or side effect requires renewed approval.
## Evidence reconciliation
Use a small evidence map:
| Evidence | What it proves | Common blind spot |
| ------------------------ | ----------------------------------------------------------- | --------------------------------------------------------------- |
| CodeGraph | Indexed semantic relationships and likely impact | Dynamic/reflection/generated/unsupported code, stale root/index |
| ast-grep | Parser-backed syntax matches for the rule/language | Semantic aliases/types/runtime dispatch, missed syntax variants |
| Runtime-native LSP | Symbols, references, types supported by the language server | Generated/dynamic code, incomplete workspace/project config |
| Text search/source reads | Literal presence and exact implementation | High noise, no semantic or AST guarantee |
| Project validation | Compiler/test/runtime contract exercised by the repo | Coverage gaps and tests that do not exist/run |
When results disagree:
1. verify CodeGraph root, status, watcher/pending state, and ignored/configured paths;
2. verify ast-grep language, parser, pattern, selector, and positive/negative fixtures;
3. inspect aliases, string-based registration, dependency injection, reflection, macros, generated files, and runtime loading;
4. read the smallest targeted source surface;
5. report the unresolved boundary instead of silently choosing the larger result.
Do not broaden immediately to repeated full-repository grep. A targeted text search is useful only when it tests a named gap.
## Fallback ladder
Use the first available trustworthy layer:
1. Exposed CodeGraph semantic MCP capability.
2. Help-confirmed CodeGraph CLI capability.
3. Runtime-native LSP symbol/reference/type tools.
4. Capability-gated `ast-grep outline` for lightweight structure.
5. ast-grep structural query/rule.
6. Bounded `rg`/file reads for literal or unsupported syntax.
7. Project-native compiler, tests, lint, or build for correctness.
State the degraded layer. Do not propose installing an optional server when a native LSP or existing tool already answers the task.
Read [extensions-and-escalation.md](extensions-and-escalation.md) only when this ladder cannot safely express a dedicated semantic backend, security/policy query, or multi-step migration.
## Output discipline
Return the minimum proof the user can act on:
- selected root and capability/version provenance;
- update state only when relevant or unavailable;
- focused findings with paths/symbols and evidence source;
- structural counts/variants and rule test state;
- disagreement or unsupported boundaries;
- proposed writes with approval state;
- commands actually run versus commands merely proposed;
- project validation and remaining risk.
Do not paste full configs, broad graph dumps, or hundreds of match lines. Summarize counts, give representative matches, and offer exact artifact paths or narrower follow-ups.
## Optional Visualizations and Actions
This reference applies to setup, update, doctor, and internal coding behaviors after setup. Visualization and action delivery are separate capabilities. Discover them from current host instructions and callable interfaces for this turn. Documentation, product names, or a prior turn do not prove availability. Unknown means unavailable for the current response. Follow the established native capability's documented rendering contract, including an HTML fragment file when required. Such a rendering input does not establish an action bridge or authorize repository writes. Do not install a renderer, create a Page, generate a standalone HTML report, or start a service as a fallback.
### Choose a useful view
| Situation | View | Details to preserve |
| ----------------- | ----------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------- |
| Setup readiness | Dependency map across CodeGraph, ast-grep CLI, client MCP, graph, and repository guidance | State, provenance, scope, checks, and gaps per component |
| Update | Version and provenance comparison with required migration steps | Channel, installed and target versions, configuration changes, index work, verification |
| Doctor | Filterable findings by severity and component | Checked and unchecked evidence, confidence, root, read-only boundary, next route |
| Impact analysis | Entry point to implementation, callers, dependents, and likely tests | Source-backed edges and dynamic or unindexed boundaries |
| Structural search | Pattern with representative matches and positive/negative examples | Language/parser, paths, match counts, exclusions, and coverage limits |
| Reviewed rewrite | Before/after view of the bounded patch | Exact files and pattern, changed count, tests, approval state, remaining matches |
Render only when interaction helps explore relationships, alternatives, or a meaningful result set. Small or simple results remain concise text. Build views only from evidence already obtained for the task; a view does not authorize extra repository reads. Label missing evidence as unknown, never as an empty result. Keep an equivalent chat result with findings, provenance, limitations, and next steps. Use accessible labels, keyboard navigation, and cues beyond color.
### Actions
An action is callable only when the current host documents a callback from the visible visualization to the agent and exposes the requested operation. Native ChatGPT Visualize availability does not establish such a callback. Apps SDK or other widget bridges apply only in their own supported integrations. Never guess a JavaScript bridge, send a hidden shell command from rendered content, or treat a suggested prompt as an executed action.
For every action, show the operation, repository root, affected scope, expected writes, and relevant evidence before the click. A genuine host-delivered click on that exact visible action is a user request within that scope. Recheck current state, selected tool capabilities, and existing approvals before acting; retain any approval or confirmation required by the host or task. A changed target, write set, destructive step, or external action is outside the click's scope and follows the ordinary approval boundary.
Filtering, zooming, expanding details, and opening evidence are view-only. Repeated clicks or an unknown prior execution result never justify blind mutation replay: inspect current state and report uncertainty. Keep `doctor` non-repairing; an approved follow-up enters the matching setup/update or coding behavior.
When no documented callback is available, present the complete bounded action as text the user can submit in chat. Clearly label it as a proposed follow-up. If native rendering is missing, fails, or its outcome cannot be verified, continue with the complete text result and do not retry automatically. Do not claim an action or render succeeded without current evidence.
SKILL.md
---
name: codegraph-ast-grep
description: Set up, update, or diagnose CodeGraph and ast-grep so coding agents can use semantic repository scope and structural syntax evidence automatically. Use when a repository needs an idempotent CodeGraph/ast-grep installation, stable tool and index migrations, MCP reconnection, persisted agent guidance, or a read-only setup diagnosis.
license: Apache-2.0
metadata:
author: stark-ai-de
category: engineering-workflows
version: "0.4.0"
---
# CodeGraph + ast-grep
## Goal
Make a repository's coding agents ready to use CodeGraph for semantic scope and ast-grep CLI for structural evidence. Public workflows manage that capability; repository exploration and refactoring are ordinary internal coding behaviors after setup.
## When to use
- Install or reconcile CodeGraph, ast-grep CLI, MCP exposure, indexing, and agent guidance.
- Update the installed analysis stack and run required configuration, index, or schema migrations.
- Diagnose a missing, stale, disconnected, or apparently broken setup without repairing it.
## When not to use
Do not activate this skill merely because a coding task can benefit from an already-ready analysis stack. Follow the persisted repository guidance instead. Do not use it for general dependency audits, compiler/runtime proof, or an unreviewed broad rewrite.
## Workflow selection
The complete finite workflow inventory, in plain, benefit-first language, is:
- `setup`: supercharge the repository with Semantic Code Intelligence and structural code search, helping coding agents explore repository code with semantic and structural evidence. Install missing pieces, connect the coding client, build the code index, add repository guidance, and safely reuse or repair any existing setup.
- `update`: bring an existing setup to current stable versions without changing how it was installed. Migrate configuration or index data when needed, reconnect the coding client, and verify that everything still works.
- `doctor`: diagnose setup health and report analytics without repairing anything.
Show the complete finite workflow inventory in its documented order for a bare or materially ambiguous invocation, or an explicit options request. An options request alone does not authorize execution or repository/tool inspection; answer from the documented inventory. For clear authorized intent, announce only the selected workflow and rationale, with material scope and evidence fields, and proceed.
There is no `auto` workflow. Select by intent:
- An explicit setup or installation request selects `setup`.
- An explicit stable-tool update, migration, or refresh request selects `update`.
- “Something is broken,” a health check, or a request for setup analytics selects `doctor`.
- A bare invocation or ambiguous intent requires showing all three workflows and asking the user to choose.
For clear direct intent, state only the selected workflow, rationale, root, expected writes/artifacts, and protected state, then proceed. Agent-initiated activation may select and announce only `doctor`; it must not infer setup or update authority. Selecting `setup` or `update` is allowed only when the user already requested that outcome for the stated root. Privileged/global installation, paid or external services, publication/deployment, destructive replacement, telemetry changes, and scope expansion retain separate approval.
## Inputs to inspect
- Exact repository root, nested repositories or monorepo packages, package/declarative policy, and protected Git state.
- Effective `CODEGRAPH_DIR` (default `.codegraph/`), root `codegraph.json` when supported, `sgconfig.yml`/`sgconfig.yaml`, and repository instruction files.
- Executable paths, installer channel and scope, version pins, installed help, configured client, and exposed MCP tools.
- Approved scope for package/config/index writes and any exact-root project opening that may migrate generated metadata.
## Workflow
### `setup`
1. Capture the exact root, protected state, runtime client, package/declarative policy, existing installer provenance, and offline/telemetry constraints.
2. Inspect existing binaries, configuration, MCP exposure, state paths, and repository guidance before changing anything. Installed help and exposed tools are authoritative.
3. Reconcile the stable CodeGraph release and stable ast-grep CLI through the repository's approved installer channel and scope. Do not install the experimental ast-grep MCP server during normal setup.
4. Configure the selected runtime client and CodeGraph project root, then perform the help-confirmed initialization and any required configuration/index/schema migration within the approved root.
5. Persist concise repository-native guidance for coding agents. It must say, in equivalent terms: use CodeGraph for semantic symbols, callers, call paths, and impact; use ast-grep CLI for structural syntax evidence; reconcile both before broad edits.
6. Reconnect or restart the client when required, then verify one semantic query, one bounded structural query, state freshness, and guidance discovery.
7. Report installed versions/provenance, writes, migration/reconnection evidence, readiness, and remaining limitations.
Setup is idempotent and agent-complete: rerunning it reconciles drift instead of duplicating config, instructions, indexes, or dependencies.
### `update`
1. Capture the same root, policy, protected-state, telemetry, and provenance evidence as setup.
2. Compare installed core tools with their authoritative stable channels once. Respect offline intent, `DO_NOT_TRACK`, `CODEGRAPH_NO_UPDATE_CHECK`, registry restrictions, and repository pins.
3. Preserve the existing installer channel and global/project/declarative scope. Update only the stable CodeGraph and ast-grep CLI components selected by repository policy; never run a blanket update-all operation.
4. Run every version-required configuration, index, or schema migration in the approved root. Keep binary replacement, runtime-config changes, prompt hooks, telemetry, and graph operations visible in the execution receipt.
5. Reconnect/restart the client, refresh the graph only as required, and verify versions/PATH, MCP exposure, graph readiness, a semantic query, a structural query, and persisted guidance.
6. If an update fails, stop further mutation, preserve config/index state, report what still works, and use only a pre-disclosed safe rollback.
The user's explicit update request authorizes ordinary in-root update and required migration work. Ask separately for privilege escalation, installer-channel or scope changes, unrelated dependency changes, destructive rebuilds, or external-service actions.
### `doctor`
1. Inspect executable/provenance, versions/help, config presence, MCP registration, state paths, ignore policy, repository guidance, and non-opening connectivity evidence.
2. Do not install, update, reconnect by writing config, initialize/rebuild/sync, repair, or rewrite source.
3. Before `codegraph status`, an MCP graph query, or another diagnostic that opens a project and may migrate generated metadata, name the exact root and obtain affirmative approval, or use an approved disposable copy. Without that approval, report the skipped deep check.
4. When approved, gather bounded graph health and useful analytics such as freshness, indexed languages, symbol/file coverage, and query readiness. Do not describe this as strictly read-only if metadata migration was possible.
5. Return diagnosis, evidence, confidence, recommended `setup` or `update` follow-up, and any unverified boundary. Do not repair as part of `doctor`.
## Internal coding behaviors
Once the setup is ready, coding agents use these behaviors without treating them as public skill modes:
Routine semantic exploration, structural search, impact analysis, rule authoring, and reviewed rewrites are internal coding behaviors.
- **Semantic exploration:** prefer exposed `codegraph_explore`, then installed-help-confirmed `codegraph explore`, then narrower verified CodeGraph capabilities.
- **Structural search:** use ast-grep CLI after the syntax shape is known; specify language when ambiguous and bound paths/output.
- **Impact analysis:** reconcile semantic ownership/call paths with structural match inventory and targeted source reads.
- **Rule authoring:** use tested YAML rules for reusable or relational patterns, including positive and negative fixtures.
- **Reviewed rewrites:** inventory, test, preview, approve exact bounded scope, apply, inspect the diff, and run repository-native validation.
When semantic and structural evidence disagree, check graph freshness/root, parser/language, generated or dynamic code, ignore rules, and targeted source before claiming coverage. Runtime-native LSP and bounded text/file inspection are fallbacks; neither core tool is compiler, type, taint, or runtime proof.
## Optional visual output
Use native interactive visualization only when the current host exposes a documented, callable capability and the result benefits from exploration. Keep ordinary results concise. The complete findings, evidence, uncertainty, and next steps must remain available in chat if rendering or interaction is unavailable. A visualization never establishes correctness or grants authority. Follow [visualization and actions](references/usage-playbook.md#optional-visualizations-and-actions) for selection, fallback, and action boundaries.
## Safety rules
- Keep ast-grep CLI as the supported default; the experimental ast-grep MCP server is excluded from normal setup.
- Suppress CodeGraph telemetry for skill-driven checks and approved setup/update commands with `CODEGRAPH_TELEMETRY=0` unless the user separately consented to telemetry. Default-on telemetry is not consent.
- Prefer exact packages or checksummed release assets. Do not default to pipe-to-shell or pipe-to-PowerShell installation.
- Preserve installer channel and scope; do not bypass package-manager freshness, trust, lifecycle-script, checksum, or declarative policy.
- Do not invent `.codegraph/config.json`. Treat effective `CODEGRAPH_DIR` as generated state and root `codegraph.json` as version/capability dependent.
- Do not assume auto-sync without an active supported watcher or require manual sync when status proves freshness.
- Do not apply an untested ast-grep rewrite or indiscriminately accept snapshots/update-all behavior.
- Redact secrets, static headers, customer data, private service names, and internal hostnames from persisted or public artifacts.
## References
Read only what the selected workflow or later coding task needs:
- `references/setup-and-mcp-config.md` for installation scopes, runtime configuration, state paths, and initialization.
- `references/update-and-provenance.md` for stable channels, provenance-preserving updates, migrations, verification, and rollback.
- `references/troubleshooting.md` for the read-only doctor ladder and follow-up routing.
- `references/codegraph-capability-guide.md` for current/legacy capability discovery, graph freshness, and exact-root project opening.
- `references/usage-playbook.md` for the persisted agent guidance and internal semantic/structural/impact behaviors.
- `references/ast-grep-rule-recipes.md` for bounded CLI patterns, rules/tests, and reviewed rewrites.
- `references/extensions-and-escalation.md` only when the core stack cannot safely express the task.
## Scripts
No runtime scripts. Use installed tools and repository-native validation commands; the catalog's deterministic contract validator is maintainer-only and is not installed with the skill.
## Output format
Report the selected workflow and rationale, exact root, protected state, installer provenance, versions/capabilities, writes or skipped writes, migrations/reconnect state, verification evidence, and remaining limitations. For `doctor`, separate non-opening evidence from exact-root deep analytics and provide diagnosis plus a recommended follow-up without repair.
## Completion criteria
- The selected `setup`, `update`, or `doctor` workflow and intent rationale are explicit.
- Setup/update preserve provenance and protected state, and required migrations/reconnection are verified.
- Target-repository guidance makes semantic plus structural evidence the default for broad coding work.
- Doctor performs no repair and labels exact-root graph-opening approval and possible metadata mutation accurately.
- Readiness is proven with verified capabilities and representative semantic/structural checks, or limitations are explicit.
## Failure modes
- If intent or root is ambiguous, expose all three workflows and ask before inspection or mutation.
- If stable metadata is blocked, report `not checked`; do not bypass offline, opt-out, registry, or pinning policy.
- If setup/update needs an unauthorized privilege, channel, scope, destructive rebuild, or external action, preserve current state and request that specific authority.
- If a tool or client remains unavailable, retain verified intermediates/configuration, report incomplete readiness, and give the narrowest next action.
- If evidence conflicts, report the disagreement and confidence rather than claiming complete semantic or structural coverage.