This reference documents every command available in the gograph CLI, compiled directly from the production source code.
Global Flags
Global flags may appear before or after the command:
--json: Structured output for query/composed-analysis commands and workspace build, status, query, path, and impact.--files-only: Deduplicated paths for the commands listed under Output Modes; an empty result writes zero lines.--mermaid: Mermaid output forcallers,callees,impact,endpoint,dependents,deps,path, andcoupling. Baregograph --mermaidis shorthand forgograph diagram.-i <message>/--intention <message>: Technical rationale recorded with CLI command telemetry. It is mandatory for analytical commands while an the caller selects an active audit session; session, MCP startup, build, installation, help, version, doctor, stale, stats, capabilities, wiki, and doc commands do not require it.--rev <ref>: Answer a graph query from the tree of a Git commit, branch or tag instead of the working tree (gograph --rev 3b37747 source internal/app/client.go,gograph callers Run --rev origin/main). The first query for a commit extracts the project withgit archiveinto.gograph/revs/<commit>/(a standalone repository, so the scanner applies only the commit’s own ignore rules) and builds an AST graph there; later queries reuse it. The graph uses the working graph’s recorded build tags and exclusions unless--tagsorGOFLAGS -tagsselect others, which rebuilds it. Not accepted bybuild,mcp,staleorworkspace, or with--uncommitted/--since. CLI only. Delete.gograph/revsto reclaim space.--no-refresh: Answer from the persisted graph even when it is stale (with the stale warning). Without it, a CLI graph query rebuilds a stale graph first: changed packages only, with the recorded precision, build tags and excluded directories, noted on stderr (or inwarningunder--json).GOGRAPH_NO_REFRESH=1does the same for every call. A different build context, another caller’s active session and--revnever rebuild, nor dostale,stats,changesand the enforcement commandsgate,checkandboundaries(gatestill fails on a stale graph).--session-id ID/GOGRAPH_SESSION=ID: Select the caller’s session returned bysession create. The flag overrides the environment. Omission keeps a read-only caller outside other agents’ audits; writes still refuse when another caller owns an active session. Independent callers may create concurrently.
CLI commands answer from the persisted graph. When selected files or the Go
build context changed since the last build, graph-backed commands print a
WARNING on stderr naming the changed files and asking for gograph build .;
JSON output carries the same text in warning and reports
graph_state.freshness: "stale". stale, stats and changes report
freshness themselves and add no warning.
Request only one of --json, --files-only, or --mermaid; unsupported or
conflicting output flags fail instead of being silently ignored.
Bounded result lists
query, focus, node, callers, callees, implementers, mocks,
fields, envs, interfaces, concurrency, dependents, public, embeds,
imports, impact, errors, httpcalls, mutate, constructors, usages,
returnusage, literals, schema, globals, fixtures, orphans, and
boundaries accept --limit N and --cursor TOKEN. Their corresponding MCP
tools accept limit and cursor with the same semantics.
Default is 100 rows, maximum 200, with a 16 KiB native-page budget. MCP sends
the page once, as compact JSON text.
CLI JSON exposes total, returned, truncated, next_cursor, limit, and
offset; MCP uses gograph.results.v1. Follow cursors until truncated=false.
Graph content or result-selection changes invalidate the cursor, but page size
may change. Individual oversized rows are refused, not silently shortened.
--files-only remains a complete file census. Do not combine row pagination
with it or --mermaid. Specialized schemas such as routes and SQL retain
their separately documented limits.
Indexing & Core Commands
build
--exclude-dirs=dir1,dir2 (also space-separated or repeated) omits literal
repository-relative directory subtrees from both AST and precise targets,
including tests. No globs, absolute paths, parent traversal, or root exclusion.
The selection is recorded in build.selection.exclude_dirs and fingerprinted;
rebuild without the flag to restore full selection. Included imports still must
type-check, and source safety / Go metadata validation remains enforced.
Since v1.7.2, --exclude-dirs=.claude/skills also masks directory symlinks
beneath that real directory during precise production/test loading. Targets
are not traversed and cannot provide imported Go code. Linked Go inputs and
metadata remain errors; an existing user Go overlay cannot be combined with
this masking. Pass the same exclusion to MCP startup and restart the server.
gograph build [path] [--precise] [--strict] [--tags=integration[,tag...]] [--exclude-dirs=dir1,dir2] [--memory-mode=low] [--max-memory=1GiB]
Walks and parses a Go repository. Generates the structured graph at .gograph/graph.json and nine targeted Markdown reports in .gograph/.
Adds .gograph/ to the Git repository root .gitignore when available; outside Git, falls back to the build target .gitignore.
The update accepts only an absent or regular .gitignore; a symlink or special
file is refused without modifying its target.
The scanner honors the effective Go build context, including build tags, platform filenames, cgo, test-file constraints, cmd/go package-directory rules, and module ignore directives. Git-ignored files and directories use the same exclusion policy in build, stale, and changes. Linked directories plus linked/special files for extensions recognized by go/build are reported and excluded, while an explicitly symlinked repository root remains supported. Unrelated regular-file or dangling links with non-Go extensions, such as YAML configuration and TSV fixtures, are not Go tool inputs and do not block precise analysis. Linked/non-regular go.mod, go.sum, go.work, go.work.sum, and vendor/modules.txt metadata is rejected before toolchain use. Applicable go.work use members may be sibling modules beneath the nearest real Git checkout; without that boundary they remain confined beneath the workspace directory. Nested Git boundaries are not crossed, and member directories, go.mod, and optional go.sum are validated before cmd/go. AST parsing uses repository-confined source bytes. If no Go files are found or none parse successfully, exits without replacing existing artifacts. Partial status includes parse failures and selection/security warnings recorded in graph.json.
Graph/report publication waits up to 30 seconds for
.gograph/.artifacts.lock, then stages and syncs all ten files. The nine
reports are renamed first and graph.json is renamed last as the commit
marker. Publication refuses a linked or non-directory .gograph, and readers
accept only a regular repository-confined graph.json. An existing
.artifacts.lock must also be a regular file. Same-directory
replacement is atomic on Unix-like systems but is not
guaranteed atomic by Go on non-Unix platforms, and the bundle is not one atomic
filesystem transaction; a crash can leave reports ahead of the previous
graph.json. The lock file remains as separate operational state. A failed
build --precise retry keeps an existing fresh precise artifact for the same
selected sources instead of publishing a downgrade.
A build of an unchanged checkout writes nothing (--force rebuilds and
rewrites): it reads .gograph/graph.meta.json, a sidecar holding the build
metadata and file digests of the published graph.json, and stops when the
source, build context and requested precision match and every report exists.
The sidecar is used only for the graph.json whose size and modification time
it records; otherwise the decision decodes graph.json.
Every successfully parsed file stores a SHA-256 digest. A later build reparses
all selected files in each changed package directory and reuses parser-owned
records for unchanged packages. This package boundary avoids mixing old and
new declarations within one Go package. --precise benefits from the reused
AST base, but type loading and CHA/SSA enrichment still run repository-wide so
cross-package method sets and dispatch targets remain correct.
- Arguments:
path(optional, defaults to.) - Flags:
--tags=<tag[,tag...]>: Selects additional Go build tags for the whole graph, including test files and precise package loading. The flag is repeatable; values are validated, deduplicated, and canonicalized. An explicit value replaces any-tagsinherited fromGOFLAGS, matchingcmd/goprecedence. Without this option, existingGOFLAGSbehavior is unchanged. The selected context is part of the graph fingerprint.--precise: Attempts type-checked CHA/SSA enrichment after a repository preflight that rejects source-tree linkscmd/gomay inspect across the selected root plus its effective module root, or the workspace root and member trees;.gitand.gographare excluded from that walk. It also rejects special recognized build inputs, unsafe workspace members, and linked/non-regular module/workspace metadata entries. Enrichment needs compilable, build-selected production packages; on unsafe input, failure, or an incomplete non-test package load gograph warns and publishes the unchanged AST graph unless a fresh successful precise artifact already covers the same safely selected sources. Graph metadata recordsprecise,precise_fallback, orast. Precise interface calls retain one parallel call edge per valid named in-repository target; promoted methods add an explicitly marked traversal-only forwarding edge. A separate typed pass resolves compiling test packages without making test compilation a prerequisite for production precision. Broken or omitted test packages producetyped_partialtest-call attribution rather than a production precision fallback.--strict: Requires--precise. Precise enrichment failure keeps the same publication/retention behavior and diagnostic metadata, then exits non-zero. Without this flag, precise fallback keeps its compatible exit-zero behavior.- Graph v2 compatibility: Precision/column/synthetic, content-digest, analysis-cache, parser/precise provenance, and reuse-count fields remain additive. Graphs without the exact current source-policy marker are deliberately rebuild-required because their source-derived data cannot be trusted. A legacy graph without digests retains mtime-based freshness until one current build upgrades it, but is never eligible for parser-record reuse. Older v2 binaries can decode newly written graphs but do not enforce repository source confinement and may count or display synthetic forwarding records as ordinary calls; use the current binary for untrusted repositories and new graphs.
- Artifact memory safety: Whole graph, saved-baseline, validation, MCP reload, and workspace-overlay JSON reads reject artifacts larger than 512 MiB before allocation. Query-only commands return rebuild guidance. A build treats an oversized previous graph as unusable, reconstructs parser facts from source, and recomputes typed-only test targets before publication.
- SSA scope: Precise production SSA bodies cover the selected repository packages rather than the transitive dependency closure. Imported types and local references to external calls remain available; dependency-body call graphs and their source-less synthetic wrapper edges are not persisted.
--memory-mode=low: Preserves the same analysis and output semantics while prioritizing lower heap use through aggressive garbage collection and phase-boundary memory reclamation, and a selective transactional precise-enrichment copy.--max-memory=<size>: Adds a soft Go-runtime memory target and requires low mode. Integer decimal and binary sizes such as1GB,768MiB, and1GiBare accepted. This is not a hard RSS cap: mapped files, the binary, cgo, and Go toolchain subprocesses are outside or may exceed the target. Gograph does not silently reduce precision when the target is too small.
stale
Recorded directory exclusions are used by default; --exclude-dirs checks an
explicit alternative selection. Included source changes invalidate freshness;
excluded source changes alone do not. Rebuild after modifying an unindexed
dependency that included code imports.
gograph stale [--tags=integration[,tag...]] [--exclude-dirs=dir1,dir2] [--json]
Compares the selected-file inventory, effective Go build context, and SHA-256 source-content digests with .gograph/graph.json. Modification times remain diagnostic fields only. It reports added, deleted, newly active, newly inactive, and byte-modified selected files plus build-context changes.
Without --tags, a graph built with tags is checked against those recorded
tags unless GOFLAGS sets -tags; an explicit --tags or GOFLAGS -tags
that differs is reported as a build-context change. Query commands (source,
callers, query, …) accept the same --tags and follow the same rule.
Text output reports the persisted graph’s source, freshness, completeness, and
precision. JSON adds the same full gograph.graph-state.v1 object as top-level
graph_state, including refresh and persistence outcomes.
Text and JSON modes use the same exit contract:
0: the graph is current2: the graph is stale and should be rebuilt1: an operational/serialization error occurred, including a missing or unsupported source-policy marker that requires rebuilding
When using set -e, put the command in an if condition and branch explicitly
on status 2. Do not use gograph stale || gograph build ., because that also
rebuilds on status 1 and can hide the original error.
stats
gograph stats [--json]
Provides a source-parse-free index health summary derived from the persisted
.gograph/graph.json. The CLI does not refresh before reporting it.
Text adds artifact_source and freshness; JSON adds top-level
gograph.graph-state.v1. Successful repository graph-backed CLI JSON commands
use this same additive field without changing their existing results value.
- Output fields:
schema_versiongenerated_atprecision(ast,precise, orprecise_fallback)test_call_resolution(ast_heuristic,typed_complete, ortyped_partial)packagesfilessymbolscalls- Counts graph edges. One precise interface call expression contributes one edge per valid named in-repository CHA target; promoted-method wrappers can add synthetic traversal-only forwarding edges that are hidden from call-site output.
importsroutessqlsenv_readstest_edgesflow_functionsbuild_status(completeorpartial)scanned_filesandparsed_filesin JSON; text rendersparsed_filesasparsed/scannedreused_filesandrebuilt_packagesin JSON; text renders the latter asrebuilt_pkgsparse_failures
validate
gograph validate --repo PATH --binding-json JSON --json
Evaluates one strict gograph.binding.v1 structural predicate against the
existing trusted repository graph and emits exactly one
gograph.validation.v1 document. It never builds or refreshes an artifact.
Supported predicates are symbol_exists, package_imports,
call_edge_exists, type_implements, and the policy predicates
imports_only_from (only allowlisted packages or files import a package),
callers_only_from (only allowlisted packages or files call a function, such
as os/exec::Command) and call_arg_constant (argument N is always a
compile-time constant, or never one of forbidden_values). Policy failures
list every violating file and line. Exit status is 0 for pass, 1
for an evaluated fail, and 2 when the request cannot be evaluated or is
invalid. This process-status machine-validation adapter is CLI-only; MCP
callers use the corresponding query/evidence tools rather than a validation
predicate endpoint. See the Machine Validation Contract
for the schemas, freshness rules, and completeness requirements.
Search & Navigation
explore
gograph explore <term...> [--compact|--deep] [--limit N] [--exact] [--json]
Performs bounded first-call discovery by composing ranked broad lexical matches
with one explicitly disclosed selected symbol’s node metadata, source, direct
callers, direct callees, attributed tests, and exact identity-resolved
transitive upstream impact. Possible dispatch edges are excluded from this
bounded impact section. Use focused impact for broader fallback traversal.
- Selection:
selection_basisisdirect_symbol_match,ranked_lexical_match, ornone;ambiguousremains true when the selected symbol resolves to several nodes. Question-like input is tokenized lexically and is not interpreted by a model. - Response modes: Standard mode preserves the original response and
defaults to 10 rows.
--compactdefaults to 5 rows and keeps ranked matches, selected node/role, full totals, andomitted_sectionswhile omitting source, caller, callee, test, and impact bodies.--deepdefaults to 25 rows, retains the standard response, and adds bounded depth-3 exact identity callers/callees, selected package context, and explanation. Compact and deep are mutually exclusive. - Bounds: An explicit
--limitoverrides the mode default, applies independently to every returned list, and is clamped to 1-100.totalsreports complete section sizes andtruncated_sectionsidentifies every bounded section. Deep also carries its own totals and explanation truncation metadata. Use the focusedquery,context, orimpactcommand when a complete section is required. - Deep precision: Deep traversal excludes possible dispatch and crosses
synthetic forwarders transparently. Caller/callee rows carry
stable_id, call-site provenance, and declaration location when the target is indexed. An ambiguous selected symbol omits the deep expansion until an exact fully-qualified identity is supplied. - Exact mode:
--exactrequires exact resolution for selected-symbol context; broad lexical matches remain visible but are not promoted automatically. - JSON/MCP parity: CLI
--jsonplaces the nativegograph.explore.v1value in its genericresultsenvelope. MCPgograph_explorereturns that same native value as JSON text, with requiredquery; optionallimitandexact; and mutually exclusive typedcompactanddeepbooleans. - Next commands: when one symbol is selected unambiguously, text output ends
with
next:lines naming the test-selection, transitive-tests and impact commands for it.
query
gograph query <term...> [--no-tests] [--path DIR|FILE]
Performs a broad, case-insensitive substring search across multiple entities.
- Scans: Symbol names, struct fields, file paths, package names, import paths, and call sites.
- Test filter:
--no-testsexcludes test-file rows before pagination; MCP usesno_tests=true. - Logic: Performs OR-matching if multiple terms are provided.
focus
gograph focus <package>
Extracts targeted package orientation context.
- Output: Returns all files, symbols, internal calls, and dependencies of the specified package.
node
gograph node <name>
Displays detailed AST metadata for a single named symbol, package, or file.
An exact, case-sensitive name or selector (Manager, Manager.Run, pkg.Manager)
selects only that declaration; a case-insensitive exact match comes next, and a
substring match only when neither finds anything.
- Output fields: Kind, file, line, signature, comments/docstrings, and struct fields. A constant shows its declared value (
SymbolKind = "method",= 16 * 1024); a constant that repeats its group’s expression is marked with its iota. Graphs built before v1.7.24 have no values; rebuild to add them.
source
File-qualified selectors also work with the declaration tools listed in the query contract. Embeds, constructors, literals, returnusage, mutate and endpoint report a named file-selector limit. Usages supports file-qualified variables/constants, but reports that limit for types. Capabilities lists these exceptions.
gograph source <name> [name...]
gograph source <name|path/file.go> --lines START-END
Extracts exact raw source blocks for a function, method, struct, interface,
type, variable, or constant using the graph’s location data. Reads are rooted
at the analyzed repository and accept only regular .go files without symlink
path components. An ambiguous name prints exact selectors, such as
internal/auth/auth.go:Verifier.Verify, and a name that matches nothing lists
close selectors (“did you mean”); the full import path plus file name is
also accepted, and so is a package path with the symbol, as a full import path
or repository-relative (internal/auth::Verifier.Verify, internal/auth.Verify). The command errors when no matching block can be read safely.
Several selectors (gograph source slotHostDefault slotHostOverride) print
each block in order, separated by ---; with --json the results are
{selector, source} objects. If any selector fails, the blocks that resolved
are still printed and the command fails naming each failed selector.
--lines START-END (file line numbers, inclusive) prints only that part of one
declaration, clamped to it, so a region of a body larger than the 64 KiB budget
can be read; given an indexed file path (gograph source internal/app/manager.go --lines 1-20) it prints that region of the file, including the package clause,
imports and comments. A file changed since the build is refused. A .go file the
graph’s build context leaves out (build constraints such as another GOOS, or
an excluded directory) is printed from disk, whole, as file.go:START-END or
with --lines, under a header saying its declarations are not indexed; a name
inside it is refused with the platform to build for (GOOS=linux gograph build . for x_linux.go). MCP:
gograph_source with lines.
- Note: This is the preferred way for AI agents to view symbol declarations and bodies, avoiding reading entire files.
Call Graph Commands
callers
gograph callers <function> [--no-tests] [--depth N] [--exact] [--mermaid]
Finds all callers of a target function or method. Names that differ only by
letter case are different declarations: a spelling that matches some
declarations with the exact case (Memory.key) selects only those; one that
matches none exactly (memory.KEY) covers every case variant and lists them.
- On AST graphs, a method call whose receiver type is spelled in the calling function (the receiver, a typed parameter or
var, a composite literal ornew(T), then struct fields such asc.clock.now()), or that is called directly onT{},&T{},new(T)orx.(T), is not matched to a same-name method of another type, and a receiver of a package outside the graph (such asbytes.Buffer) matches no repository method;tests,plan,reviewandcoverageapply the same rule. Interface values, call results, shadowed names and structs with embedded types stay candidates. Graphs built before this needgograph build .(incremental builds re-parse automatically). - Interface-qualified names such as
Repository.Delete, including methods inherited from embedded interfaces, resolve through every recorded precise implementer. If several targets correspond to one invocation, the source expression is returned once. Records with a known column report it as well as the line; records without a column remain line-only. - Flags:
--no-tests: Filters out test files from caller results.--depth N: Traverses the call graph upwards up toNhops (from 1 to 10). Useful for scoped neighborhood analysis. Defaults to1(direct callers).--exact: Requires exact symbol-name or fully-qualified-ID matching.
callees
gograph callees <function> [--no-tests] [--depth N] [--mermaid]
Finds all functions or methods called from within the target function.
- Flags:
--no-tests: Filters out calls within test files.--depth N: Traverses the call graph downwards up toNhops (from 1 to 10). Defaults to1(direct callees).
impact
gograph impact <symbol>
gograph impact --uncommitted
gograph impact --since <ref>
Calculates the transitive upstream blast radius (all functions that eventually call the target).
- Options:
<symbol>: Performs impact analysis for a specific function.--uncommitted: Computes the blast radius for all currently modified uncommitted symbols.--since <ref>: Computes the blast radius for all symbols changed since the specified git reference (e.g.,main,v1.4.50).--mermaid: Returns the blast radius as a Mermaid flowchart.
--uncommitted uses declaration comparison against HEAD, including selected
untracked Go files. Like --since, it refuses incomplete comparisons, deleted
declarations requiring historical caller evidence, and identities absent from
the current graph. Use changes --git REF for the deletion census; rebuild
before traversing newly added symbols. The same guard applies to context,
plan, review, and risk in uncommitted mode, in CLI and MCP.
path
gograph path <from> <to> [--json|--mermaid]
Calculates the best indexed call chain between two symbols. Competing paths are
ranked deterministically by exact before possible, then shorter paths,
production before tests, typed resolution before heuristics, and a canonical
relationship key. CLI and gograph_path use the same implementation.
Either end may be a file selector (internal/app/run.go:Run), a package-path
selector (internal/app::Run) or a stable ID; the chain then starts from, or
ends at, exactly that declaration, also on AST graphs.
orphans
gograph orphans
Finds dead code candidates using BFS from main/init, test/benchmark/fuzz roots, registered routes, and eligible externally callable exports. Exports under internal/ are not roots; dead chains are reported even when their members call one another. Precise reachability follows every retained interface target, not an arbitrary single implementation.
Interfaces & Types
fields
gograph fields <struct>
Lists a struct’s fields, types, and tags.
embeds
gograph embeds <struct>
Finds structs that anonymously embed the named type.
implementers
gograph implementers <interface> [--test-only]
Finds structs that implement the named interface (duck-typing).
- Type-checked production results are merged with AST-discovered test-file implementations because production package loading does not include test variants.
- Flags:
--test-only: Restricts results strictly to structs defined in test or mock files.
interfaces
gograph interfaces <struct>
Duck-type checker. Finds all interfaces in the codebase that the specified struct implements.
constructors
gograph constructors <struct>
Finds factory and constructor functions that return the named struct (e.g., NewClient, New*).
strings
gograph strings <term...> [--no-tests] [--path DIR|FILE]
Searches Go string literals in the indexed source files and reports each
match with its file, line, and enclosing function. Use it for raw route
strings, URLs, SQL fragments, header names, and messages that are not
symbols, instead of grep. Matching is a case-insensitive substring test
with OR semantics across terms. Route-shaped terms match any path-parameter
spelling, so /users/{id}, /users/:id, and /users/*id find each other.
Files are read through the confined repository reader. Indexed files that
were deleted or moved since the build, or cannot be read safely, are named in
a warning with the reason and a rebuild hint. On a stale graph the CLI also
searches Go files added since the build; those rows say so instead of naming
an enclosing function. --json and --files-only are supported. MCP:
gograph_strings (term, query, or terms; no_tests; limit/cursor).
query also matches registered HTTP route patterns with the same parameter
normalization, and both query and strings accept a repository path as
--path or as a trailing directory argument (gograph query org-link .).
A --path file or subdirectory inside the repository also keeps only results
in that file or subtree (gograph query Run --path internal/app/manager.go).
Arguments after -- are terms, even when they start with -
(gograph strings -- --log-file); global flags such as --json go before --.
literals
gograph literals <struct>
Finds every place where the struct is initialized using a composite literal (StructName{...}). Essential to run before adding or removing a required field to know exactly which sites will break.
returnusage
gograph returnusage <function>
Traces how each caller handles the return values of the specified function.
- Labels:
discarded,assigned,partially_ignored,returned, orpassed. Run this before refactoring signatures to find callers that silently ignore return values.
usages
gograph usages <type>
Finds every place where a named type appears in parameter/return lists, struct
fields, interface methods, or composite-literal construction. Use
gograph literals <type> for the focused Foo{...} construction-only subset.
Essential for tracing the impact of a type change.
With a precise index, this also finds package-level variable and constant
references in comparisons, switch cases, composite values, and function
arguments. Typed enum-like constants retain their resolved identity, excluding
local shadows. Broad query includes these sites as usage rows. AST-only
indexes do not claim type-resolved constant references.
gograph usages <Type.Field> (also pkg.Type.Field, or a bare field name that
is not a type) answers struct fields: the declaration plus every field_read,
field_write, field_address, and keyed field_literal site. Uses are
attributed to the struct that declares the field, so promoted fields through
embedding resolve to their embedded struct, and a same-named field of another
struct is not included. A precise build records these type-checked rows for
production packages in the field_uses graph section. An AST-only graph
returns a limit row and name-only possible_field_use rows instead.
Uncommitted plan and review omit blank-identifier declarations from symbol
traversal. Review preserves the declaration evidence and names that limit;
changes --git HEAD still includes the blank assertions.
schema
gograph schema <table>
Finds structs mapped to a database table or schema via struct tags (e.g. db:"...", gorm:"...").
globals
gograph globals <pkg|dir>
Finds all package-level variables and constants, as well as functions that mutate them. A term containing / (for example internal/app or the full import path) selects exactly that package; any other term matches package names by case-insensitive substring.
mocks
gograph mocks <interface>
Alias for implementers <interface> --test-only. Kept for compatibility.
fixtures
gograph fixtures <pkg>
Finds helper types, factory functions, and other non-test symbols within
*_test.go files in a specific package. Functions named Test*, Benchmark*,
or Example* are excluded.
Packages & Dependencies
deps
gograph deps <pkg> [--transitive] [--mermaid]
Finds the direct import dependencies of a package.
- Flags:
--transitive: Calculates the full transitive closure of package imports (BFS).
dependents
gograph dependents <pkg> [--mermaid]
Finds all packages in the repository that import the specified package (the inverse of deps). Deduplicated by package. Highly recommended to run before package-level refactoring.
changes
gograph changes
gograph changes --git <ref>
Without --git, compares current source against the last trusted persisted
graph using declaration fingerprints, not all symbols in a changed file.
Formatting/comment-only edits do not change a declaration. Removed declarations
are detected even inside surviving files. Existing but deselected files are
excluded, not deleted; unsafe paths and parse errors are diagnostics, never
proof of deletion. Missing legacy declaration fingerprints produce unknown.
Git-ref mode extracts a confined declaration baseline and supports new, modified,
and deleted declarations without compiling Go code. gograph.changes.v1 reports
complete, partial, or cannot_evaluate; incomplete CLI evaluation exits 2.
MCP gograph_changes returns the same native evaluation and diagnostics.
Both modes reuse recorded platform/compiler/CGO and effective build/tool/release
tags rather than inheriting different ambient GOFLAGS. Missing legacy
selection metadata is partial. Current module ownership is rediscovered even
when source bytes are unchanged; package names distinguish external-test twins.
Repeated initializers are retained, and changing their order is reported.
Detected source/selection races invalidate the comparison; retry on a stable tree.
imports
gograph imports <pkg>
Finds all source files in the repository that import a specific external or internal import path.
public
gograph public <pkg>
Lists the exported (public) functions, methods, types/interfaces, variables, and constants of a package.
Extraction Commands
routes
gograph routes [term] [--module MODULE] [--include-tests] [--limit N] [--cursor CURSOR]
Returns a deterministic gograph.routes.v1 page of HTTP REST API routes from
Gin, Chi, Echo, Fiber, and net/http-style registration calls. Production routes
are included by default; --include-tests adds registrations from _test.go.
The optional term matches method/path, handler, or file. --module accepts an
exact module path/directory, a unique nested-module directory basename, or the
repository directory name for the root module. Pages default to 100 rows,
accept 1-200, and stay within a 64 KiB compact-JSON budget; use the returned
cursor with unchanged filters to continue a truncated census. CLI JSON mirrors
total, returned, truncated, and next_cursor directly on its envelope and
retains the complete native page under results.
CLI --files-only follows every page locally and emits the complete
deduplicated file set, not a complete route-row dump; normal text and JSON
return one bounded page.
Constant nested Gin/Echo/Fiber Group prefixes and Chi Route closure prefixes
are composed into final paths. Dynamically computed prefix expressions remain
unresolved, so those routes retain their known literal suffix. Variadic
Gin/Fiber registration uses the final argument as the terminal handler. Echo
uses path, handler, middleware..., and gograph retains that ordering. Handler
factories remain marked dynamic when their returned closure cannot be
statically resolved.
Path constants and concatenations are retained, including ServeMux method patterns. A precise build resolves imported and cross-file constants. Unresolved runtime path expressions remain visible with a diagnostic.
sql
gograph sql [term] \
[--table TABLE]... [--verb VERB]... [--access read|write|ddl]... \
[--function NAME] [--module MODULE] [--no-tests] \
[--limit N] [--cursor CURSOR]
Returns deterministic gograph.sql.v1 pages for static PostgreSQL statements,
including the actual operation, statement access class, referenced tables,
enclosing Go function, module ownership, and source location. The positional
term remains a case-insensitive raw-query substring for compatibility.
Extraction covers direct literals plus statically resolvable local and
same-file package const/var declarations, straight-line assignments, and
bounded string concatenations.
This includes multiline INSERT ... RETURNING statements before table/access
filtering; runtime-generated SQL remains outside the static census.
--table accepts either table or schema.table; --verb accepts SELECT,
INSERT, UPDATE, DELETE, MERGE, CREATE, ALTER, DROP, or
TRUNCATE; and --access accepts read, write, or ddl. These three flags
are repeatable: values within one category OR-compose, while different filter
categories AND-compose. --function is a case-insensitive enclosing-function
substring. --module accepts an exact module path/directory, a unique nested
directory basename, or the repository basename for a root module.
Tests remain included by default to preserve existing behavior;
--no-tests excludes _test.go. Pages default to 100 rows, permit at most
200, and stay within 64 KiB. Continue with next_cursor and the same filters.
CLI --json mirrors total, returned, truncated, and next_cursor on the
outer envelope; --files-only follows every page for a complete file census.
MCP gograph_sql executes the same native query. Its typed parameters are
term, tables[], verbs[], accesses[], function, module, no_tests,
limit, and cursor, and its JSON text is the same gograph.sql.v1 page found
under CLI results.
Classification is deliberately PostgreSQL-specific and static. WITH queries
report their actual terminal operation, and INSERT ... ON CONFLICT remains
INSERT. A data-modifying CTE retains its write-table evidence and elevates the
statement access even when the terminal operation is SELECT. Every row reports
exact, partial, or unknown; runtime-generated SQL and unsupported constructs
are not presented as confidently classified. Rebuilt graph-sql.md reports expose
the same persisted operation, access, table, and classification metadata.
errors
gograph errors [term] [--no-tests]
Lists indexed errors.New/fmt.Errorf calls, sentinel declarations, and panic
calls mapped to their source locations.
envs
gograph envs [term]
Lists every os.Getenv, os.LookupEnv, or supported Viper Get* read in the
codebase, with file and line. Optional substring filter by key name.
concurrency
gograph concurrency [term]
gograph concurrency --locks <function>
Maps goroutine spawns (go func), channel sends, and calls on mutex/RWMutex,
WaitGroup, and sync.Once. Channel receives and select statements are not
indexed.
--locks <function> takes one function or method selector (Manager.start,
pkg::(*Manager).start, internal/app/manager.go:Manager.start), parses its
body at query time, and lists each Lock/RLock call with its release: the
matching unlock lines, “held until return” for a deferred unlock (including one
inside a deferred closure), or “not released in this function”. Under each lock
it lists the calls between the lock and its last matching unlock before the
next lock of the same mutex. Spans are lexical: an early-return unlock in a
branch does not split the span, but calls that follow an unlock in the same
block (such as the return fmt.Errorf(...) after it) are not listed. --json returns {function, file, start_line, end_line, locks: [{lock, line, release, release_line, unlock_lines, end_line, calls: [{call, line}]}]}. MCP: gograph_concurrency with function.
httpcalls
gograph httpcalls [term]
Lists imported, unshadowed package-level net/http calls (Get, Post,
PostForm, Head) and possible NewRequest/NewRequestWithContext
construction. The optional filter matches method, URL/base, or function context.
Shares bounded --limit/--cursor pages with gograph_httpcalls; detail includes
bounded dynamic base/static-suffix evidence and labels construction without
dispatch proof. Client receiver methods and arbitrary URL builders are not inferred.
No runtime environment values are read.
flow
gograph flow [term] [--source http_request|decoded_json|environment|<custom>] [--sink sql_query|process_execution|filesystem|outbound_http|<custom>] [--config path] [--no-tests] [--package path[/...]]... [--max-work N] [--context-depth N]
Finds potential paths from untrusted inputs to security-sensitive operations. Test files are included by default; --no-tests limits analysis to production files.
-
Sources:
http_request: parameters typed as*net/http.Requestor recognized Gin, Echo, Fiber, and fasthttp contexts.decoded_json:encoding/json.Unmarshal,encoding/json.NewDecoder(...).Decode, Go 1.27’sencoding/json/v2decode functions (Unmarshal,UnmarshalRead, andUnmarshalDecode), and recognized framework binding methods.environment:os.Getenv,os.LookupEnv, and supported Viper package reads.
-
Sinks:
sql_query: the query-text argument toQuery,QueryRow,Exec,Prepare, andRawvariants. Parameter values are not treated as query text, and a leading context argument (pgx-styleQuery(ctx, sql, args...)) moves the text to the second argument.process_execution: command and argument values passed toos/exec.CommandorCommandContext. When the program is a constant literal that is not a shell or interpreter (git, notsh), findings are markedparameter_onlyand rated at most medium: only argument injection is possible.filesystem: path arguments to commonosfile operations.outbound_http: URL/request arguments passed to package-levelnet/httpcalls, request constructors, andDomethods.
-
Output: Severity, confidence, source and sink locations, and source-to-sink path steps.
--jsonreturns structuredFlowResultobjects;--files-onlyreturns deduplicated source and sink files. -
Sanitizers: The command automatically reads
gograph/flow.json(committable), else.gograph/flow.json, when present, and prints the policy file it used.--configselects another JSON file inside the graph root. Policies apply to return values and may be sink-scoped:{ "sanitizers": [ { "function": "security.CleanPath", "for": ["filesystem"] }, { "function": "security.ValidateURL", "for": ["outbound_http"] } ] }Omit
forto apply a sanitizer to every sink kind.functionaccepts the call spelling or a fully-qualified symbol ID (also of dependencies, such asos/exec::Command, on precise graphs); use the fully-qualified form for duplicate names. A sanitizer with"argument": Nis a validator: within the calling function, the value passed as argument N (and its fields) is trusted for the listed sinks.Repository-specific sources and sinks extend the built-in kinds:
{ "sources": [{ "function": "agent.ReadAgentOutput", "kind": "agent_output", "return": 0 }], "sinks": [{ "function": "mcpio.WriteMCPResponse", "kind": "mcp_response", "argument": 1, "severity": "high" }], "sanitizers": [{ "function": "mcpio.Validate", "for": ["mcp_response"], "argument": 0 }] }A source taints the call’s return values (all, or only
return); a sink checks its arguments (all, or onlyargument);kindis lower-case letters, digits and underscores and works with--sourceand--sink;severitydefaults tohigh. Without a policy the built-in behavior is unchanged. -
Budget: when the work budget runs out,
completeness.top_functions(and the text output) lists the functions that consumed the most propagation work;--package(MCPpackages) limits analysis to chosen import paths. -
Limitations: Interprocedural and path-insensitive, with call/return context for the 3 most recent call sites by default (context depth up to 16; deeper returns that lose their call site are kept at low confidence), bounded by a size-derived work budget that reports incomplete runs explicitly. Default graphs resolve direct local/imported functions; run
build . --precisefor stronger method/interface targets. Reflection, globals, arbitrary heap aliases, and unresolved dynamic calls may be missed or over-approximated. Unresolved external transformations lower confidence. Findings require source review and do not prove exploitability.
tests
gograph tests [symbol] [--json]
gograph tests <symbol> --transitive [--exact-only] [--package name] [--max-depth N] [--limit N] [--cursor T] [--json]
gograph tests --uncommitted|--since <ref> [--format run|go-test] [--exact-only] [--max-depth N] [--json]
gograph tests <symbol> --format run|go-test [--package name] [--exact-only] [--max-depth N] [--json]
Which tests to run for a change. --uncommitted (working tree against
HEAD), --since <ref>, or --format with one symbol select every test that
reaches the changed (or named) functions and print, per import path, an anchored
and regex-escaped -run pattern of top-level test names (benchmarks get a
-bench pattern). Naming a test function (gograph tests TestRun --format go-test) selects that test itself. --format go-test prints only runnable
commands, one per package, with the graph’s -tags:
go test -tags=integration example.com/app/calc -run '^(TestMul|TestTotal)$'
go test example.com/app/api
A package whose every test is selected runs without -run, and long patterns
are split at 16 KiB. Changed tests select themselves; tests deleted by the
change are never listed; a deleted function still in the pre-change graph
selects the tests that reached it. A changed type (or tests <Type>) selects
the tests of the functions that use it: its methods (exact), functions whose
signatures name it and composite literals of it (possible), and, on precise
graphs, its field uses (exact); its root reports users. A changed variable or
constant selects the tests of its uses on precise graphs only; on AST graphs it
is reported under unselected with a --precise hint. When a change reaches
the main function of a package, that package’s tests that start a process
(exec.Command/exec.CommandContext, directly or through a helper) are
added as possible: they usually run the built binary. Tests in other packages
that run a binary are not linked. New functions missing from a stale graph are
reported under unselected (status partial). When every path to some selected
tests is possible (interface dispatch, or a signature or literal naming a
type), stderr notes how many and what --exact-only keeps; a type whose method
satisfies a common interface (Error, String) is a possible target of every
call through that interface. --max-depth N keeps tests whose shortest call path is at
most N, --exact-only drops paths through dynamic dispatch. --json returns
gograph.test_selection.v1.
Default mode lists direct attributed test edges for compatibility and accepts
Receiver.Method (including pointer-receiver stable targets) or a full stable
symbol ID without conflating another receiver’s same-named method. Transitive
mode requires one product symbol and returns gograph.tests.v1: a summary of
every reaching test by depth and resolution (and next_command), then one page
of tests sorted nearest first (depth, then exact before possible), each with
a representative stable-ID path. Pages hold 50 tests by default (--limit N,
--limit 0 for all) with total, returned, truncated and next_cursor;
pass --cursor to continue. --exact-only removes paths containing parser/CHA
uncertainty, and --package disambiguates a same-named product symbol. The MCP
equivalent uses transitive, exact_only, package, max_depth, limit,
cursor, plus uncommitted, since and select for selections. Static
attribution is not runtime or branch coverage proof. MCP since/uncommitted
selections, like the CLI, read the tests of a deleted declaration from the
compared revision’s graph.
Test memory skips tests that already passed on identical inputs:
gograph tests --uncommitted --skip-passed --run selects, drops remembered
passes, runs the rest with go test -json and records the results
(--record F for a run gograph did not start, --max-time D,
--stop-on-fail, --go-flags, --input, --trust-env). On a --precise
graph a process start, unnamed environment read or service connection refuses
only the tests that may reach it; a function literal stored in a package
variable refuses only the tests that reach the variable, while a call run by a
package initializer or TestMain refuses the whole package. gograph help test-memory is the full contract.
coverage
gograph coverage <test-function-or-stable-id> [--exact-only] [--package name] [--json]
Returns the transitive product functions and methods statically reachable from
one test. Every row carries a canonical stable ID, representative path, depth,
and exact or possible resolution. Any uncertain parser/CHA edge degrades
the remainder of that path to possible; --exact-only omits those rows.
Same-named tests in multiple packages return an ambiguity instead of merging
their results. When an in-package test and external foo_test package share the
same graph ID, --package (MCP package) selects the exact Go package name.
This is static attribution, not runtime or branch coverage.
whatsnew
gograph whatsnew [--since vX.Y.Z] [--json]
Prints the release notes shipped with the running binary: the section for its
release, or, for a development or branch build, the unreleased changes plus the
latest release. --since lists every release newer than the given version up
to the running one. --json returns gograph.whatsnew.v1. This command is
CLI-only; MCP clients read the server version from gograph_capabilities.
uncovered
gograph uncovered --uncommitted|--since <ref> --coverprofile <file> [--json]
Lists the changed lines of non-test Go files that a go test -coverprofile
run never executed, as exact line ranges per file (gograph.uncovered.v1).
--uncommitted compares the working tree with HEAD and includes untracked
files; --since compares it with a ref. Merged profiles are accepted; a block
executed in any run counts as executed. Only lines inside coverage blocks count:
declarations, comments and blank lines are never reported, and changed files
without profile data (an untested package without -coverpkg, or a file outside
the build) are listed separately. The MCP equivalent is gograph_uncovered,
whose coverprofile must be a repository-relative file.
identity
gograph identity <symbol-or-stable-id> [--package name] [--json]
Prints and re-resolves canonical symbol IDs. IDs use module import path plus receiver/name, so line shifts and file moves inside the same package do not change them. Package/module moves, receiver changes, and renames do. Ambiguous short names return every candidate and never select one silently. The optional package qualifier handles colliding in-package/external-test IDs without using file/line as identity.
Composed Token Saver Commands
These compound commands are optimized for AI agent consumption to prevent sequential tool execution round-trips, significantly saving context tokens and reducing latency.
context
gograph context <symbol> [--limit N] [--exact]
gograph context --uncommitted [--limit N]
Gathers all essential structural details for a symbol or uncommitted changes in a single call.
- Output: Node AST details, exact source code, caller list, callee list, test list, and its calculated architectural
roleclassification. - JSON/MCP shape: CLI JSON and
gograph_contextkeep the first match innodefor compatibility, preserve every ambiguous match innodes[], exposerole, return both test names and structuredtest_results[], and report a non-fatal source read failure insource_error. - Flags:
--uncommitted: Bundles the full context for all currently uncommitted modified symbols into one response.
explain
gograph explain <symbol>
Synthesizes AST data into a rich, prompt-ready natural language prose narrative.
- Output details: Symbol purpose, Prod vs. Test split, McCabe cyclomatic complexity rating, SQL queries used, Environment variables read, matching HTTP routes, interface satisfaction, and an opinionated role classification (e.g., HTTP handler, orchestrator, utility).
endpoint
gograph endpoint <route> [--depth N] [--include-tests] [--json|--mermaid]
Generates a complete vertical slice report for a single HTTP endpoint.
- Inputs: Handler symbol name, route path fragment (e.g.
/users), or route pattern (POST /api/users). Constant grouped prefixes are resolved; for a dynamic group prefix, use the known suffix or handler symbol. - Composes: Route definition + handler function + full downstream callee chain (BFS, default depth 5) + database SQL queries + env vars read.
- Flags:
--depthis clamped to 1-20;--include-testsincludes routes registered in_test.gofiles;--mermaidreturns a fenced flowchart instead of the normal text/JSON presentation.
errorflow
gograph errorflow <term> [--no-tests]
Traces the lifetime of an error up to the HTTP/entrypoint layer.
- Algorithm: Resolves the error’s declaration site, return/wrapping locations (including
%wformat strings), and traverses the call graph upwards to find entry points. - JSON/MCP shape: CLI JSON, MCP
gograph_errorflow, andtracesharedefinitions, returnsites, propagationpaths, test names, structuredtest_results, and the static-analysis limitation. - Flags:
--no-tests: Excludes test-file callers from the trace.
trace
gograph trace <term> [--no-tests]
Alias for errorflow. Kept for compatibility and returns the same structured
payload under JSON/MCP.
plan
gograph plan <symbol> [--with-context]
gograph plan --uncommitted [--with-context]
Generates a comprehensive change-impact plan prior to editing.
- Output: Affected callers, relevant tests to run after editing, and specific risks (SQL writes, environment reads, public API drift).
- Flags:
--with-context: Inlines the completecontextfor every symbol listed in the plan, avoiding sequential lookup calls.--uncommitted: Generates a joint change plan for all currently modified uncommitted symbols.
- Next commands: the plan ends with the exact follow-ups to run (
next: gograph tests <symbol> --format go-test --max-depth 3,--transitive, andimpact); JSON carries them asnext_commandsand MCPgograph_planasnexttool calls.
review
gograph review <symbol>
gograph review --uncommitted
gograph review --since <ref>
Performs post-edit verification. --since <ref> reviews every declaration
changed between the Git ref and the working tree, committed or not (MCP
gograph_review with since).
- Output: Code changes, complexity drift, test coverage status, and a risk evaluation.
risk
gograph risk <symbol>
gograph risk --uncommitted
Combines blast radius, complexity, attributed tests, public API status, and SQL/env dependencies into a 0-100 risk score and verdict.
summary
gograph summary
Returns top hotspots, worst package instability, highest complexity, reachability-orphan count, and god-object count in one call.
untested
gograph untested [--pkg name] [--top N] [--exclude glob]... [--wide] [--exclude-interface-methods] [--coverprofile file] [--json]
Ranks called production functions and methods without an exact transitive path
from any test. Direct selectors, local method values, and proof-backed concrete
interface receivers can be exact. Open CHA/parser paths propagate possible to
their descendants, which remain in the result with test_resolution=possible
and possible_test_count; test_resolution=none means no bounded path was
found. JSON and MCP rows include canonical stable_id. --wide prints that
identity without truncation. typed_partial means the result remains an upper
bound. This is static attribution, not runtime coverage.
Each --exclude is matched lexically against the repository-relative source
path; use prefix/** for all descendants. The MCP equivalent is the exclude
string array on gograph_untested.
Rows rank none before possible (possible-only paths are often dynamic
dispatch such as error.Error), then by caller count.
--exclude-interface-methods skips methods that implement an interface method
(common standard-library ones such as Error, String and MarshalJSON, or a
repository interface the receiver implements) and reports how many it skipped.
--coverprofile <file> switches to runtime evidence: it lists every production
function with statements of which none executed in the go test -coverprofile
output (merged profiles accepted), whether or not it has static callers, with
the static resolution as supporting evidence; a function executed at runtime is
never listed. MCP: exclude_interface_methods and a repository-relative
coverprofile, which return {summary, results}.
Code Quality & Verification
check
gograph check [--config path]
gograph check --uncommitted
gograph check --since <ref|graph.json>
Executes static policy checks against package boundaries, API drift, changed-route and changed-export test requirements, exported-symbol test coverage, unreachable symbols, new globals, arity, and complexity. Git baselines are extracted to a temporary directory; a path ending in .json instead loads a saved graph baseline. Route checks use handler identity and detect body-only changes from Git changed files.
Saved graph baselines must be regular, non-linked files (including no linked ancestor) inside the selected project and carry the exact current repository source-policy marker. Their serialized root is ignored in favor of the trusted project load location. Rebuild or replace an unsupported baseline before use.
- Options:
--config path: Use a custom checks JSON file instead of.gograph/checks.json. A default or relative path is confined to a regular non-linked file beneath the selected project; an absolute path explicitly selects a regular local file.--uncommitted: Includes uncommitted changed-symbol/file context in checks that use change scope.--since <ref|graph.json>: Validates changes against a Git reference or a saved graph baseline.
gate
gograph gate
gograph gate init
Enforces CI/CD quality gates. Reads only a regular, non-linked project-root .gograph.yml and fails closed if graph.json is stale. A current graph then exits non-zero when configured complexity, instability, god-object, reachability-orphan, or coupling thresholds are violated. gate init exclusively creates the same regular project-root path and rejects links, special files, and existing entries.
Thresholds are configured only in .gograph.yml; gate does not accept
per-threshold CLI flags. Run gograph gate init, review and commit the generated
configuration, then run gograph build . --precise followed by gograph gate
in CI. Orphan and new-coupling limits compare with the immediately preceding
persisted graph and are skipped when that baseline is absent. Package-boundary
rules are a separate gograph boundaries check.
api
gograph api --since <ref|graph.json>
Builds a validated temporary graph from a Git reference, or loads a saved graph
whose path ends in .json, and reports exported API/contract additions,
removals, and changes. Saved graph files must be regular, non-linked entries
inside the selected project with the exact current repository source-policy
marker; their serialized root is ignored. contract is a compatibility alias.
snapshot
gograph snapshot save <name>
gograph snapshot diff <name>
gograph snapshot list
gograph snapshot drop <name>
Architectural metric snapshots stored under .gograph/snapshots/. Each entry
captures symbol count, reachability-orphan count, god objects, maximum
complexity, average instability, and coupling edges for before/after comparison.
The directory must be real and snapshot entries regular and non-linked. save
may overwrite an existing regular snapshot of the same name; drop removes
only the validated named regular file.
boundaries
gograph boundaries [--config path]
gograph boundaries --create [--config path]
Enforces package modularity boundaries.
- Options:
--config path: Evaluates package import relationships against an in-project, regular, non-linkedboundaries.json(default:gograph/boundaries.json, else.gograph/boundaries.json;--createwritesgograph/boundaries.json). Absolute and repository-relative in-project paths are accepted.--create: Exclusively creates a starting boundary map at that path from current package imports. Only real parent directories are created; links, special files, traversal outside the graph root, and overwrite are refused.
The CLI reads the trusted persisted graph, so run gograph stale and rebuild
before enforcing the policy. MCP gograph_boundaries applies the same boundary
evaluation after its normal source refresh.
complexity
gograph complexity [symbol] [--no-tests] [--top N] [--path DIR] [--json]
Displays McCabe cyclomatic complexity for all functions, sorted highest first. Optional substring filter by symbol name. --no-tests drops functions declared in _test.go files, --path DIR keeps one repository-relative directory subtree, and --top N keeps the N highest after filtering. MCP gograph_complexity takes symbol, top, no_tests and path.
- Labels:
LOW(1-5),MEDIUM(6-10),HIGH(11-20),VERY HIGH(21+), orUNKNOWNwith score-1when repository source cannot be read or parsed safely.
coupling
gograph coupling [package] [--include-stdlib] [--internal-only] [--mermaid]
Calculates Fan-In, Fan-Out, and Instability metrics for all packages or a target package.
- Formula:
Instability = FanOut / (FanIn + FanOut).0means no outgoing dependencies;1means no incoming dependents. Isolated packages reportn/a.
diagram
gograph diagram [--group-by package|module|service|file] [--max-depth N] [--include-stdlib]
Generates a Mermaid architecture diagram. Bare gograph --mermaid is shorthand for the package overview.
hotspot
gograph hotspot [--top N] [--include-tests]
Identifies structural hotspots by ranking functions by their incoming call count (fan-in). Essential to identify high-risk parts of the codebase. Defaults to --top 10 and excludes test-file call edges unless --include-tests is set.
godobj
gograph godobj [--methods N] [--fields N] [--calls N] [--top N]
Ranks structs that exceed any enabled method, field, or outgoing-call threshold; combined excess determines severity.
skeleton
gograph skeleton [file] [--json]
Outputs API signatures with function/method bodies stripped. Supply an exact repository-relative indexed file, such as tools/devseed/main.go, to return only that file’s package clause, import block (grouped as gofmt
does, with aliases) and declarations. A missing file is an error; basename matching and repository fallback are not used. With no file argument, outputs the entire repository for structural orientation. The MCP tool gograph_skeleton accepts the same optional file parameter.
mutate
gograph mutate <field|Type.Field>
Finds struct-field and package-global mutations. Type.Field filters same-named fields on unrelated types, and ordinary local assignments are excluded. An explicit precise build adds ++/+=, pointer-alias, atomic/sync/wrapper, and channel mutations.
arity
gograph arity [--min N]
Finds functions with excessive parameter counts. Defaults to --min 5.
Federated Workspaces
A regular .gograph-workspace.yml establishes a workspace root. Every member
must be a unique relative descendant without symlink traversal. Each member’s
.gograph/graph.json remains authoritative and independently fingerprinted;
the deterministic .gograph/workspace.json contains only scoped
cross-repository ownership, resolution, and HTTP-contract facts.
gograph workspace --help lists the complete command family and prints a
minimal valid manifest. Repository-local go.work sibling-module authority
inside a Git checkout does not widen this manifest’s member-path boundary.
workspace build
Members can specify exclude_dirs: [legacy, examples/broken] in the manifest.
Paths are relative to each member, and affect its fingerprint, refresh, and
CLI/MCP status/query validation. Use matching flags for independently built
member graphs; workspace refreshes apply the manifest list automatically.
gograph workspace build [path] [--refresh-members] [--tags=integration[,tag...]] [--memory-mode=low] [--max-memory=1GiB] [--json]
Without --refresh-members, reads member graphs and writes only the workspace
overlay. Missing, stale, incomplete, incompatible, or insufficiently precise
members fail the build without replacing the previous overlay.
--refresh-members explicitly permits sequential writes in member repositories
and is not transactional. Its JSON reports refresh_plan,
refresh_attempted, refresh_succeeded, and refresh_failed, including
before/after artifact fingerprints, so a failure after earlier successful
member writes is visible.
When member refresh is enabled, the repository build memory options apply
sequentially to every refreshed member with the same soft-limit semantics.
--tags selects the same member build context for validation and every
explicit refresh. Use the same tag selection for subsequent workspace status,
query, path, impact, and MCP startup; a different selection is correctly
reported as stale rather than silently mixing graphs.
workspace status
gograph workspace status [path] [--tags=integration[,tag...]] [--json]
Reports complete, partial, or cannot_evaluate, with each member’s
availability, freshness, exact artifact/source/build-context fingerprints,
analysis mode, capabilities (including independent
test_call_resolution), advisory repository revision/dirty state, and
diagnostics. Overlay status includes presence, freshness, input fingerprint,
external exact-byte artifact fingerprint, resolver versions, and diagnostics.
The advisory Git probes disable repository-configured filesystem monitors and
optional index locking.
workspace query
gograph workspace query [--scope id] [--workspace path] [--tags=integration[,tag...]] <term...> [--json]
Searches symbols, packages, modules, first-class HTTP contracts, and unresolved
HTTP diagnostics in the
selected scope. repository:symbol is presentation/query syntax only;
persisted identities are structured.
Member http_clients configuration can map a lexical base to a logical service:
http_clients:
- base: cfg.APIURL
authority_id: api-service
path_prefix: /v1
- base: env:API_URL
authority_id: api-service
This maps cfg.APIURL + "/items" to /v1/items at api-service when that
service belongs to the selected scope. env:API_URL names source evidence,
not a value read from the running environment. Bases must be unique per member;
prefixes cannot contain an authority, query, fragment, or dot segments.
Unbounded URLs and missing mappings/owners remain in the query’s filtered
http_unresolved array, never as traversable edges. Verified workspace status
reports overlay.http_unresolved_by_scope counts without marking the graph
stale solely because some calls remain unresolved. CLI and MCP share these fields.
Request construction is only possible evidence; exact traversal excludes it.
After upgrading, rebuild member graphs and the overlay for net_http_v2 facts
and the http-contract-v2 resolver.
workspace path
gograph workspace path [--scope id] [--workspace path] [--tags=integration[,tag...]] [--include-possible] <from> <to> [--json]
Finds the best path over the selected member graphs plus the workspace overlay.
Competing paths rank exact before ambiguous before possible, then shorter,
production before tests, typed resolution before heuristics, and fewer
cross-repository transitions when otherwise equivalent. A canonical final
tie-breaker makes results independent of edge iteration order. Cross-repository
Go resolutions materialize as ordinary calls; HTTP clients and handlers
connect through a contract as calls_http then serves_http.
workspace impact
gograph workspace impact [--scope id] [--workspace path] [--tags=integration[,tag...]] [--include-possible] <target> [--json]
Finds transitive incoming dependencies in the same virtual graph. Path and
impact traverse only exact evidence by default. --include-possible opts
into both ambiguous and possible evidence for exploration.
workspace mcp
gograph workspace mcp [path] [--tags=integration[,tag...]]
Starts a separate read-only workspace MCP server with exactly four tools:
gograph_workspace_status, gograph_workspace_query,
gograph_workspace_path, and gograph_workspace_impact. For each operation,
the MCP JSON text is exactly the native value placed in the CLI --json
envelope’s results field, including scope selection, ordering, and traversal
semantics. MCP cannot refresh member graphs or publish the overlay.
Multiple scopes require --scope unless the manifest defines default_scope
or contains exactly one scope. Duplicate module or logical HTTP ownership is
an error within a scope unless shared HTTP ownership is explicit; duplicates
in mutually exclusive scopes are allowed. Workspace changes, snapshots, RPC,
topics, and shared-schema resolution are outside workspace v1.
CLI / MCP Transport Matrix
Every repository query, analysis, and workflow capability has a project-MCP
equivalent. The standard mapping is CLI <command> to MCP
gograph_<command>. The complete shipped inventory is listed here so neither
transport has an undocumented analytical feature.
| Capability group | CLI ↔ project MCP |
|---|---|
| Core | capabilities ↔ gograph_capabilities; stale ↔ gograph_stale; stats ↔ gograph_stats |
| Search/navigation | query ↔ gograph_query; strings ↔ gograph_strings; focus ↔ gograph_focus; node ↔ gograph_node; source ↔ gograph_source; public ↔ gograph_public |
| Calls/reachability | callers ↔ gograph_callers; callees ↔ gograph_callees; impact ↔ gograph_impact; path ↔ gograph_path; orphans ↔ gograph_orphans |
| Types/tests | implementers ↔ gograph_implementers; interfaces ↔ gograph_interfaces; fields ↔ gograph_fields; embeds ↔ gograph_embeds; constructors ↔ gograph_constructors; literals ↔ gograph_literals; usages ↔ gograph_usages; returnusage ↔ gograph_returnusage; schema ↔ gograph_schema; globals ↔ gograph_globals; mocks ↔ gograph_mocks; fixtures ↔ gograph_fixtures; identity ↔ gograph_identity |
| Packages/changes | imports ↔ gograph_imports; deps ↔ gograph_deps; dependents ↔ gograph_dependents; changes ↔ gograph_changes |
| Extraction | routes ↔ gograph_routes; sql ↔ gograph_sql; errors ↔ gograph_errors; envs ↔ gograph_envs; concurrency ↔ gograph_concurrency; httpcalls ↔ gograph_httpcalls; flow ↔ gograph_flow; tests ↔ gograph_tests; coverage ↔ gograph_coverage; uncovered ↔ gograph_uncovered |
| Composed workflows | explore ↔ gograph_explore; context ↔ gograph_context; plan ↔ gograph_plan; review ↔ gograph_review; risk ↔ gograph_risk; errorflow ↔ gograph_errorflow; trace ↔ gograph_trace; endpoint ↔ gograph_endpoint; explain ↔ gograph_explain; summary ↔ gograph_summary; untested ↔ gograph_untested |
| Quality/policy | api/contract ↔ gograph_api; boundaries ↔ gograph_boundaries; boundaries --create ↔ gograph_boundaries_create; check ↔ gograph_check; complexity ↔ gograph_complexity; coupling ↔ gograph_coupling; diagram ↔ gograph_diagram; hotspot ↔ gograph_hotspot; godobj ↔ gograph_godobj; skeleton ↔ gograph_skeleton; mutate ↔ gograph_mutate; arity ↔ gograph_arity |
| Documentation/toolchain | wiki ↔ gograph_wiki; doc ↔ gograph_doc |
| Session lifecycle | session create ↔ gograph_session_create; session end ↔ gograph_session_end; session audit ↔ gograph_session_audit; session cleanup ↔ gograph_session_cleanup |
That is 66 CLI-equivalent project capabilities plus four session tools: 70
tools on gograph mcp. The separate gograph workspace mcp server adds these
four exact pairs:
| Workspace CLI | Workspace MCP |
|---|---|
workspace status |
gograph_workspace_status |
workspace query |
gograph_workspace_query |
workspace path |
gograph_workspace_path |
workspace impact |
gograph_workspace_impact |
The only CLI operations without callable MCP equivalents are process-, host-,
CI-, or artifact-lifecycle operations: build, validate, doctor, gate,
snapshot, add-claude-plugin, hook-guard, hook, project/workspace MCP
startup, workspace build/member refresh, and help. The standalone version command
has no dedicated MCP tool, but gograph_capabilities exposes the running server
version. CLI flags/envelopes and typed MCP arguments/content are transport-specific; paired operations share
their functional implementation and documented filters, ordering, evidence,
and result semantics.
Agent Integration
doctor
gograph doctor [--json]
Inspects the running executable and every distinct gograph executable found
on PATH. It reports duplicate installations, a running/PATH mismatch, and
older stable binaries when versions are safely comparable. Alternate binaries
are read through Go build metadata and are never executed. --json emits the
versioned gograph.doctor.v1 document. When run inside a Go repository it also
reports graph availability/freshness, analysis mode, AST/precision/call
resolution capabilities, artifact fingerprint, and the exact freshness or
build-context diagnostic. Development, dirty, and prerelease builds are not
ordered against stable releases. Doctor remains intentionally CLI-only because
it diagnoses the host process and installation selected before MCP startup.
capabilities
gograph capabilities
Prints the token-optimized AI agent cheat sheet detailing common workflows and
commands. It starts with a task index that maps jobs (such as “choose which
tests to run for a change”) to commands; gograph help starts with the same
index. The MCP counterpart returns it as structured task_index rows. The MCP counterpart, gograph_capabilities, also includes a top-level
version identifying the running server binary, so MCP-only clients can record
the analysis instrument. Useful for bootstrapping context in an LLM system prompt.
mcp
Use the same --exclude-dirs selection as the repository build. Startup,
refreshes, and baselines retain it; capabilities exposes
analysis_build_context.exclude_dirs. This is a startup option, not a per-tool
argument. Restart the server after changing it.
gograph mcp [path] [--persist-refresh] [--tags=integration[,tag...]] [--exclude-dirs=dir1,dir2] [--memory-mode=low] [--max-memory=1GiB] [--max-scopes=4] [--scope-idle-ttl=10m]
Starts a Model Context Protocol (MCP) server over stdio, exposing gograph’s
query, analysis, and workflow capabilities as native tools for integration with
AI clients (e.g., Claude Code, Cursor).
- Checkout selection: Every tool accepts
root(aliascwd): the absolute path of the caller’s checkout. It must bepathor one of itsgit worktree listentries (a subdirectory selects its checkout) and is answered from that checkout’s own graph. Without it, the client’s MCP roots are used when the client declares them (a root that merely contains the repository is ignored); otherwisepathanswers. A path outside the repository and its worktrees is refused, naming the indexed and the asked root. Results carry_meta.gograph_scope. - Load limits: Startup loads no graph and starts no background work; a
checkout’s graph loads on its first request.
--max-scopes(1-64, default 4) bounds the checkouts held in memory and--scope-idle-ttl(at least 1s, default 10m) drops an idle one when a request needs an unloaded checkout (no background timer).gitchild processes run withoutGIT_DIR,GIT_WORK_TREE,GIT_COMMON_DIRand the other repository-selectingGIT_*variables, and a listed worktree must share the configured repository’s git common directory. A checkout with a running request is never dropped; when all slots are busy a new checkout is refused. - Freshness: If
graph.jsonis missing, unreadable, linked through a descendant path, or has a missing/unsupported source-policy marker, startup builds a safe in-memory AST graph. Source-analysis tools compare selected source digests plus the build/module fingerprint and newer persisted artifacts per call, then reparse changed packages while reusing unchanged package AST records. Refresh-backed results attach per-request_meta.gograph_graph_state. Each answer is sent once, as compact JSON text withoutstructuredContent: bounded row lists use nativegograph.results.v1, and explain/changes retain their own native schemas. The nestedgograph.graph-state.v1independently reports persisted/in-memory source, current/stale freshness, complete/partial parsing, AST/precise/fallback analysis, refresh outcome, and persistence outcome; each operation owns its bounded diagnostic. Failed precise enrichment can serve a marked current in-memory fallback; an ordinary refresh failure can serve the last trusted stale graph. Degraded states are not silently published. MCPstale, defaultchanges, andstatsinspect the trusted persisted snapshot, or the startup in-memory fallback when no usable artifact exists, and attach the exact state they inspect. - Build tags:
--tagsuses the same validated selection and precedence as CLIbuild. Startup analysis, incremental AST rebuilds, precise refreshes, temporary Git baselines, and optional artifact publication all retain that selection.gograph_capabilities.analysis_build_contextreports requested and effective tags. - Environment binding: A persisted graph is valid only under its recorded
effective source/build selection. Start MCP with the same
GOWORK,GOFLAGS, and explicit--tags; a mismatch is stale and must refresh successfully or return a diagnostic rather than serving incompatible facts; stale-on-error never bypasses this boundary.gograph doctor --jsonreports the same diagnostic before server startup. - Persistence: Refreshes remain in memory by default.
--persist-refreshwrites or overwrites.gograph/graph.jsonand the nine Markdown reports only after a successful, confirmed-fresh refresh. It does not update.gitignoreand keeps one latest state rather than a per-branch cache. A publication failure during startup auto-build prevents the server from starting. A later publication failure serves the fresh in-memory result withpersistence.outcome=failedand is retried on another refresh-capable call without rebuilding. Writers wait up to 30 seconds on.gograph/.artifacts.lock. Reports are renamed first andgraph.jsonlast as the commit marker. Same-directory replacement is atomic on Unix-like systems but is not guaranteed atomic by Go on non-Unix platforms; the complete bundle is not one atomic transaction, and the lock file remains as separate operational state. - Memory policy:
--memory-mode=lowand--max-memoryapply the same correctness-preserving runtime policy to startup analysis and every later MCP refresh.gograph_capabilitiesreports the requested and effective byte targets plus the soft-limit caveat. - Changes baseline: Default
gograph_changescompares against persistedgraph.json. Successful refresh publication advances that baseline, so usegit_refwhen the comparison must remain anchored to a Git revision. - Mermaid: Set
mermaid: trueongograph_callers,gograph_callees,gograph_impact,gograph_endpoint,gograph_dependents,gograph_deps,gograph_path, orgograph_coupling. The tool returns Mermaid flowchart text instead of its normal response. - Parity: 66 query, analysis, and workflow commands have corresponding MCP
endpoints; four additional endpoints manage sessions (70 endpoints total).
MCP uses typed tool arguments rather than CLI global flags, and some
not-found and status results have different transport-level presentation.
gograph_exploreand CLIexplore --jsonshare the nativegograph.explore.v1value; only the CLI adds its generic envelope. - Audit telemetry: Each request accepts
session_idandintention. Selected analytical owner calls require a rationale and record command, duration, status, and intention; arguments and query results stay omitted. Omission never inherits another caller’s session or the server environment. Independent read-only calls leave audit files byte-identical. Mutating calls, including opt-in persisted refresh, refuse while another owner is active. Read-only annotations describe functional analysis with this explicitly selected local audit telemetry as an observational exception.
wiki
gograph wiki [--output dir]
Generates machine-first llm-wiki/ pages from the graph. A relative output is
rooted at the analyzed project and may not traverse or follow a linked
descendant; an absolute output explicitly selects another local root. The
selected output must be a real directory. Generated directories and regular
page writes are confined beneath it, links/special entries are refused, and
existing regular pages may be overwritten. After successful generation,
obsolete packages/*.md files are removed only when they carry Gograph’s
generated package-page signature. Custom files, packages/README.md, links,
special entries, and oversized unknown pages are preserved.
doc
gograph doc <pkg[.Symbol]>
Runs go doc with the user’s Go environment. In workspace-auto mode the
working-tree preflight starts at the nearest enclosing workspace; otherwise it
starts at the nearest enabled module (or project/start fallback), while an
explicit GOWORK selection is validated separately. No graph is required. Gograph
rejects absolute/relative filesystem-shaped queries and flags, then refuses
go doc when source-tree links cmd/go may inspect exist across the selected
root plus its effective module root, or the workspace root and member trees;
.git and .gograph are excluded from that walk. It also refuses when
go.mod, go.sum, go.work, go.work.sum, vendor/modules.txt, or a
recognized Go build input is non-regular. Applicable go.work members may be
sibling modules beneath the nearest real Git checkout; without that boundary
they remain confined beneath the workspace directory. Each directory,
go.mod, and optional go.sum is validated first. Unrelated non-Go
regular-file or dangling links do not block the Go-tool preflight.
Package/symbol queries such as fmt.Errorf,
net/http.HandleFunc, and github.com/jackc/pgx/v5.Conn.QueryRow remain valid.
The local Go toolchain and dependency resolution follow the user’s
module/cache/network policy and are therefore open-world.
The MCP gograph_doc response is a one-element JSON array containing
{"query": "...", "output": "..."}; output holds the raw go doc text.
The handler itself does not query the graph, but the project-scoped MCP server
must already have started with a usable artifact or buildable Go source.
session
gograph session create [word] [-i "<task>"]
gograph session end [session_id]
gograph session audit [session_id|word]
gograph session cleanup
create -i "<task>" records a default intention: calls in that session without
-i use it instead of failing. audit <word> grades every session created with
that word together (plan in one session, review in another).
Manages local workflow metadata under .gograph/sessions/. Session IDs contain
only letters, digits, and underscores. The .gograph/sessions directories must
be real, and markers/logs must be regular non-linked entries. Audit reads and
cleanup are confined to the project; cleanup removes only validated inactive
regular logs with an end record. Each created session has an independent active
marker and random suffix, so equal labels and simultaneous creation do not share
a pointer. Owners keep the existing scoring rules. A CLI command without
--session-id/GOGRAPH_SESSION uses the repository’s only active session
when this host’s CLI created it; with several sessions, or a session that is
MCP-owned, from another host, or without owner metadata, an unselected caller
cannot end a session and must name it (session end ID). Abandoned sessions also expire
automatically: every CLI command and MCP call first ends other callers’ CLI
sessions idle past GOGRAPH_SESSION_IDLE_LIMIT (a Go duration, default 2h;
0 or off disables) and sessions of exited MCP servers, naming each on
stderr. Refused calls are not activity, and a call’s own selected session is
never ended. Markers hold only the session ID; a session_<id>.meta.json
sidecar records the owner (cli or mcp), process ID, host, working directory
and creation time. Cleanup never deletes: it moves files into
.gograph/_to_delete/<UTC time>_<suffix>/. It first ends and archives other
callers’ CLI-owned sessions idle past GOGRAPH_SESSION_IDLE_LIMIT (default 2h) or MCP-owned sessions of an
exited server process on this host (sessions without owner metadata, or owned
on another host, are kept), printing each, and archives an unselected legacy
pointer; it then refuses while another owner is still live. A legacy pointer never blocks other callers;
explicitly select older pointer-based sessions by their printed ID to finish
them. The project root is the nearest directory with .git or go.mod; an
ancestor .gograph above it is never used. Unset the CLI
environment selector after ending. Selectors are cooperative attribution, not
credentials. Unsafe selected markers fail closed; independent readers never
inspect another owner’s session metadata. Raw query results are not logged.
add-claude-plugin
gograph add-claude-plugin
Registers Claude Desktop MCP configuration, injects shared ~/.claude/CLAUDE.md rules, and registers gograph hook --agent claude in ~/.claude/settings.json for the Bash tool (and drops it from any other tool group). It removes the entry of the former ~/.claude/hooks/gograph-guard.sh (a gograph hook-guard wrapper) and deletes that script when it is unchanged. Claude Code MCP registration still requires the claude mcp add command printed by the installer. Partial installation exits non-zero.
hook
gograph hook [--agent claude|codex|opencode|agy] [--deny-go-writes] [--require-session] [--record DIR] [--selftest DIR]
PreToolUse hook that steers Go navigation to gograph, the same way for every agent: Claude Code (claude, the default), Codex (codex), opencode (opencode) and Antigravity (agy). Each agent’s tool-call JSON is read into one event (shell, edit, write, multi_edit, patch, read, other); one shared rule set decides; the verdict is written in the agent’s format. Inside a repository with a .gograph index it denies Go symbol searches (a declaration head or call site even with a reason), region reads of .go files and Go text searches without a # gograph-cannot: <reason> comment (a reason allows both). Commands hidden behind loops, sh -c, eval, xargs, find -exec, a shell heredoc or a python/perl/ruby shell call are judged too; a search with no path over the output of a command that does not print Go source is allowed. Editing is checked only on request: --deny-go-writes denies text tools editing .go files (sed -i, perl -i, awk -i inplace, redirects or tee fed by a text tool; moves, copies and program output such as go run ./gen > x.go are allowed; a # gograph-cannot: <reason> comment allows; the denial points at the agent’s own edit tool), and --require-session denies edits, writes, multi-edits and patches of .go files while no gograph session is open (every path of a Codex/opencode apply_patch is checked). A shell call whose input cannot be read is denied, and under an editing rule so is an unreadable write call or a malformed patch; an unknown read-only tool is allowed. An unknown --agent exits 2.
Output: claude allows with exit 0 and no output (Claude Code’s own permission rules still apply) and denies with a hookSpecificOutput.permissionDecision of deny; codex denies with exit 2 and the reason on stderr; opencode and agy get {"decision":"allow"} or {"decision":"deny","reason":...} on stdout. Until an agent’s input format is backed by recorded fixtures, every denial says no fixture-backed format for <agent>. --record DIR writes the raw input to DIR/<agent>-<time>.json (directory 0700, file 0600, strings cut to 4 KiB) and allows the call. --selftest DIR replays DIR/verdicts.tsv (<agent>/<file>, allow|deny, optional reason text) with the given rules and fails on a mismatch or a fixture without a row. gograph hook --help prints the registration for each agent, including a minimal opencode plugin. Never logged to session telemetry.
hook-guard
gograph hook-guard [--deny-go-writes] [--deny-region-reads] [--require-reason] [--require-session] [--strict] [--ask]
PreToolUse hook for Claude Code, Codex and Antigravity; the payload format is detected. Claude Code and Codex receive exit 2 with the reason on stderr; Antigravity receives {"decision":"allow"|"deny"} on stdout. Opt-in rules, applied only inside indexed repositories: --deny-go-writes (text tools editing .go files: sed -i, perl -i, awk -i inplace, redirects or tee fed by a text tool; moves, copies and program output are allowed; a # gograph-cannot: <reason> comment allows), --deny-region-reads (cat/head/sed/… of .go files; counts, checksums, git show/git diff and commands with a # gograph-cannot: <reason> comment stay allowed; not applied to Codex), --require-reason (Go text searches need a # gograph-cannot: <reason> comment), --require-session (.go edits need an open gograph session); --strict enables all four. --ask asks the user instead of denying in Claude Code and Antigravity; Codex still denies.
Called by the Claude Code PreToolUse hook. Intercepts incoming tool-call JSON over stdin; resolves effective search paths against the payload’s cwd; and blocks likely grep/rg Go-symbol searches with exit code 2 only when at least one target has a real .gograph ancestor. An omitted cwd falls back to the hook process working directory. Unindexed, non-Go, and comment-only searches are allowed. Identifier-only alternations are recognized according to grep/ripgrep regex mode; literal-pipe patterns in fixed-string mode and escaped pipes in extended grep/ripgrep remain allowed.
version and help
gograph version
gograph help
Print the build version or the complete CLI help contract. Help starts with the
task index. Builds from go install ...@vX.Y.Z report X.Y.Z; local checkout
builds report dev+<revision> (.dirty when modified).
Output Modes
Query/composed commands, check, and workspace build/status/query/path/impact
support --json using the envelope keys
schema_version, command, status, query, count, and results.
Successful envelopes always include numeric count; collection-shaped empty
results are [], not null. Hard failures use status: "error" and exit 1.
check also exits 1 when its structured report has failed policy findings.
session audit --json is the deliberate raw-JSON exception.
--files-only is supported by query, focus, node, public, fields,
embeds, imports, callers, callees, impact, implementers, envs,
interfaces, concurrency, tests, routes, sql, errors, flow,
orphans, mutate, constructors, literals, usages, returnusage,
schema, globals, mocks, fixtures, boundaries, httpcalls, and
dependents. An empty files-only result writes zero lines. --mermaid is supported by
callers, callees, impact, endpoint, dependents, deps, path, and
coupling; bare gograph --mermaid renders diagram. Unsupported or
conflicting output flags fail. Other operational commands (repository build,
wiki, gate, snapshot, session create/end/cleanup, installation, help, and
version) remain text. Use global
--intention / -i to provide the rationale required by analytical CLI
commands during an active audit session.
Successful-result mode support is:
| Modes | Commands |
|---|---|
| JSON, files, Mermaid | callers, callees, impact, dependents |
| JSON, files | query, focus, node, public, fields, embeds, imports, implementers, envs, interfaces, concurrency, tests, routes, sql, errors, flow, orphans, mutate, constructors, literals, usages, returnusage, schema, globals, mocks, fixtures, boundaries, httpcalls, strings |
| JSON, Mermaid | path, coupling, deps, endpoint |
| JSON | source, errorflow, trace, stale, stats, summary, untested, doc, doctor, godobj, skeleton, arity, complexity, context, hotspot, changes, explain, plan, review, risk, api, check |
| JSON | workspace build, workspace status, workspace query, workspace path, workspace impact |
| Raw JSON | session audit |
| Mermaid | diagram, or bare gograph --mermaid |
For commands with several supported presentations, request only one output mode at a time.