Skip to content

| codemap doctor | Check the environment — go toolchain, gopls, the optional language servers behind --precise (TS/JS via typescript-language-server, Python via pyright-langserver), Ollama embeddings,--- description: Complete codemap CLI reference for indexing, navigation, impact analysis, search, caching, and automation. ​

CLI ​

The full codemap command reference — for people running it by hand and for scripts/CI piping --json. New here? Start with Quick Start; wiring an agent instead of a terminal? See codemap for agents and the MCP server. Every query command below accepts --json for machine-readable output.

For SQL/sqlc, YAML, Markdown, and HTML/CSS, start with Data, configuration, and documentation. Use dependencies for inbound evidence and traverse for typed relationships. These formats do not gain function calls from --precise. The same guide is available through codemap docs formats and codemap_docs with topic: "formats". MCP traverse requires the full profile.

Global options ​

These persistent options can be placed before or after a subcommand:

OptionDescription
-C, --path <dir>Run against a project directory instead of the current working directory; this is the CLI counterpart of MCP's uniform path input.
-c, --config <file>Load a specific config file instead of the normal precedence chain.
--jsonEmit machine-readable report output and structured failure envelopes where the command has a JSON contract.
--embed-provider ollamaOverride the embedding provider (currently only Ollama).
--embed-model <name> / --ollama-url <url>Override the embedding model or Ollama endpoint.
--embed-dimensions <n> / --embed-distance <cosine|dot|euclidean>Override the vector profile; changing either on an existing collection requires a reindex.

Project management ​

Register a directory, build its graph, and check on it — the commands you run before anything else.

CommandDescription
codemap init [--local]Register the current directory as a project
codemap index [--reindex] [--no-embed] [--no-lsp] [--precise] [--watch] [--via-vault <project>] [--cache=<bool>] [--no-tips]Index (incremental — re-indexes changed files and prunes deleted ones); --reindex rebuilds, --no-embed skips embeddings, --no-lsp skips the language-server backend (Go is still indexed via go/parser; TS/JS/Python/Vue SFC files are skipped — no typescript-language-server/pyright spawned), --precise resolves call edges exactly (Go via go/types, TypeScript/JavaScript/Python via callHierarchy; Vue SFCs get symbols + defines + import edges only, no call graph yet), --watch hands off to the background daemon after indexing once, --via-vault re-execs inside tvault run so language servers get private-registry creds (see secret-impact / ecosystem), --cache=false disables best-effort fcheap restore/save, and --no-tips suppresses post-index advice for scripts/CI
codemap status [--full] [--skip-stale]Show index statistics (nodes, edges, languages, kinds), plus index freshness — warns when files have changed/been added/removed since the last index (a stale field in --json), so you know to reindex before trusting queries. The default status deliberately skips opening the local vector store; use --full when the exact local vector count is needed (it can use substantial memory). --skip-stale skips the dirty-tree drift walk for cheap readiness probes (e.g. Cortex setup); default status still reports stale. JSON exposes vectors_known to distinguish a skipped count from zero. precise contains an explicit boolean for each indexed call-graph language: true only when every indexed file in that language completed precise resolution at the last index. Combine it with stale and each query's call_graph; precise_edges is diagnostic only. Also reports a running background daemon (a daemon object in --json)
codemap doctorCheck the environment — go toolchain, gopls, language servers (TS/JS, Python, Vue SFC via the same typescript-language-server), Ollama embeddings, and the background daemon — with install hints (--json)
codemap projectsList all registered projects and their index sizes
codemap docs [topic]Print the agent guide (topics: overview, formats, workflow, commands, annotations, accuracy, ecosystem; codemap docs --help lists them)
codemap structural-manifest --jsonEmit the single-response codemap.structural-manifest.v1 preflight for export-symbols: explicit export schema version, project identity, the exact export fingerprint, total records, completeness, and working-tree freshness counters plus the per-file delta (changed_files/new_files/deleted_files), so a consumer can decide what to re-ingest instead of re-reading the whole export. Also carries the additive reindex_delta attestation (from/to fingerprint + the files that run moved) when the latest index run can honestly certify one. It streams indexed metadata without reading source bodies or loading the full export.
codemap export-symbols [--offset N] [--limit N] [--max-content-bytes N] [--files <csv>] [--files-from <path>] --jsonExport deterministic, paginated structural records under codemap.structural-export.v1: a contiguous global ordinal, durable selectors, hashes, signature/doc, and bounded current content. Stale/missing/unsafe content is omitted explicitly. With --files (CSV) or --files-from (one path per line; - for stdin), the response switches to codemap.structural-export.v2: ordinals and totals scope to the requested slice, files_filter + files_filter_fingerprint echo it, and index_fingerprint still identifies the full index — the seam vecgrep uses to re-ingest only an attested delta. This is the CLI-only boundary consumed by vecgrep structural_chunks modes auto, off, and required; it never shares codemap's DB or Go packages.
codemap annotate <sym> | <from> <to>Pin a --note and/or --data (e.g. DB rows) to a symbol or call path (--source). Automation should add --external-id <id>: retries upsert one row within project + source and report action:"created|updated|unchanged"; reads return the external ID.
codemap annotate --retarget <id> <sym> | <from> <to>Repoint an existing annotation at a new target of the same kind — the repair for a note left dangling by a rename or removal. Reports matched for the new target.
codemap annotations [<sym> | <from> <to>]List annotations (all/node/path); --rm <id> to remove

Index-specific configuration overrides are also available as flags: --exclude, --exclude-extra, --max-file-bytes, --embed-batch-size, --embed-concurrency, and --embed-max-chars. See Configuration for precedence and semantics.

Configuration introspection ​

Read-only commands for checking which config file codemap resolved and what it contains — useful when precedence (flag > env > project file > global file) isn't giving the value you expect.

CommandDescription
codemap config pathShow the resolved config file path (honours CODEMAP_CONFIG, ~, and XDG defaults)
codemap config showPrint the resolved config as YAML (or --json for machine-readable)
codemap config show --jsonSame values as show, as structured JSON for agents

Follow the call graph from a symbol you already have a name for — who calls it, what it calls, where it's registered, and how it connects to another symbol.

CommandDescription
codemap callers <symbol>Functions/methods that call a symbol
codemap callers <symbol> --precisePrecise one-off callers via the language server — exact without reindexing
codemap callers --at <file>:<line>Callers of exactly one definition (same selector is available on callees)
codemap callees <symbol>Functions/methods a symbol calls
codemap callees <symbol> --precisePrecise one-off callees via the language server
codemap references <symbol>Places a function/method is used as a value rather than called — callbacks, handlers, and registrations. --at file:line selects one definition; JSON reports bounded sites plus totals, partial/unavailable coverage, stale state, and confirmed/candidate confidence. The stored edge identifies the enclosing symbol or file, not the exact expression column.
codemap path <from> <to>Shortest call path between two symbols. Unique FQNs such as app.Controller.Run and app.Store.Save select exact endpoints; human output always reports call_graph confidence and any resolution/staleness warning.
codemap symbols <file>Outline a file's symbols with their signatures (a structured alternative to reading it)
codemap symbol-at <file>:<line> [<file>:<line>...]Resolve one or more positions to their enclosing symbols (FQN, kind, range, reusable selector). Multiple positions are batched in one call; at most the first 25 are resolved and an over-limit response includes a note. The indexed field in --json distinguishes an unindexed project (indexed:false) from a real miss (indexed:true, resolution:none). callers, callees, source, context, impact, and risk also accept --at to select one exact definition.
codemap related-files <file>Files related to a file via the call/test graph — its callers', callees', and covering-test files, each with a reason (caller/callee/test) and confidence
codemap source <symbol> [--brief]Print source for matching definitions; use --at <file>:<line> for exactly one. --brief drops each match's body (keeping signature/doc/location) and sets source_omitted:true in --json — a cheaper first look at a hub definition
codemap context <symbol> [<symbol>...] [--depth N] [--brief] [--max-tokens N]One call, everything about a symbol — definition (signature + doc + source), callers, callees, value-reference wiring, covering tests + runnable test_commands, blast-radius size, and pinned annotations. Uses the indexed graph only (never launches a language server implicitly); unresolved relationships stay explicit. Replaces separate source/callers/callees/references/impact calls; the codemap_context MCP tool returns the same JSON. Pass several symbols for a batch with combined_blast_radius and common_callers (shared entrypoints/coupling) — each result carries its own test_commands. Batch source bodies share a 64 KiB budget disclosed by source_budget/source_truncations; optional component failures appear in partial_errors without discarding usable context. --brief drops every definition's source body (keeping signature/doc/location, source_omitted:true) — the token-diet follow-up for a hub symbol whose context feels heavy; everything else in the bundle is unchanged. --max-tokens N bounds the result to roughly N tokens (compact JSON bytes / 4): source bodies go first, then list tails, and the result gains a budget object (max_tokens, estimated_tokens, truncated, dropped); identity fields, selectors, call_graph, and *_total counts are never trimmed. 0 (default) means no budget. The same flag exists on impact, explore, and task-context. JSON adds hierarchy (extends, implements, subtypes, overrides, overridden_by) when the symbol takes part in declared inheritance.

The fast default uses the indexed graph (name-based resolution; same-named methods can over-match, e.g. callers Close lists callers of every Close). The best fix is to reindex once with codemap index --precise — the unified exact-resolution pass (a pure-Go go/types pass for Go, typescript-language-server callHierarchy for TypeScript/JavaScript, and pyright callHierarchy for Python). Successful coverage is recorded per file; a query is resolved only when all matched definition files completed the pass, while partial failures remain name/unresolved. (TypeScript and JavaScript get name-based candidate edges for JSX component usage, imports, Next.js framework wiring, typed Temporal proxyActivities and workflow starts, and high-precision calls: same-file calls (f(), new C(), await f(), this.m()) and calls through imported bindings (named, default, and namespace imports and require, resolved through relative paths, @//~/ aliases, and workspace packages). Arbitrary obj.method() calls are not linked (Python carries the same kind of candidates: same-file calls, self/cls methods, imported bindings), so --precise is what gives covered files a complete call graph, superseding the candidates per file.) Vue SFCs currently provide script-block symbols, defines, and import edges only; precise indexing does not add Vue call edges yet. For a one-off exact answer without reindexing, callers/callees accept --precise; it degrades to the indexed graph with a note when the language server isn't available — never a hard error. The old --lsp spelling remains a hidden compatibility alias, but new scripts and people should use --precise.

Precise indexing fixes call edges; a bare name can still match several exact definitions. Use --at <file>:<line> to keep callers/callees/references/source/context/impact/risk on one definition. --at replaces the positional symbol and cannot be combined with one. JSON/MCP consumers use the field-compatible selector:{file,start_line,fqn,kind} described in the MCP guide. The selector prefers file+FQN+kind, so ordinary line shifts survive reindex; moves/renames return a miss.

On a name-based index the analysis commands flag their limits honestly: callers/impact note when a name resolves to multiple definitions, hotspots marks name-collision inflation, and orphans follows functions wired by value (handlers like cobra RunE / mux.HandleFunc; JSX-rendered components and Next.js framework-invoked exports in TS/JS) but can't see callers reached via interface dispatch or reflection, components passed only as props (Link={AuthLink}), or wrapped default exports (export default memo(Page)) — treat its output as dead-code candidates. index --precise removes the call-edge inflation outright. See Accuracy.

Orientation ​

Learn an unfamiliar repository from the top down: the shape of the tree, what the software can do, and how one feature works. The Learn a codebase page walks through these in order, with real output. read-order and map (in Analysis) and explore (in Semantic) cover entrypoints, hubs, and intent search.

CommandDescription
codemap atlas [--prefix <dir>] [--depth N] [--files] [--max-nodes N] [--key-symbols N]The repo as a described tree. Per directory (and per file with --files): files, symbols, lines, tests, roles (source, tests, docs, config, entrypoint, examples, bench, generated, vendor), a summary with its summary_source, key symbols with durable selectors, inbound/outbound/internal coupling, and top neighbouring directories. Summaries are extracted from the project's own text (README first paragraph, Go package doc, Python module docstring, leading file comment, Markdown), never generated. --prefix zooms into a directory, --depth (default 2, max 8) sets how many levels to expand, --max-nodes (default 1500, max 20000) bounds the tree, --key-symbols (default 5, max 20) sets symbols per node. JSON is schema_version: 1 with call_graph, stale, truncated, and partial_errors. MCP counterpart codemap_atlas is full-profile only.
codemap features [--kind <csv>] [--query <text>] [--top N] [--depth N] [--no-footprint]What the software can do. Lists entry surfaces of kind program, cli_command, rpc_tool, http_route, api_route, and page. Each has a label, invocation, description (from the registration, such as a cobra Short or MCP Description, or a docstring), handler with durable selector (null for inline handlers), parent for nested CLI commands, and a bounded call footprint: symbols, files, subsystems, feature-specific tests, ambiguous_edges. Go registrations are read from the syntax tree (confidence: confirmed); TS/JS and Python are pattern-detected (candidate). --kind is a comma-separated list, --query filters by substring over label, description, handler, and file, --top defaults to 200, --depth (default 3, max 6) sets the footprint walk, and --no-footprint skips it. Ruby, Lua, and GDScript detection is not implemented; notes says so. MCP counterpart codemap_features is in the agent, core, and full profiles.
codemap processes [--kind <csv>] [--query <text>] [--top N] [--depth N] [--max-steps N]How every entry point works. Runs the flow builder from each features entry with a resolved handler and returns one process per entry: id (kind:name), kind, name, the entry selector, steps (symbol, fqn, kind, file, start_line, depth) in call order, unique files, truncated, and a per-process call_graph. Same-name fan-out is collapsed as in flow; ambiguous placeholders and cycle steps are not steps, and each definition appears once, at its first appearance in call order. A partial_errors list on a process names unreadable source files its symbols live in (step order is then name order, not call order). The report carries entrypoints_total (entry points with a resolved handler), evaluated (how many had a flow built), processes_total, and truncated; a --query can only inspect the first 300 entry points, in which case evaluated is below entrypoints_total and truncated is true (narrow with --kind). Computed on demand, nothing is stored. --top defaults to 50 (max 200), --depth to 4 (max 8), --max-steps to 40 (max 200). --query keeps processes whose name or steps match the query's content words (the keyword search floor's tokenization), best match first. MCP counterpart codemap_processes is in the full profile only.
codemap flow <symbol> [--depth N] [--max-nodes N] [--include-tests]How one feature works. A call tree from one entry (a handler, a cobra RunE, any function) in the order the code calls things, each step with file:line, subsystem, signature, one-line doc, and confirmed/candidate confidence. On a name-based graph, same-name fan-out is collapsed to the most plausible definition (alternatives) or left as an unexpanded ambiguous step with candidates; precise edges are never collapsed. Repeats, cycles, and depth or node cuts are explicit (leaf_reason). Select the entry with a name or FQN, or with --at <file>:<line>. --depth defaults to 4 (max 8), --max-nodes to 120 (max 1000); tests are skipped unless --include-tests. MCP counterpart codemap_flow takes symbol or selector and is in the agent, core, and full profiles.
codemap task-context <task> [--mode understand|change|debug] [--at <file>:<line>] [--max-tokens N]One-call, mode-scoped orientation for a concrete task (alias brief): freshness, explore neighbourhoods, and for change/debug contexts, impact drill-downs, and related files. The task text is used verbatim as the retrieval query. Default mode is understand; --at is repeatable and requires change or debug. --max-tokens N trims the least important material first and adds a budget object (see codemap context). MCP counterpart codemap_task_context is full-profile only.
text
$ codemap atlas --prefix internal --depth 1
internal                             3,569 sym   254 files [source]
├─ app/                              1,309 sym   100 files [source]  Package app is codemap's shared service layer. The…
├─ extract/                            618 sym    40 files [source]  Package extract turns source files into structural…
├─ graph/                              319 sym    22 files [source]  Package graph is codemap's structural code graph: …

$ codemap features --kind cli_command --query review
CLI (1):
  review          Diff-scoped impact + test selection: what your changes affe…  cmd/codemap/query.go:690
                    61 sym · 21 files · 6 subsystems · 34 tests

$ codemap flow runReview --depth 1
runReview                               cmd/codemap/query.go:690 — runReview renders diff-scoped intelligence…
├─ 1 parseFailOnRiskFlag                cmd/codemap/gate.go:28 — parseFailOnRiskFlag validates --fail-on-risk's value.  (+1 deeper)
├─ 2 openSession                        cmd/codemap/main.go:297  (+2 deeper)
├─ 3 app.Session.Close                  internal/app/session.go:316 — Close closes any stores that were opened.  (+8 alt) (+1 deeper)
…

Analysis ​

The commands built around a change: how far it reaches, what tests cover it, how risky it is, and — for review — what your current diff already touched.

CommandDescription
codemap impact <symbol> [--depth N] [--min-confidence confirmed|candidate] [--max-tokens N]Definition sites, direct callers, blast radius, covering tests, and copy/paste-ready test_commands. JSON adds buckets (the blast radius grouped into direct depth-1 and transitive depth-2+ nodes; the counts are always the true totals), blast_radius_total (the true blast-radius size, unchanged by trimming), and a per-node confidence; --min-confidence confirmed drops name-based candidates — see Confidence-filtered impact. --at file:line selects one definition; repeat --at to analyze up to 25 positions in one ordered, partial-success batch. A missed frame carries item-level error.code:"symbol_not_found". Add --batch to force the stable batch envelope for one position. --max-tokens N bounds the result (the buckets node lists go first, then the blast radius; buckets only ever list nodes still present in blast_radius, and budget.dropped counts them) and adds a budget object (see codemap context).
codemap dependencies <file>Direct inbound call/reference/import evidence grouped by dependent file and edge kind. Every relationship is classified as confirmed or candidate with a reason (precise, same_package, resolved_import, name_fanout, package_scope, or stale_snapshot); totals and bounded source→target samples preserve that confidence. Coverage remains explicit for calls, references, imports, runtime wiring, and external consumers. Missing evidence never means safe.
codemap file-impact <file> [--depth N]File-level impact — "what happens if I change or delete this file?" Returns grouped dependency evidence, coverage, blast radius, tests, and delete_verdict. Only fresh, confirmed, file-scoped indexed evidence can prove unsafe; name-fanout candidates, stale evidence, and Go's package-scoped imports remain unknown for the exact file. Missing evidence never proves safety; legacy safe_to_delete stays false.
codemap review [--since <ref>] [--staged] [--depth N] [--fail-on-risk <low|medium|high>] [--fail-on-untested] [--fail-on-uncovered]Diff-scoped impact + test selection — the command to run after editing. Maps your git diff (whole working tree by default; --staged for the index; --since <ref> for everything since a branch point) to the symbols it touches, then reports their union blast radius, the tests to run (regression test selection), and the changed symbols that are untested or are hotspots (many callers). Deleted files are analyzed from definitions retained in the last index; run the selected tests before reindexing removes that evidence. Carries aggregate risk, a separate test-coverage coverage verdict, stale/resolution, and stable call_graph honesty signals. --fail-on-risk/--fail-on-untested/--fail-on-uncovered gate on that data — see Gating a commit or script.
codemap affected [files...] [--stdin] [--staged] [--since <ref>] [--filter <glob>] [--depth N]Changed files → the test files to run, without parsing a review report. Selects a test file when it covers a changed symbol through the call graph (covers:<symbol>), imports a changed file directly or transitively up to --depth hops (imports:<file>), or is itself a changed test file (changed). Files come from arguments, --stdin (newline-separated, e.g. git diff --name-only), or git (--staged, --since <ref>); with none of those it uses the working tree. Paths are project-relative (absolute paths under the root are accepted). Human output is exactly one test path per line on stdout — pipe it to a runner (codemap affected --stdin | xargs go test) — with notes on stderr; --json adds reasons, unmapped, deleted_tests, call_graph and analysis_complete. --filter is a glob over the reported test paths. Deleted test files are never listed. See affected.
codemap secret-impact [<KEY>...] [--via-vault <project>]Rotation blast radius for secret keys: which symbols read each key (os.Getenv/process.env/os.environ), the transitive callers affected, and covering tests (untested:true warns you're rotating a key no test reaches). Operates on key names only — never reads or returns values. --via-vault fetches the names from tinyvault. Each request accepts at most 256 unique names, 256 bytes per name.
codemap required-keys <entrypoint> [--via-vault <project>]Least-privilege key set: which candidate keys an entrypoint's transitive call tree actually reads — pipe to tvault seal/export to grant only what a code path needs. One key per line. Candidate input is capped at 256 unique names, 256 bytes per name.
codemap risk <symbol> [--depth N] [--fail-on-risk <low|medium|high>]Change-risk score — "how careful should I be changing this?" in one number (0..1) + level (unknown/low/medium/high). Combines untested coverage, fan-in (direct callers), cross-package spread, and name ambiguity into a saturating score, with the factors behind it. If the call graph is unavailable, the level is unknown rather than a misleading low. Use --at file:line for one definition. --fail-on-risk gates on the level — see Gating a commit or script.
codemap hotspots [--top N] [--include-tests]Most-referenced symbols (hubs), ranked by effective_in_degree (precise callers plus name-based callers divided by the number of same-named definitions). Test code is ignored by default: calls from tests do not count and test-defined symbols are not ranked; --include-tests counts them. Each entry carries query_frequency — how many past searches surfaced it — so equal-confidence hubs can be tie-broken by how often they are actually queried
codemap orphans [--top N]Functions/methods with no callers (dead-code candidates)
codemap coverage [--prefix P] [--lang L] [--uncovered] [--files] [--top N]Per-file precise call-graph coverage: rollups by language and by directory (worst-covered first), plus a bounded per-file list (--files, or any filter, includes it; capped at --top, default 200) showing each file's resolver, resolved_at, and whether it's gone stale since the last index. Complements, does not replace, the per-query call_graph enum.
codemap read-order [query] [--top N] [--include-tests]Where to start reading — ranks entrypoints and load-bearing hubs (effective_in_degree) into a newcomer's reading guide, each with the reason it ranked. Tests are ignored by default (--include-tests counts them). The cmd/main boost applies only to main() and to functions wired by value (for example a cobra RunE that nothing calls directly); methods never get it, and a main() under bench, examples, scripts, tools, or hack ranks as an auxiliary program entrypoint. Optional query narrows by name/path. The agent-facing answer to "I just landed in this repo — what do I read first?"
codemap map [--top-subsystems N] [--top-bridges N] [--top-hubs N] [--top-entrypoints N]Architecture overview — deterministic source-path subsystems, directed cross-subsystem bridges with relationship provenance, likely entrypoints, and hubs. Test code is excluded from bridges, subsystem edge counts, and hubs (tests_excluded: true). JSON includes schema_version, totals/truncation, call_graph, resolution, stale, and partial_errors.
codemap traverse --at <file>:<line> [--direction outgoing|incoming|both] [--edge-types calls,references,...] [--depth N] [--limit N]Exact heterogeneous walk — starts from the one indexed definition enclosing --at (no ambiguous positional name), resolves it to the durable {file,start_line,fqn,kind} identity, then walks selected relationship domains cycle-safely. --edge-types is CSV from calls, references, imports, implements, overrides, depends_on, tests, and defines; depth is 1–10 (default 2), node limit is 1–500 (default 100). JSON v1 includes every hop's parent selector, direction, edge type/provenance, and confirmed/candidate confidence. MCP counterpart codemap_traverse is full-profile only and requires the typed durable selector.
codemap inconsistencies --jsonWhere the compiled knowledge contradicts itself: dangling annotations whose target no longer exists (repair: annotate --retarget or --rm), precise-resolved files still emitting name-based call edges (repair: re-run --precise), and coverage recorded for files with no indexed nodes (repair: reindex). Reports stale when the working tree has drifted, since that makes every claim provisional. Emits codemap.inconsistencies.v1; an empty report is evidence of internal coherence, not correctness. CLI-only by contract.

Semantic ​

Three ways to search when you don't already have an exact symbol name: by meaning, by name fragment, or by literal text.

CommandDescription
codemap semantic <query> [--top N] [--backend fallback|local|vecgrep] [--fusion auto|balanced]Meaning-based search across the indexed graph (alias: codemap search); the backend flag explicitly selects the semantic owner
codemap explore <query> [--seeds N] [--edges N] [--depth N] [--max-tokens N]Intent to structure — finds semantic/name seeds, joins each usable hit to an exact durable selector, then returns bounded caller/callee/reference/test neighborhoods without source bodies. Seeds are 1–10 (default 5), edges per neighborhood are 1–20 (default 5), and depth is 1–10 (default 2). --max-tokens N trims context lists, then processes, then the lowest-ranked contexts and seeds (a process never names a dropped seed in matched_seeds) and adds a budget object (see codemap context). MCP counterpart codemap_explore is registered in every profile. The report also carries processes (up to 3): entry-point flows (route or command, handler, service chain) whose steps contain a joined seed, each with matched_seeds and the call-order path to them capped at 8 steps; empty when the project has no detected entry points or no flow reaches a seed. task-context embeds it with the rest of the explore report.
codemap find <query> [--top N]Find symbols by name, with signatures (offline; no embeddings needed)
codemap grep <pattern> [--regex] [-i] [--top N]Exact text search over indexed file content, each hit resolved to its enclosing symbol (offline, no embeddings)

The default backend is fallback: codemap reads its local vectors when present, then asks vecgrep only for a structure-only project. Use --backend local to forbid that adapter, or --backend vecgrep to make vecgrep the sole semantic owner. Explicit vecgrep mode treats a missing binary, execution failure, or bad JSON as an error and preserves a genuine zero-hit answer; it never silently switches back to local vectors. Indexing with that backend keeps the graph but skips/removes codemap's unused local vectors.

On a structure-only project where neither permitted owner has embeddings, codemap semantic returns no hits with a short note and JSON "mode": "none". It never invokes the embedder or creates an empty vector store on that query path; codemap find remains the offline name-search floor.

codemap find in degraded (no-Ollama) mode: it's the offline search floor, not a semantic replacement — it tokenizes the query on whitespace and camelCase boundaries (query side only) and matches each token against symbol/FQN or docstring, so a multi-word query like parse selector finds ParseSelector and parse_selector alike, and a docstring-only mention still surfaces (ranked below a name match). Each hit carries matched_in ("symbol", "fqn", or "docstring") so you can see why it matched. It's still substring/keyword matching, not meaning search: it won't find a conceptually related symbol that shares no words with the query — for that, embed the index (codemap index, with Ollama running) and use codemap semantic.

codemap explore / codemap task-context without embeddings: their search requires no vectors. When name search finds nothing (a question like how does signup work has no symbol containing every word) or fewer hits than requested, a lexical floor fills the rest: it drops question words and stopwords, then ranks definitions by BM25 over symbol names, FQNs, file paths, docstrings, and signatures, preferring definitions that match more of the remaining words. Matching is case-insensitive substring (trigram), so signup reaches signupUser and app/api/auth/signup/route.ts. The JSON search_mode is lexical when only that floor answered and name+lexical when exact name matches lead; matched_in may then also be "path" or "signature".

codemap grep searches only the indexed file set — the files codemap extracted structure from (same excludes as codemap index) — not every byte in the repo; a config/YAML/README file with no registered extractor is invisible to it, exactly as it already is to codemap find/codemap symbols. Reads happen live from disk at query time, so a file edited since the last index is searched at its current content; a file added since the last index is not yet in that set (the stale field on the report discloses this — it describes file-set completeness, not staleness of a matched line). Matching is a literal substring by default; pass --regex for Go RE2 syntax and -i/--ignore-case for case-insensitive matching in either mode. This is deliberately not a ripgrep reimplementation: no context lines, no glob/language filters — use codemap semantic for meaning search and codemap find for name search instead.

codemap semantic adaptively balances the vector/BM25 hybrid-search fusion by the shape of your query: an identifier-looking query (ParseSelector, graph.Store.NodeAtLine) leans toward the exact-name/BM25 channel, while a natural-language question (where do we retry on rate limit) leans toward the vector channel — both channels always contribute, just unevenly. The chosen profile is surfaced as fusion ("identifier", "natural_language", or "balanced") in --json output and printed as a fusion: … line above the hit list otherwise. Pass --fusion balanced (or set semantic.fusion: balanced in config) for the exact pre-adaptive equal-weighted behavior.

Surfaces ​

The three ways to run codemap beyond one-off CLI queries: as an MCP server, or just check what's installed.

CommandDescription
codemap serveRun the MCP server over stdio. --profile agent|core|full selects the tool profile: agent is exactly 27 taught workflow tools plus codemap_docs (28 total), core preserves the compatible 28-tool surface, and default full exposes all 50. Same file < env (CODEMAP_MCP_PROFILE) < flag precedence as every other setting.
codemap versionPrint version information

Agent harness setup ​

One command wires codemap into an AI coding harness — no hand-editing MCP config files. See codemap for agents for the harness table and the Claude Code plugin.

CommandDescription
codemap agent listList known harnesses (Claude Code, Cursor, Codex, Gemini, Cline/Roo, Zed, VS Code, OpenCode, aider, and the agents-md fallback), whether each is detected here, and if codemap is already registered (--json)
codemap agent setup <harness>Merge the codemap MCP server into the harness's native config and drop the canonical playbook into its guidance file (.cursor/rules/*.mdc, AGENTS.md, GEMINI.md, …). Never clobbers other servers or your prose. The agents-md fallback is deliberately playbook-only: it updates the marked block in AGENTS.md for any AGENTS.md-reading harness without registering MCP. Flags: --global (user-level config where the harness has one), --dry-run (print planned writes, change nothing), --no-playbook (MCP registration only)
codemap agent playbook [--format markdown|markdown-cli|claude-skill|cursor-rule]Print the canonical "when to use codemap" playbook, for wiring an unlisted harness by hand

Branches & caching ​

The index is a snapshot of one working tree. Two features keep it aligned with your git branch and make reindexing cheap when you return to a tree you've indexed before — both best-effort over the sibling fcheap stash vault, and both degrade to a normal index when fcheap isn't on $PATH. See Branches & caching for the concepts.

CommandDescription
codemap branch-status [path]Read-only git state (repo hash, branch, HEAD sha) used to key per-branch index snapshots
codemap branch-switch [--to <branch>] [--from <branch>] [--root <dir>]Switch the code index to a git branch: snapshot the old branch into fcheap, restore/reindex the new one. --to defaults to the current git branch; a non-git dir or detached HEAD is a no-op
codemap branch-switch --install-hookInstall a git post-checkout hook that auto-switches the index on every git checkout (idempotent, preserves an existing hook; pins the running binary so it works off-PATH)
codemap branch-snapshot [--branch <branch>] [--root <dir>]Stash the current branch's index into fcheap without switching (defaults to the current git branch)
codemap cache saveStash the current index into the fcheap cache, keyed by a tree hash of all indexed (path, content_hash) pairs — two identical working trees share one entry
codemap cache restoreRestore the cached index matching the current working tree (skips extraction + embedding entirely); a miss is a no-op
codemap cache list [--rebuild]List cached indexes for this repo (stash IDs, tree hashes, node/vector counts, age). --rebuild reconstructs from fcheap if the local pointer file is lost
codemap cache drop --tree <hash> | --allDrop one cached index by tree hash, or every cached index for this repo
codemap cache export <file.tar.gz>Package the current index into a self-contained, portable tarball — no fcheap/shared store needed, so a CI job can hand it to the next runner
codemap cache import <file.tar.gz> [--force]Restore a tarball from cache export (registers the project first if unindexed). Refuses a schema/embedding-profile mismatch outright; refuses a working-tree hash mismatch unless --force
codemap vectors-gc [--dry-run]Prune orphan local vector records no graph node claims (deleted/replaced nodes, projects migrated to vecgrep). Explicit maintenance: opening the shared store loads every project's records. --dry-run only reports

codemap index wraps cache for you behind --cache (on by default): it auto-restores from a matching cache entry before a --reindex (skipping the full wipe+extract+embed cycle), and auto-saves the freshly-built index to fcheap after a successful index. With --precise, a restore only lands when the cache entry already has precise edges — otherwise it falls through to a real reindex so the go/types pass actually runs. Pass --cache=false to disable both for a run.

Background daemon ​

The daemon watches the working tree and keeps the index fresh automatically — incrementally re-indexing on save and throttling embeddings so it never hammers Ollama. Tune it via the daemon: config block / CODEMAP_DAEMON_* env / the flags below (see Configuration).

CommandDescription
codemap daemon start [path]Run the daemon in the foreground (watches the project; background it with &, stop with Ctrl-C). Flags: --precise (rerun exact Go/LSP resolution after watched edits), --no-embed (structure only, no Ollama), --debounce, --idle-timeout, --embed-rps, --embed-max-in-flight, --embed-cache-size
codemap daemon statusShow whether a daemon is running and what it's watching
codemap daemon stopStop the running daemon

When a daemon is running, codemap status and the codemap_status MCP tool report it (a daemon object in --json), codemap doctor lists it as a health check.

While a daemon is running, codemap index delegates the reindex to it over the control socket instead of opening a second write handle (which would collide with the daemon's exclusive database lock). The output is the normal Indexed ... summary, annotated with via daemon (pid N), and forwards --reindex / --precise / --no-lsp / --no-embed. --watch is a no-op in this case (the daemon is already watching); --exclude-extra is not forwarded (stop + restart the daemon to change excludes).

Exactness is persistent daemon state, not a one-shot label. Start with --precise (or daemon.precise: true / CODEMAP_DAEMON_PRECISE=true) to run the exact Go go/types and LSP callHierarchy pass on the initial index and every changed batch. If a package stops type-checking or an LSP request fails, the affected files lose precise coverage instead of retaining ghost confidence.

Example ​

Given a small store package:

go
// store.go
package store

func openDB() error       { return nil }
func Save(x int) error    { return openDB() }
func Delete(id int) error { return openDB() }

// store_test.go
func TestSave(t *testing.T) { _ = Save(1) }

impact answers what breaks if I change this, and what do I run to check? — here, openDB is reached by Save and Delete, and TestSave (✓) transitively covers it:

bash
$ codemap impact openDB --depth 2
Impact of openDB (store)
  defined:        store.go:3
  direct callers: 2
  blast radius:   3 (depth ≤ 2)
  tests covering: 1
  covering tests (run these):
     store.TestSave                       store_test.go:5
  affected (blast radius):
     [1] store.Save                           store.go:4
     [1] store.Delete                         store.go:5
   ✓ [2] store.TestSave                       store_test.go:5

For symbols with many dependents the human-facing lists are capped — the nearest blast-radius nodes and the first covering tests, with a … (N more) line. --json always carries the complete set. (The README shows the same command run on codemap itself.)

Confidence-filtered impact ​

On a name-based index a hub name like Update fans out to every same-named method, so the flat blast_radius can be mostly noise. --json therefore adds, without touching the flat list:

  • buckets — {direct, transitive, direct_count, transitive_count}: the same blast_radius nodes split at depth 1 vs depth 2+, so the direct callers can be read first. The counts are always the true totals; when --max-tokens (or task-context's 25-item cap) trims blast_radius, the direct/transitive lists are rebuilt from the kept prefix only, and blast_radius_total reports the true size.
  • confidence on every blast-radius and test node — confirmed when a shortest path from the symbol to that node uses only precise edges (an index --precise pass) or same-file name edges whose target symbol is unique in its file, otherwise candidate (cross-file name-based fan-out, same-file fan-out over several same-named methods; heuristic covering tests are always candidates).
  • --min-confidence confirmed (MCP min_confidence) — drops candidate nodes from blast_radius, buckets, tests, direct_callers, and test_commands, and reports how many distinct candidate nodes it removed as filtered: {"candidate": N} (with min_confidence echoed). candidate, or leaving it unset, is the default and changes nothing. untested keeps its call-graph meaning — it is computed before filtering.

review — the post-edit query ​

Where impact starts from a symbol, review starts from your diff. After editing Save, you don't have to name the symbol — review reads the working tree, finds the changed symbols itself, and unions their impact:

bash
$ codemap review
Review (store · working)
  changed files:   1
  changed symbols: 1
  blast radius:    2 (depth ≤ 3)
  covering tests:  1
  changed symbols:
     store.Save                           store.go:4
  tests to run:
     store.TestSave                       store_test.go:5

--since main reviews everything you changed on the branch (committed + uncommitted); --staged reviews just what's staged. JSON/MCP output also includes copy/paste-ready test_commands grouped by package and at most two conditional next actions, so an agent can execute the selected regressions without deriving runner syntax. The codemap_review MCP tool returns the same JSON. Every successful review document emits schema_version: 1; the authoritative Draft 2020-12 contract is schemas/codemap.review.v1.schema.json. Canonical keys are snake_case: {schema_version, changed_symbols, analysis_complete, total_symbols, analyzed_symbols, truncated_symbols, partial_errors, blast_radius, covering_tests, test_commands, untested_symbols, hotspots, stale, resolution, call_graph, risk, coverage, next}. Version 1 permits additive optional properties but does not rename or repurpose existing fields. The command degrades gracefully (a plain changed-file list with a note) when the project isn't indexed or isn't a git repo; hard-failure error envelopes are separate from the success schema.

analysis_complete is false when the index is stale, a supporting stage fails, an individual symbol cannot be analyzed, deleted definitions are unavailable, or the 200-symbol work cap omits part of the diff. Pure-deletion hunks are classified before they can make a review incomplete: a deleted block that fell inside a surviving symbol's span maps to that symbol (it is analyzed), deleted lines that belong to no symbol at all (blank lines, comments, imports — in the gaps between definitions or at the top/end of the file) are informational, and only a removed declaration or an unclassifiable file is an error. Fresh indexed untracked source files and exact source-file renames are mapped as whole files because they have no post-image hunks; an empty renamed source file remains partial. Documentation, assets, and configuration files stay visible in changed_files but do not create structural mapping errors. Compare total_symbols, analyzed_symbols, and truncated_symbols; bounded partial_errors entries carry stable stage/code fields plus an actionable message. An incomplete review's aggregate risk.level is always unknown, even when the successfully analyzed subset produced a numeric score. Mapping-stage codes distinguish a failed symbol lookup (symbol_mapping_failed), a structural-source pure-deletion hunk whose file has no indexed symbols to classify it against (deletion_only_hunk when the file has no mapped hunks, deletion_hunk_unmapped otherwise), a recognized callable or type declaration line removed from structural source by any hunk shape (removed_definition_unavailable), and an exact structural-source rename whose new path has no indexed symbols (rename_unmapped). These signals prevent a successfully mapped post-image subset from hiding old definitions that review could not analyze.

call_graph (stable machine enum) on impact/callers/callees/references/review/context/ hotspots/orphans/path/map/traverse tells a consumer how much to trust the call graph without parsing prose: resolved (every matched definition file has precise coverage), name (Go/Ruby/Lua name-based — same-named symbols may over-match), unresolved (TS/JS/Python without successful precise coverage, or Vue whose call graph is not supported yet — callers/blast/tests are incomplete, not absent; TS/JS may still return name-based candidates for JSX, same-file calls, and imported bindings), none (no matching symbol). The free-form resolution sentence stays for humans.

risk on review is one band for the whole diff — level (unknown/low/medium/high), score (0..1), and factors (untested_changes/hotspot_fanin/cross_package/ ambiguity/unresolved) folded from every changed symbol — so a harness can gate verification on one call instead of fanning risk out per symbol. It is absent for a complete zero-symbol diff and early no-repository/no-index degradation; a finalized incomplete indexed review emits unknown even when no symbol could be mapped safely. unknown also covers a changed symbol whose call graph is unavailable.

coverage on review is the test-coverage verdict, kept apart from the structural risk band: {verdict, covered_symbols, uncovered_symbols, unknown_symbols} with verdict one of covered, partial, uncovered, or unknown. Per changed symbol, covered means a call-graph path, a heuristic name match, or a test file in the same diff reaches it (a changed or new test file whose code, comments and string literals excluded, references the symbol by name counts even before reindexing; for Go it must live in the symbol's directory, and a name shared by several definitions is never linked this way). A same-diff link counts toward this verdict only: it never removes a symbol from untested_symbols and never changes risk or --fail-on-untested; uncovered means the call graph is usable (resolved/name) and no test was found; unknown means no test link was found and the call graph cannot say (TS/JS/Python without --precise, declarative formats), or the symbol was never analyzed (truncated or failed). Test symbols are the coverage, not its subject, so they are skipped. The block is absent when the diff maps no non-test symbol. unknown is never evidence of missing tests.

affected — changed files → tests to run ​

When all a hook or CI job wants is "which test files should I run?", affected skips the review report. Feed it paths and it prints test files, one per line:

$ git diff --name-only main | codemap affected --stdin
internal/app/review_test.go
cmd/codemap/gate_test.go
$ codemap affected --staged --filter '*_test.go' | xargs go test

A test file is selected for one of three reasons, all visible under --json:

  • covers:<symbol> — it holds a test that reaches a changed symbol through the call graph (within --depth, default 3), including codemap's heuristic text-reference scan for languages without a call graph.
  • imports:<file> — it imports a changed file, directly or through up to --depth hops of non-test files. Go imports are package-scoped and cannot prove one exact file is needed, so Go coverage comes from call edges only.
  • changed — the changed file is itself a test file.

--json returns schema_version: 1 with files (normalized input), tests (sorted unique paths, each with reasons), unmapped (changed files with no indexed symbols — docs, config, unindexed or out-of-project paths), call_graph (the weakest confidence among contributing symbols: resolved/name/unresolved/none), analysis_complete, stale, and a note whenever coverage is name-based, unresolved (TS/JS/Python without --precise) or absent (YAML, SQL, Markdown: call_graph: none), so an empty list is never silent. analysis_complete is about staleness, caps and failures, not coverage: it is false on a stale index, a capped or failed analysis, or an unmapped source file (an unmapped README does not count), and stays true when the call graph simply cannot say, which is what the note is for. A changed test file that no longer exists (deleted in git, or gone from disk) is never in tests; it is listed in deleted_tests instead. Changed files come from arguments, --stdin, --staged, or --since <ref> (an explicit list is unioned with the git diff; an empty --stdin list means nothing changed, not the working tree). A relative path is resolved under the project root, then the current directory, then the git toplevel, so git diff --name-only output (repository-root-relative) works when the project is a subdirectory of the repository; a path outside the project is unmapped. The codemap_affected MCP tool (full profile) returns the same JSON.

Exit codes follow the usual taxonomy: a project that was never indexed is a not_indexed failure; running a git-sourced mode (the default working tree, --staged, --since) outside a git repository is not_a_repo (exit 5 under --json); a --depth outside 1-10, --staged together with --since, or a --since ref that does not exist is invalid_input (exit 1).

Gating a commit or script ​

codemap review and codemap risk compute a risk level and an untested-symbols list either way, but historically always exited 0 — a caller wanting to block on "this diff touches untested high-risk code" had to hand-roll the check against --json output (exactly what the GitHub Action did before it grew fail-on-untested/fail-on-risk inputs). Three flags turn that into a first-class exit code instead:

  • --fail-on-risk <low|medium|high> — after printing the normal output (unchanged), exit 6 if the risk level's ordinal is at or above the threshold (low ≤ medium ≤ high). On a complete report, level:"unknown" does not trip this risk comparison: an unresolved call graph is not evidence of risk, so a repo indexed without --precise cannot spuriously fail a risk threshold. Available on both review (gates the aggregate diff-wide risk band) and risk (gates one symbol).
  • --fail-on-untested — after printing the normal output (unchanged), exit 6 if untested_symbols is non-empty, or if mapped symbols have an unresolved/none call graph and test coverage therefore cannot be established. An empty list is not proof of coverage when relationships are unknown. review only (there is no untested-symbols list on risk, which reports one symbol at a time).
  • --fail-on-uncovered — after printing the normal output (unchanged), exit 6 only when coverage.verdict is uncovered, or partial with at least one known-uncovered symbol. It never trips on unknown coverage (an unresolved call graph with no test link) or on a partial made only of covered and unknown symbols — the honesty rule — so unlike --fail-on-untested it is usable on polyglot diffs. Like the other review gates it fails closed (exit 6) on an indexed Git review with analysis_complete:false — truncated at the 200-symbol cap, partial errors, or a stale index — since a subset proves nothing about the whole diff; genuine unknown coverage of a complete analysis still passes. --fail-on-untested itself is unchanged. review only; the report's gate.would_fail_on.uncovered reproduces the coverage condition from the JSON (combine it with gate.would_fail_on.incomplete_analysis).

For review, enabling any gate also requires a complete analysis. An indexed Git repository with analysis_complete:false exits 6 before policy comparison, even though its aggregate risk is honestly unknown; otherwise a stale or partially mapped diff could pass because the evidence needed to enforce the gate is missing. With all gate flags disabled, the same incomplete report remains reporting-only and exits 0. Early graceful reports for a non-Git directory or a project with no indexed nodes (including codemap init without codemap index) also remain nonblocking and exit 0.

The gate is exit-code-only: under --json the body printed is the exact same success envelope you'd get without the flag (ok/error/code never appear — that shape is reserved for real failures, see below). A tripped gate is not a query failure; nothing was left unanswered. This means a script can run the same command it already runs for output and just also check $?.

A ready-made pre-commit hook packages the common case — see .pre-commit-hooks.yaml and the pre-commit section of the CI guide for the trade-offs (name-based resolution for speed; a non-Git or never-indexed project degrades to exit 0, while an existing but stale/partial index fails closed until refreshed).

Machine-readable errors + exit codes ​

Under --json, a failure prints a structured envelope to stdout (not stderr) so an agent parsing JSON still gets it:

json
{"ok": false, "error": "…", "code": "not_found|not_indexed|index_missing|index_corrupt|not_a_repo|operational", "hint": "run: codemap index"}

The non-zero exit codes follow a documented taxonomy:

exitmeaning
0answered (results, possibly empty-but-resolved like "no callers")
1operational error (bad flag, git failure, untyped runtime error)
2not_found / not_indexed — a valid query with no answer
3index_missing — no index for the project
4index_corrupt — the graph DB exists but won't open
5not_a_repo — a git operation was required but cwd isn't a repo
6gate_failed — a --fail-on-risk/--fail-on-untested threshold tripped on review/risk. Not a query failure: there is no --json failure envelope for it (see Gating a commit or script)

So a consumer can map code→action deterministically either way (the JSON code matches the exit-code suffix) for exit codes 0-5; exit 6 is exit-code-only by design.

Durable impact batches ​

For hits returned by Vecgrep's structural chunks, pass each selector unchanged:

sh
codemap impact --selector '{"file":"main.go","start_line":12,"fqn":"main.Run","kind":"function"}' --json

Repeat --selector for up to 25 definitions. It always returns the ordered batch shape, including for one selector. It cannot be combined with positional names or --at. Each JSON selector is bounded to 16 KiB and rejects unknown fields. File, FQN and kind retain identity across ordinary line shifts after reindexing.

Impact batches (--selector, repeated --at, or --at --batch) include freshness.checked and freshness.stale. A false checked is unknown freshness, not a fresh index. This is a working-tree observation, not a transaction spanning concurrent edits. Check each item's found and call_graph independently.

This docs site uses cookie-free Vercel Web Analytics. codemap sends no usage telemetry.