Skip to content

Latest commit

 

History

History
387 lines (297 loc) · 16.2 KB

USER_GUIDE.md

File metadata and controls

387 lines (297 loc) · 16.2 KB

Codetrip User Guide

Codetrip is a Hybrid Graph-Augmented Code Intelligence Engine with three supported integration surfaces: Go library, CLI, and MCP. All three use the same persisted repository snapshots and public Engine operations.

Data and update model

The default data directory is ~/.codetrip; override it with the global --dir flag.

repos/<id>/
  manifest.json  logical repository metadata
  graph/db/      authoritative graph, adjacency, and active pointer
  index/         versioned symbol indexes
  content/       versioned source indexes
  vectors/       optional semantic data
trash/           interrupted deletion cleanup

Each logical repository owns an independent database and points to one immutable physical snapshot. Repository databases open lazily, so accessing one project does not lock unrelated projects. Every successful changed update builds a copy-on-write snapshot, publishes the active pointer only after all derived indexes succeed, and then retires the previous snapshot. Codetrip never modifies the active snapshot in place. Data created by the earlier shared-database layout must be reindexed.

CLI

All business commands are single words:

Command Purpose
index Parse and persist a repository
delete Delete a repository and all persisted data
brief Build a bounded, evidence-backed context pack for one symbol
search Search symbols and metadata
source Search code, engineering configuration, or documentation contents
embed Build semantic data for a repository
hybrid Fuse symbol and semantic retrieval
context Explain a symbol and its direct semantic neighborhood
impact Analyze symbols affected by a change
check Check graph integrity and repository structure
diff Map Git changes to symbols and affected code
rename Plan a symbol rename without modifying source
traverse Run bounded BFS from a node
path Find a shortest directed path
export Export the persisted graph as CSV
list List active logical repositories
mcp Start the stdio MCP server or configure supported agent clients
version Print the build version

Index and refresh

codetrip index /src/project --repo project
codetrip index /src/project --repo project --full
codetrip index /src/project --repo project --replace

Index flags:

Flag Meaning
--repo Logical repository name; defaults to the source directory name
--full Force a complete rebuild and atomically publish it
--replace Compatibility alias for --full
--export Write deterministic parser-inspection CSV files to a directory
--export-strict Fail indexing if parser CSV generation fails

The CLI uses automatic update mode by default. It reports one of these modes:

Mode Meaning
noop No eligible source file changed; the active snapshot is reused
incremental Only invalidated files and their semantic dependents are reparsed; graph, symbol, source, and vector deltas are committed to the existing snapshot
full-fallback A safe incremental update was not possible, so a complete snapshot was rebuilt
full A complete build was explicitly requested or no prior repository existed

Incremental mode uses content, structure, and call-shape fingerprints across supported languages. Call-stable body edits use a file-local delta without materializing the complete graph. Call changes refresh callable relationships, while declaration/import/interface changes expand through semantic dependents. Add, delete, and rename operations update graph and search indexes in one revision. Incompatible analyzer state safely falls back to a full build. Changed node vectors are invalidated; run embed to regenerate them. A noop keeps existing vectors.

Delete a logical repository, including every graph, source, symbol, and vector snapshot:

codetrip delete project

The library exposes the same operation as Engine.DeleteRepo. Destructive deletion is intentionally not exposed through MCP.

Symbol brief

codetrip brief ParseConfig --repo project
codetrip brief ParseConfig --repo project --format text

brief is the recommended starting point when an Agent needs to understand one symbol. It returns the declaration and source excerpt, direct typed relationships with confidence and evidence, incoming impact counts, related tests, and explicit budget-truncation state. Output is deterministic and does not invoke an LLM. JSON is the default for integrations; --format text provides a compact terminal view.

The symbol may be an exact name or a stable node ID. When a name is ambiguous, Codetrip returns the candidates instead of guessing. Source line coordinates are one-based.

Search

codetrip search "ParseConfig" --repo project --limit 20
codetrip source 'lang:go file:config ParseConfig' --repo project --context 2
codetrip source 'deployment architecture' --repo project --scope docs
codetrip source 'NewHTTPServer' --repo project --scope all

search targets indexed symbols and metadata. source searches repository text and supports literal, regular-expression, file, and language filters. Its --scope is code by default: code includes programming languages and engineering configuration, docs searches documentation only, and all searches both. Binary files, dependencies, build output, caches, and unsupported text remain excluded.

Linux and macOS use the native high-throughput source backend. Windows uses a portable full-text backend followed by exact line matching. The public API and query features are the same, but Windows source search is slower on large repositories. Rebuild a repository snapshot after moving its data directory between Windows and Linux/macOS because their source-index formats differ. Reindex existing repositories after upgrading to the scoped source-index format.

Semantic and hybrid retrieval

codetrip embed --repo project \
  --endpoint http://localhost:11434/v1/embeddings \
  --model nomic-embed-text \
  --dimensions 768

codetrip hybrid "configuration loading" --repo project \
  --endpoint http://localhost:11434/v1/embeddings \
  --model nomic-embed-text \
  --dimensions 768

Use --quantize-int8 on embed when a compact semantic representation is required. The API key may be supplied with --api-key or CODETRIP_EMBEDDING_API_KEY.

Graph traversal

codetrip context ParseConfig --repo project
codetrip context ParseConfig --repo project --relations CALLS,IMPLEMENTS
codetrip impact ParseConfig --repo project --depth 3 --limit 100
codetrip impact ParseConfig --repo project --change signature
codetrip impact ParseConfig --repo project --format tree
codetrip check --repo project
codetrip check --repo project --checks confidence --confidence 0.7
codetrip traverse ParseConfig --repo project --direction both --depth 3
codetrip traverse ParseConfig --repo project --relations CALLS,IMPORTS
codetrip path LoadConfig ParseConfig --repo project

context, impact, traverse, path, and rename accept either an exact symbol name or a stable node ID. When an exact name matches multiple symbols, the CLI lists their file locations and node IDs instead of choosing one. impact returns JSON by default; use --format tree for a compact terminal view with a symbol and file summary. --change accepts behavior, signature, contract, or remove. When omitted, functions and methods default to behavior, interfaces to contract, and types to signature.

context returns the symbol, its source excerpt when the original checkout is available, and direct typed relationships. It excludes structural graph noise by default. impact separates confirmed dependents, contract impacts, entry points, related tests, and review candidates. Every item includes its evidence path and why it may be affected; uncertain dispatch remains explicitly marked for review and cannot become confirmed later in the path. It defaults to depth 3 and supports --relations for narrower analysis.

check runs integrity and cycles by default. Integrity reports missing edge endpoints and invalid self-dependencies. Cycle analysis distinguishes inheritance cycles (errors) from import cycles (warnings). The optional confidence check reports semantic relationships below --confidence; it is not enabled by default because it is intended for focused review rather than as a correctness failure.

Change analysis

# Compare HEAD with tracked working-tree changes.
codetrip diff --repo project

# Compare two commits.
codetrip diff HEAD~1 --target HEAD --repo project

# Map changed symbols without reverse impact expansion.
codetrip diff HEAD~1 --target HEAD --repo project --no-impact

diff parses zero-context Git hunks, maps changed lines to persisted actionable symbols, and aggregates impact results with the changed symbols recorded as causes. It uses the source directory stored in the repository manifest and restricts Git output to that directory, including when the indexed repository is a subdirectory of a larger worktree. Untracked files are not included until they are added to Git and indexed.

Rename planning

codetrip rename ParseConfig LoadConfig --repo project

rename is analysis-only and never edits files. It validates the requested identifier, reports same-file conflicts as errors and repository-wide collisions as warnings, follows incoming typed relationships to identify semantic references, and searches the code index for exact identifier occurrences. Declaration and graph-backed reference lines are marked as high-confidence edits; comments, strings, reflective access, and other textual candidates remain explicitly marked requiresReview.

Canonical traversal directions are out, in, and both. Agent-friendly aliases are accepted: forward, down, downstream, and call map to out; reverse, backward, up, and upstream map to in; any, all, and bidirectional map to both. Direction controls edge orientation, while --relations CALLS restricts the relationship type. The engine enforces a configurable visit limit.

CSV

Validation CSV captures the ingest result before persistence and is intended for language tuning:

codetrip index /src/project --repo project \
  --export ./local-review/project --export-strict

Full export reflects the active persisted graph:

codetrip export --repo project --output ./exports/project

It writes nodes.csv, edges.csv, and manifest.json with row counts and SHA-256 checksums.

Go library

Open and configure

engine, err := codetrip.Open("./.codetrip",
    codetrip.WithCacheSize(512<<20),
    codetrip.WithMaxConcurrentIndex(2),
    codetrip.WithNodeCacheSize(500_000),
    codetrip.WithTraversalLimit(100_000),
    codetrip.WithScalePreset(codetrip.ScaleMedium),
)
if err != nil { /* handle */ }
defer engine.Close()

Index and inspect repositories

result, err := engine.IndexRepo(ctx, "/src/project",
    codetrip.WithRepoName("project"),
    codetrip.WithIndexMode(codetrip.IndexModeAuto),
    codetrip.WithIndexTimeout(30*time.Minute),
    codetrip.WithCSVExport("./local-review/project"),
    codetrip.WithCSVExportStrict(true),
)

repositories, err := engine.ListRepos()
metrics := engine.GetMetrics()

Search and graph queries

symbols, err := engine.Search(ctx, &codetrip.SearchRequest{
    Repo: "project", Query: "ParseConfig", Limit: 20,
})

source, err := engine.SearchSource(ctx, &codetrip.SourceSearchRequest{
    Repo: "project", Query: "lang:go ParseConfig", Limit: 20, ContextLines: 2,
})

brief, err := engine.Brief(ctx, &codetrip.BriefRequest{
    Repo: "project", Symbol: "ParseConfig",
})

nodes, err := engine.Traverse(ctx, &codetrip.TraverseRequest{
    Repo: "project", StartNodeID: nodeID,
    Direction: codetrip.TraverseAny, MaxDepth: 3,
    RelationTypes: []string{"CALLS"},
})

path, err := engine.ShortestPath(ctx, &codetrip.PathRequest{
    Repo: "project", SourceNodeID: sourceID, TargetNodeID: targetID,
})

symbolContext, err := engine.Context(ctx, &codetrip.ContextRequest{
    Repo: "project", NodeID: nodeID,
})

impact, err := engine.Impact(ctx, &codetrip.ImpactRequest{
    Repo: "project", NodeID: nodeID, MaxDepth: 3, Limit: 100,
})

checks, err := engine.Check(ctx, &codetrip.CheckRequest{
    Repo: "project",
})

changes, err := engine.Diff(ctx, &codetrip.DiffRequest{
    Repo: "project", BaseRef: "HEAD~1", TargetRef: "HEAD",
    MaxDepth: 3, Limit: 100,
})

rename, err := engine.Rename(ctx, &codetrip.RenameRequest{
    Repo: "project", NodeID: nodeID, NewName: "LoadConfig",
})

Semantic API

Implement codetrip.Embedder or use the HTTP implementation:

embedder := codetrip.NewHTTPEmbedder(endpoint, model, apiKey, 768)

embedded, err := engine.EmbedRepo(ctx, "project", embedder, &codetrip.EmbedOptions{
    QuantizeInt8: true,
})

if err := engine.AttachEmbedder("project", embedder); err != nil { /* handle */ }
hybrid, err := engine.HybridSearch(ctx, &codetrip.HybridSearchRequest{
    Repo: "project", Query: "configuration loading", Limit: 20,
})

Persisted graph export

manifest, err := engine.ExportFullCSV("project", "./exports/project")

The Go API exposes domain request/result types. Internal storage and index implementations are intentionally not public.

MCP

Configure every supported client detected on the current machine:

codetrip mcp setup --watch

Supported targets are codex, claude, cursor, vscode, and copilot. Pass one or more targets explicitly, use --dry-run to inspect the planned changes, and use --force only when an existing Codetrip entry should be replaced:

codetrip mcp setup codex cursor
codetrip mcp setup codex --watch
codetrip mcp setup --dry-run
codetrip mcp setup claude --force

If Codetrip was configured before watch support was enabled, rerun setup with --watch --force to replace that Codetrip entry; unrelated MCP servers remain untouched.

The setup command preserves unrelated MCP servers. Cursor's JSON configuration is merged atomically and backed up before modification. The other clients are configured through their official command-line interfaces.

To start the stdio server directly:

codetrip mcp --dir ~/.codetrip
codetrip mcp --dir ~/.codetrip --watch

With --watch, the MCP process recursively watches every indexed repository source root. Filesystem bursts are debounced for 750 ms by default (--watch-debounce changes it), then the watcher invokes automatic refresh through the public Engine API. The language-neutral invalidation pipeline incrementally updates supported languages and safely falls back to a full rebuild only when persisted analyzer state is incompatible. A freshness barrier makes queries wait for every already-observed change to commit; a failed refresh is returned as an explicit error instead of serving stale results. Newly indexed repositories are discovered while the server remains running. Watch diagnostics are written to stderr so they cannot corrupt the stdio protocol.

The stdio server exposes index, list, brief, search, source, context, impact, check, diff, rename, traverse, and path, matching the corresponding CLI command names. brief accepts the same repository, symbol, and budget controls as the public API. MCP lives in the CLI adapter and invokes only public Engine methods. The index tool remains useful when watch mode is disabled, for explicit recovery, or when full is requested.

The MCP process opens the engine for one tool request and releases it when the request finishes, so an idle server does not hold the database lock or block CLI indexing. MCP requests are serialized; a request made while a CLI index command owns the database may return a temporary store-busy error and can be retried.

Local language tuning

Codetrip uses one production analysis path. Maintainers can inspect the deterministic CSV produced by --export using their local fixtures, gold expectations, and review tools. Those tuning assets are intentionally not part of the public source repository and are not required by CLI, MCP, or Go library users.

codetrip index /src/project --repo project \
  --export /path/to/local-review/project --export-strict