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 and composed-analysis commands.--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 audit session is active; session, MCP startup, build, installation, help, version, stale, stats, capabilities, wiki, and doc commands do not require it.
Request only one of --json, --files-only, or --mermaid; unsupported or
conflicting output flags fail instead of being silently ignored.
Indexing & Core Commands
build
gograph build [path] [--precise]
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. Descendant symlinks and special files for extensions recognized by go/build are reported and excluded, while an explicitly symlinked repository root remains supported. 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 must remain beneath the workspace directory; their 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.
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:
--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 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.- 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.
stale
gograph stale [--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.
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.
- Output fields:
schema_versiongenerated_atprecision(ast,precise, orprecise_fallback)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
Search & Navigation
query
gograph query <term...>
Performs a broad, case-insensitive substring search across multiple entities.
- Scans: Symbol names, file paths, package names, import paths, and call sites.
- 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.
- Output fields: Kind, file, line, signature, comments/docstrings, and struct fields.
source
gograph source <name>
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 may return its safely readable matches; the
command errors when no matching block can be read safely.
- 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.
- 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.
path
gograph path <from> <to> [--json|--mermaid]
Calculates and prints the shortest call chain (BFS path) between two symbols, verifying reachability.
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).
- 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*).
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, or interface methods. Essential for tracing the impact of a type change.
schema
gograph schema <table>
Finds structs mapped to a database table or schema via struct tags (e.g. db:"...", gorm:"...").
globals
gograph globals <pkg>
Finds all package-level variables and constants, as well as functions that mutate them.
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 and reports new, modified, and deleted symbols. DELETED means the
recorded file is absent from the current safely selected inventory: it may be
gone, ignored, inactive under the effective build context, or unsafe to read.
Git-ref mode reports symbols in changed files relative to the ref; full
NEW/DELETED classification requires a baseline graph comparison.
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
Extracts HTTP REST API routes from Gin, Chi, Echo, Fiber, and net/http-style
registration calls. 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.
sql
gograph sql [term]
Extracts and maps raw SQL string queries to the functions that execute them. The optional term filters by SQL keyword or table-name substring.
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]
Maps goroutine spawns (go func), channel sends, and calls on mutex/RWMutex,
WaitGroup, and sync.Once. Channel receives and select statements are not
indexed.
httpcalls
gograph httpcalls [term]
Lists package-level net/http client calls (Get, Post, PostForm, Head). The optional filter matches method, URL, or function context.
flow
gograph flow [term] [--source http_request|decoded_json|environment] [--sink sql_query|process_execution|filesystem|outbound_http] [--config path] [--no-tests]
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, 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.process_execution: command and argument values passed toos/exec.CommandorCommandContext.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.jsonwhen present.--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; use the fully-qualified form for duplicate names. Validators that only returnboolorerrordo not sanitize the original value. -
Limitations: Interprocedural and path-insensitive, with call/return matching across at most 16 nested repository calls. 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]
Lists attributed test edges, optionally filtered to one symbol. This is static attribution, not runtime coverage.
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.
review
gograph review <symbol>
gograph review --uncommitted
Performs post-edit verification.
- 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]
Ranks called production functions that have no attributed test edge. This is distinct from unreachable-code detection and from runtime coverage.
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). 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.
complexity
gograph complexity [symbol]
Displays McCabe cyclomatic complexity for all functions, sorted highest first. Optional substring filter by symbol name.
- 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 [--json]
Outputs the entire repository’s API signatures with their function/method bodies stripped. Useful for full structural orientation.
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.
Agent Integration
capabilities
gograph capabilities
Prints the token-optimized AI agent cheat sheet detailing common workflows and commands. Useful for bootstrapping context in an LLM system prompt.
mcp
gograph mcp [path] [--persist-refresh]
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).
- 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. MCPstale, defaultchanges, andstatsinspect the trusted persisted snapshot, or the startup in-memory fallback when no usable artifact exists. Precise and precise-fallback sessions still re-run repository-wide CHA/SSA, and a failed precise refresh is returned visibly. - 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 tool-triggered failure makes that tool fail and is retried on another refresh-capable call without rebuilding the fresh in-memory graph. 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. - 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: 61 query, analysis, and workflow commands have corresponding MCP endpoints; four additional endpoints manage sessions (65 endpoints total). MCP uses typed tool arguments rather than CLI global flags, and some not-found and status results have different transport-level presentation.
- Audit telemetry: Read-only annotations describe the functional analysis
contract. While an audit session is active, non-session MCP calls append
local command/status telemetry without arguments or query results.
MCP has no
intentiontool parameter and does not enforce the CLI session requirement, so those records use an empty intention.
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.
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 workspace members must
remain beneath the workspace directory, with each directory, go.mod, and
optional go.sum validated first.
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]
gograph session end
gograph session audit [session_id]
gograph session cleanup
Manages local workflow metadata under .gograph/sessions/. Session IDs contain
only letters, digits, and underscores. The .gograph/sessions directories must
be real, and pointers/logs must be regular non-linked entries. Audit reads and
cleanup are confined to the project; cleanup removes only validated inactive
regular logs. CLI analytical commands fail closed when active-pointer metadata
is unsafe or corrupt. 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 installs ~/.claude/hooks/gograph-guard.sh. Claude Code MCP registration still requires the claude mcp add command printed by the installer. Partial installation exits non-zero.
hook-guard
gograph hook-guard
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.
Output Modes
Query/composed commands and check 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. Operational commands (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 |
| JSON, Mermaid | path, coupling, deps, endpoint |
| JSON | source, errorflow, trace, stale, stats, summary, untested, doc, godobj, skeleton, arity, complexity, context, hotspot, changes, explain, plan, review, risk, api, check |
| Raw JSON | session audit |
| Mermaid | diagram, or bare gograph --mermaid |
For commands with several supported presentations, request only one output mode at a time.