Commit Graph
88 Commits
Author SHA1 Message Date
Colby McHenry a15ad69288 Remove unused detectApiIntent and inferRouteDirectories
Both functions have zero callers — dead code on arrival. Remove them
and their tests (9 tests) to keep the module focused on what's
actually used: search term extraction, path relevance scoring, and
kind bonuses.
2026-02-10 16:05:46 -06:00
Colby McHenry 36af284e10 Remove redundant code and deduplicate indexFile
- Remove extractFunctionVariable() and its dispatch (already handled by extractVariable)
- Remove dead getGrammar() export (zero callers)
- Deduplicate indexFile by delegating to indexFileWithContent
- Remove redundant arrow function variable extraction tests (covered by existing suite)
2026-02-10 15:55:43 -06:00
Colby McHenry ce220a573c Resolve merge conflict with main (gitignore + symlink rename)
Keeps the PR's visitedDirs rename and main's gitIgnoredDirs addition.
2026-02-10 15:44:56 -06:00
Martin Oehlert 0f2eda8da3 feat: file nodes, arrow function extraction, parallel I/O
- Create file-kind nodes for each parsed source file
- Add isInsideClassLikeNode() for method vs function detection
- Extract arrow functions and function expressions from variable declarators
- Batch file I/O with FILE_IO_BATCH_SIZE=10 using Promise.all
- Add symlink cycle detection with visitedDirs Set in scanDirectory
- Add lazy grammar loading with exported getGrammar() function
- Add indexFileWithContent() for pre-read content processing
- Add tests for file nodes and arrow function extraction
2026-02-10 11:47:07 +01:00
Martin Oehlert c80378d73c feat: search query utilities and multi-signal scoring
- Add src/search/query-utils.ts with extractSearchTerms, scorePathRelevance,
  kindBonus, detectApiIntent, inferRouteDirectories
- Add multi-signal scoring to searchNodes (kind bonus + path relevance)
- Improve FTS query sanitization (strip :^ chars, filter boolean operators)
- Add comprehensive search tests
2026-02-10 11:40:41 +01:00
Martin Oehlert 53beb1bd2f feat: schema v2 migration, database performance, batch query methods
- Add provenance column on edges for tracking how edges were created
- Add project_metadata table for version/provenance tracking
- Make unresolved_refs file_path/language NOT NULL with defaults
- Add composite indexes for unresolved_refs and edges.provenance
- Update v2 migration to handle all new schema additions
- Record schema version on initialize to prevent re-migration
- Add dynamic prepared statement cache (getDynamicStmt) for varying SQL
- Add batch methods: getNodesByIds, getNodesByKinds, getFileHashMap, getFileSyncMap
- Add project metadata methods: getMetadata, setMetadata, getAllMetadata
- Optimize getStats to use single aggregate query
- Optimize getStaleFiles to use temporary table JOIN
- Add provenance parameter to getOutgoingEdges
- Add intent field to SearchOptions type
2026-02-10 11:31:05 +01:00
Martin Oehlert 399d78b938 security: path validation, ReDoS prevention, picomatch, PID-based file lock
- Add validateProjectPath() to reject sensitive system directories
- Add isPathWithinRoot/isPathWithinRootReal for symlink-aware path checks
- Replace hand-rolled glob-to-regex with picomatch to prevent ReDoS
- Add isSafeRegex() to reject custom patterns with nested quantifiers
- Replace FileLock with PID-tracking version that detects stale locks
- Add symlink detection in removeDirectory/listDirectoryContents
- Add subdirectory name validation in ensureSubdirectory
- Add atomicWriteFileSync and corrupted file backup in config-writer
- Add MCP input validation (validateString) for all tool handlers
- Fix CLAUDE.md section replacement to handle ### subsections correctly
2026-02-10 11:22:04 +01:00
Colby McHenryandClaude Opus 4.6 62a6cf38fe Fix .gitignore support and Windows path separator bug in scanner
Normalize paths to forward slashes in matchesGlob() and scanDirectory()
so glob exclude patterns work on Windows. Add getGitIgnoredDirectories()
using git ls-files to skip .gitignore'd directories during indexing.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-10 04:08:10 -06:00
Colby McHenry 2ad03d2f7d updates 2026-02-10 02:26:47 -06:00
Colby McHenryandClaude Opus 4.6 4c983ba082 Add Svelte language support with SvelteKit framework resolver
- Add 'svelte' to Language type, DEFAULT_CONFIG includes, grammars, and config validation
- Add SvelteExtractor that extracts <script> blocks and delegates to TS/JS TreeSitterExtractor
- Add Svelte framework resolver for runes ($state, $derived, $effect, etc.), store auto-subscriptions, SvelteKit module aliases ($app/*, $env/*, $lib/*), and SvelteKit route detection
- Update README to list Svelte and Dart in supported languages

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-10 01:32:52 -06:00
Colby McHenryandClaude Opus 4.6 f46ba02b87 Add Claude Code hooks for automatic CodeGraph sync
PostToolUse(Edit|Write) marks the project dirty via .codegraph/.dirty,
and Stop syncs only if dirty — batching all edits into one sync per
Claude response. The installer now writes these hooks to settings.json.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-10 01:12:43 -06:00
Colby McHenryandClaude Opus 4.6 c3cf891bf4 Fix UNIQUE constraint crash on large C/C++ projects
Node insertion used plain INSERT which crashes on duplicate IDs.
In large C/C++ projects, tree-sitter can produce duplicate nodes for
the same symbol (e.g. typedef struct where both struct_specifier and
type_definition resolve to the same name/kind/line, or multiple
anonymous constructs on the same line).

- Change nodes INSERT to INSERT OR REPLACE (idempotent, same data)
- Change edges INSERT to INSERT OR IGNORE (skip duplicate edges)

The node ID is sha256(filePath:kind:name:line) which already uses full
relative paths, so cross-directory collisions are not the issue.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-10 00:40:18 -06:00
Colby McHenryandClaude Opus 4.6 ab5f9a03ef Improve MCP tool symbol disambiguation and output truncation
- Add findSymbol() helper that prefers exact name matches and notes
  alternatives when multiple symbols share the same name
- Add output truncation (15K char cap) to prevent context window bloat
- Apply to callers, callees, impact, node, search, and files tools

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-10 00:05:56 -06:00
Colby McHenryandClaude Opus 4.6 9ea4be3c24 Add CLI uninit command to remove CodeGraph from a project
Exposes the existing uninitialize() method via `codegraph uninit [path]`.
Includes confirmation prompt (skippable with --force) before deleting
the .codegraph/ directory.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-10 00:02:52 -06:00
Colby McHenryandClaude Opus 4.6 94c8d5ccaa Port extraction quality improvements from PR #15
- Fix arrow function extraction: explicitly call extractFunction() for
  arrow functions/function expressions in variable declarations instead
  of silently skipping them (all 6 arrow function tests now pass)
- Best-candidate resolution: collect candidates from all strategies and
  return highest confidence match instead of first match
- Fix graph traversal 'both' direction: correctly determine next node
  for mixed incoming/outgoing edges in BFS and DFS

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-09 23:55:00 -06:00
Colby McHenryandClaude Opus 4.6 d80900f653 Port performance improvements from PR #15
- SQLite performance pragmas: synchronous=NORMAL, 64MB cache,
  memory temp store, 256MB mmap (safe with WAL mode)
- Batch insert for unresolved refs: single transaction instead of
  N individual inserts per file
- Symbol caching (warmCaches): pre-load all nodes into memory maps
  before resolution, eliminating repeated SQLite queries per ref
- Async file I/O: fs.stat/readFile in indexFile() are now non-blocking
- Denormalize filePath/language onto UnresolvedReference: avoids N
  node lookups during resolution, with schema migration v2

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-09 23:45:34 -06:00
Colby McHenryandClaude Opus 4.6 e07250ed60 Port bug fixes and stability improvements from PR #15
- Fix Float32Array embedder bug: was creating zero-filled array instead
  of copying data from TypedArray-like objects
- Fix VSS search query: use subquery pattern so LIMIT applies before JOIN
- Pin tree-sitter versions: remove caret ranges for ABI stability, add
  overrides to lock tree-sitter core at 0.22.4
- Lazy grammar loading: load native bindings on first use per language
  instead of all at startup, so one missing grammar doesn't affect others
- Remove stale src/extraction/queries copy from copy-assets script

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-09 23:40:37 -06:00
Colby McHenryandClaude Opus 4.6 932c567d18 Security hardening: path validation, input clamping, safe JSON, file locking
Implements security improvements inspired by PR #16 (credit: MO2k4):

- Add validatePathWithinRoot() to prevent path traversal attacks in
  extraction and context building
- Clamp MCP tool inputs (limit, depth, maxDepth) to sane ranges
- Use atomic writes (temp file + rename) for config saves
- Add symlink cycle detection in directory scanning to prevent infinite loops
- Replace all JSON.parse calls in db/queries.ts with safeJsonParse fallbacks
  to handle corrupted database metadata gracefully
- Add cross-process FileLock for DB write operations (indexAll, indexFiles,
  sync) to prevent concurrent writes from CLI, MCP server, and git hooks
- Remove unused path import from context/index.ts

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-09 23:18:40 -06:00
Colby McHenryandClaude Opus 4.6 38fac1ff28 Merge PR #18: Fix arrow function/export indexing + type alias extraction
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-09 22:36:26 -06:00
Colby McHenry d0ee6f7fc4 Enhances code extraction and project indexing
Adds support for Dart and Liquid languages with tree-sitter parsing.
Improves accuracy of code symbol extraction for existing languages.
Indexes project files to enhance code navigation features.
Migrates build system to facilitate code contributions.
Removes git hook functionality.
Integrates Sentry for error tracking and reporting.
Enhances project initialization and configuration loading.
2026-02-09 22:18:59 -06:00
Tanner Balluff ea9d0bf549 Add type alias and exported variable extraction
Extend extraction to index two additional categories of symbols
that were previously invisible:

1. Type aliases (e.g. `export type X = ...` in TypeScript,
   `type X` in Go, `type X = ...` in Rust, `typealias X` in Swift,
   `type_alias` in Kotlin). Adds `typeAliasTypes` to the
   LanguageExtractor interface with values for all 13 languages.

2. Exported variable declarations that aren't functions, including:
   - Zustand stores: `export const useX = create(...)`
   - XState machines: `export const xMachine = createMachine(...)`
   - Zod schemas: `export const schema = z.object(...)`
   - Config objects: `export const config = { ... }`
   - Constants: `export const MAX = 3`
   - Arrays: `export const NAMES = [...] as const`

   The extractExportedVariables() method is called when visiting
   export_statement nodes. It skips variable_declarator values that
   are already handled by functionTypes (arrow_function,
   function_expression) to avoid duplicate extraction.

Adds 11 new test cases (59 total extraction tests, 215 total).

Tested on production monorepo: nodes increased from 958 to 1,172
(+22%), with 109 new variable nodes and 105 new type_alias nodes.
Only 4 files remain at 0 nodes — all are re-export barrels or
ambient declaration files with no extractable symbols.
2026-02-09 14:48:09 -05:00
Tanner Balluff b6d5346c3c Fix arrow function and function expression export indexing
Arrow functions and function expressions assigned to variables
(e.g. `export const useAuth = () => { ... }`) were not being indexed
because the arrow_function AST node has no `name` field — the name
lives on the parent variable_declarator node.

Additionally, `isExported()` for TypeScript and JavaScript extractors
only checked 10 characters back from the node's start position, which
missed `export` for deeply nested nodes like arrow functions inside
variable declarations inside export statements.

Changes:
- extractFunction(): When an arrow_function or function_expression
  resolves to '<anonymous>', look up the parent variable_declarator
  for the name before skipping.
- isExported() (TS + JS): Walk the parent chain to find an
  export_statement ancestor instead of substring matching.
- Add 6 test cases covering arrow function exports, function
  expression exports, non-exported arrow functions, anonymous
  arrow functions, multiple exports, and JavaScript files.

Tested on a real monorepo (238 files): node count increased from
779 to 958 (+23%), with 94 new nodes in packages/ that previously
had 0 coverage.
2026-02-09 14:35:15 -05:00
Colby McHenryandClaude Opus 4.5 f0ddfccf47 Skip global install if codegraph command already exists
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-21 13:40:29 -06:00
Colby McHenryandClaude Opus 4.5 3ad4d5b35d Download embedding model to ~/.codegraph/models on install
The nomic-ai model is now downloaded during npm install via a postinstall
script and stored globally in ~/.codegraph/models (shared across projects)
instead of per-project in .codegraph/models.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-21 13:29:03 -06:00
Colby McHenryandClaude Opus 4.5 47af81aee7 Remove codegraph_explore tool in favor of native Explore agents
The hybrid approach (Claude's native Explore agents using codegraph tools)
is more effective than a custom explore tool because Explore agents already
know what format the main session needs.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-19 21:14:52 -06:00
Colby McHenryandClaude Opus 4.5 a4ddedb197 Add Liquid template language support for Shopify themes
- Add 'liquid' to Language type and default include patterns
- Create LiquidExtractor with regex-based extraction (tree-sitter-liquid has ABI issues)
- Extract render/include/section references as component nodes
- Extract schema blocks as constant nodes with parsed names
- Extract assign statements as variable nodes
- Create file relationship edges for snippet/section references

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-19 15:59:40 -06:00
Colby McHenryandClaude Opus 4.5 8d1fb680e5 Installer now creates/updates CLAUDE.md with CodeGraph instructions
- Added claude-md-template.ts with the instructions template
- Installer writes to ~/.claude/CLAUDE.md (global) or ./.claude/CLAUDE.md (local)
- Smart detection: updates existing CodeGraph section or appends if not found
- Uses HTML comment markers for reliable section replacement on upgrades

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-19 15:30:13 -06:00
Colby McHenryandClaude Opus 4.5 1ca43a85e0 Installer now installs codegraph globally
The installer runs `npm install -g @colbymchenry/codegraph` so users
can simply run `codegraph init -i` instead of the full npx command.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-19 15:20:53 -06:00
Colby McHenryandClaude Opus 4.5 26f8f2f59f Fix next steps to use npx instead of global codegraph command
Users running via npx don't have the codegraph command installed
globally. Update installer message and README to use
npx @colbymchenry/codegraph init -i instead.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-19 15:18:47 -06:00
Colby McHenryandClaude Opus 4.5 c87c5487aa Fix ESM import error for @xenova/transformers
Change static import to dynamic import() for @xenova/transformers
which is an ESM-only package. This fixes ERR_REQUIRE_ESM when
running via npx in CommonJS environments.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-19 15:11:40 -06:00
Colby McHenryandClaude Opus 4.5 9baf59e5f0 Add interactive CLI installer for Claude Code integration
- New `codegraph install` command and auto-run when invoked with no args
- Beautiful ASCII banner using figlet
- Interactive prompts for global (~/.claude) or local (./.claude) installation
- Writes MCP server config to claude.json
- Writes auto-allow permissions to settings.json
- For local installs: auto-initializes project, indexes, and installs git hooks

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-19 14:31:29 -06:00
Colby McHenry e26ec13f7f Reset to 0.1.8 best version so far 2026-01-19 04:53:32 -06:00
Colby McHenryandClaude Opus 4.5 ef6f2ae50b codegraph_explore now reads code internally (sub-agent behavior)
Instead of returning file paths for Claude to read separately,
codegraph_explore now:
- Reads relevant files internally using fs
- Extracts code snippets for key symbols (functions, types, APIs)
- Includes the code directly in the response
- Returns a synthesis with data flow and key code included

This matches native explore agent behavior where file reading
happens in the sub-agent context, keeping main context clean.

Bump version to 0.1.8

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-19 03:16:05 -06:00
Colby McHenryandClaude Opus 4.5 0ecd195f15 Add explicit action items to codegraph_explore output
- Move warnings to TOP of output so Claude sees them first
- If existing implementations found: "STOP: Similar implementations exist!"
- If feature request: "BEFORE PLANNING: Use AskUserQuestion to clarify..."
- Update tool description to emphasize checking existing code first
- Fixes issue where Claude listed questions but never asked them

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-19 03:04:11 -06:00
Colby McHenryandClaude Opus 4.5 43cee17dc3 Make codegraph_explore language-agnostic
- Pattern generation now uses multiple naming conventions:
  PascalCase, snake_case, and camelCase
- Common suffixes/prefixes work across languages (Service,
  Handler, Controller, handle_, create_, etc.)
- Removed JS/React-specific patterns like useBundle, SwapDialog
- Bump version to 0.1.6

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-19 02:53:50 -06:00
Colby McHenryandClaude Opus 4.5 0c168c4d8b Add codegraph_explore tool and expand exclude patterns
- Add codegraph_explore MCP tool for deep exploration with condensed output
- Expand default exclude patterns for framework build outputs (.next, .nuxt, .expo, etc.)
- Increase node ID hash length from 16 to 32 chars to prevent collisions
- Add feature request detection with UX clarification reminders
- Update README with MCP tools reference and best practices
- Update CLAUDE.md with context usage guidelines

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-19 02:42:34 -06:00
Colby McHenryandClaude Opus 4.5 6b672f9152 Add evaluation framework and fix call graph extraction
- Add evaluation test suite with TypeScript and Python fixtures
- Fix MCP server to defer CodeGraph init until rootUri received
- Fix call edge extraction by calling resolveReferences() after indexAll/sync
- Fix glob matching for root-level files (e.g., **/*.py now matches auth.py)
- Fix duplicate node extraction for methods inside classes
- Update context tests to use buildContext for semantic search + graph traversal
- Export unused formatter functions to fix build

Evaluation results:
- TypeScript: 96% precision, 79% recall, 85% F1
- Python: 99% precision, 80% recall, 85% F1

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-18 18:48:22 -06:00
Colby McHenry cc6e7a5c89 Init 2026-01-18 16:25:00 -06:00