Skip to main content

Code graph

The code graph indexes the Python, TypeScript, Java, Go and C# repositories you connect and serves them to coding agents as the spanway_code MCP server. Agents can find a symbol, read it with its parent and members, outline a file and walk callers and callees instead of reading whole files. It is an enterprise feature and needs a license that lists code_graph.

The index lives in a codegraph schema in a Postgres database you choose, which can be the gateway's own. The gateway never builds or runs your code. It reads repository files through the provider's REST API, parses them in a separate sandboxed process and stores what it finds.

A real-world scenario​

A payments team uses a coding agent on a 400,000 line repository, and the agent burns most of its context reading whole files to find one function. The platform admin connects the repository to the code graph and grants the team's keys the spanway_code MCP server. The agent now asks for a symbol, its callers and its callees, and reads only those lines.

Steps​

  1. Set SPANWAY_CODE_GRAPH_DATABASE_URL and restart the gateway, as shown in Set up the database.

  2. Store a read-only GitHub token as a credential, then bind it to the organization. In the Admin UI open Code Graph under Tools and click Bind credential. With the API:

    curl -X POST "$SPANWAY_URL/code_graph/credentials/bind" \
    -H "Authorization: Bearer $SPANWAY_ADMIN_KEY" -H "Content-Type: application/json" \
    -d '{"tenant_id": "default", "credential_name": "repo-indexer"}'
  3. Click Connect repository, fill in Repository, GitHub repository id, Branch to index, Your GitHub MCP server and Credential, and click Connect. The API call is the curl in Connect a repository.

  4. Copy the payload URL and secret from the Repository webhook dialog into the repository's webhook settings with the push event, then click Done.

  5. Click Runs on the repository row to follow the first index run, or list the runs with the API.

    curl "$SPANWAY_URL/code_graph/repos/$REPO_ID/runs" -H "Authorization: Bearer $SPANWAY_ADMIN_KEY"
  6. Add spanway_code to the mcp_servers grant of the agent's key, see MCP access control.

Expected result​

A toast reads "Connected ..., the first index run is queued". The run moves from queued to running to succeeded with a commit and a file count, and the agent's MCP tool list includes the read-only spanway_code tools.

What agents can call​

spanway_code is registered like any other MCP server, so a key needs it in its mcp_servers grant to see its tools, and per-key mcp_tool_permissions, server-level allowed and disallowed tools and MCP guardrails apply to it the same way. Every tool is read-only.

ToolWhat it returns
list_reposThe repositories the key may read.
get_index_statusHow fresh the index of one repository is.
get_repo_mapDirectories with file and symbol counts.
search_codeSymbols matching a query, by identifier words (mode: lexical, the default), by qualified name prefix (mode: symbol) or by both at once (mode: hybrid).
get_symbolOne symbol with its source, parent and members, by symbol id or by path and line.
get_fileUp to 400 lines of a file.
get_file_outlineThe classes, functions and methods of one file.
find_callersSymbols that call, import, instantiate or inherit from a symbol, up to five hops.
find_calleesSymbols a symbol calls, imports, instantiates or inherits from, up to five hops.

With mode: hybrid, search_code runs the full-text search and the name prefix search and merges them with reciprocal rank fusion, so a symbol that both find ranks above one that only one finds. It is the easiest choice when an agent does not know whether the query is a word from the code or the start of a qualified name. Search covers symbol names and identifiers only. Function bodies and comments are not embedded, so there is no vector search over code text.

Every result except list_repos carries a freshness block. ready means the result comes from the latest finished index, and stale means a newer index is being built and you are reading the previous one. indexing means the first index is still running, and tools return no symbols, files or edges until it finishes. unindexed means no index run has finished for the repository yet and none is running, for example right after a failed first run, so queue a reindex. The index only knows committed code on the default branch, so agents should keep reading local files for paths they have edited.

Tool arguments​

Every tool except list_repos takes repo, the repository's full_name or id, which can be left out when the key can read exactly one repository, and ref, which defaults to the default branch and is the only ref indexed. max_tokens caps the size of each answer. A result cut short says truncated: true and gives a next_cursor to pass as cursor for the next page.

ToolArguments, with defaults and limits
list_reposquery (optional, up to 256 characters, filters by name), max_tokens 800 (100 to 4000).
get_index_statusrepo, ref, max_tokens 600 (100 to 2000).
get_repo_maprepo, ref, path (empty for the root), depth 2 (1 to 4), max_tokens 1500 (200 to 6000).
search_codequery (required, up to 512 characters), mode lexical, symbol or hybrid (default lexical), path_prefix, language (python, typescript, tsx, java, go or csharp), kinds (up to six of module, class, interface, function, method, type), limit 10 (1 to 50), cursor, max_tokens 1500 (200 to 8000).
get_symbolEither symbol (a symbol id) or both path and line, include body, signature_only or members (default body), max_lines 200 (1 to 400), max_tokens 3000 (200 to 12000).
get_filepath (required), start_line 1, end_line (optional, at most 400 lines after start_line), max_tokens 4000 (200 to 16000).
get_file_outlinepath (required), max_tokens 1500 (200 to 6000).
find_callers, find_calleessymbol (required), depth 1 (1 to 5 hops), edge_kinds (one to four of call, instantiate, import, inherit, default call), min_confidence (default name_unique), cursor, max_tokens 2000 (200 to 8000).

Each edge in the call graph has a confidence. import_resolved and scope_resolved edges were bound through an import or the enclosing scope, name_unique edges matched the only definition with that name, and name_ambiguous edges are one of up to five same-named candidates. Pass min_confidence to drop the weaker ones.

Who can read a repository​

A call only sees repositories in the caller's tenant, which is the key's organization, or default for keys without one. Within the tenant a repository is visible when

  • the caller is a proxy admin, or
  • the key's team owns the repository or lists it in the team's object_permission.code_repos, or
  • a key without a team lists it in its own object_permission.code_repos.

A key on a team that lists repositories in its own code_repos only sees the ones its team also grants. Only proxy admins can put code_repos on a personal key, and a team key can only carry repositories its team already lists. Only proxy admins can add repositories to a team's code_repos. A team admin can save the team with the same list or a shorter one, but not add to it.

In the Admin UI, the Code repositories picker sits under Code Graph Settings when you create a team or key, and next to the other permissions when you edit one. It lists the repositories connected in that team's or key's organization by name, and the object permissions card on a team or key shows which ones are granted.

An unknown repository and a repository the key may not read return the same error, so the response never reveals which repositories exist.

A repository whose upstream access was lost, because the GitHub App was uninstalled, the repository was removed from the installation or the provider answered 401, 403 or 404, is hidden from every caller until a reindex succeeds again.

Mirror upstream permissions​

Permission mirroring keeps the code graph from showing code to people the source host itself would not show it to. It is off by default, and then anyone granted the repository through a team or key sees it. Turn it on for a repository to also require that the caller's own GitHub or GitLab identity can read it. The side effect is that callers who have not signed in to the named MCP server, and everyone while the host is unreachable, stop seeing the repository, so turn it on for repositories with stricter access upstream than in the gateway. A proxy admin, a holder of code_graph.manage or the admin of the owning team can change it. The identity comes from the per-user OAuth sign-in of a GitHub or GitLab MCP server you name, and that server's token URL must belong to the same host the repository is indexed from. A caller who has not signed in to that server, or a key with no user, does not see the repository. Access is checked against the repository's numeric id, so a repository renamed upstream stays visible to the people who can read it. Answers are cached in memory for five minutes when access is allowed and for one minute when it is refused. An upstream outage hides the repository rather than showing it.

curl -X POST "$SPANWAY_URL/code_graph/repos/$REPO_ID/settings" \
-H "Authorization: Bearer $SPANWAY_ADMIN_KEY" \
-H "Content-Type: application/json" \
-d '{"mirror_source_permissions": true, "acl_server_id": "source-mcp"}'

What is logged​

Tool calls appear in spend logs, Lens traces and logging callbacks like any other MCP call, with the tool name and its arguments. The result of a spanway_code tool call is replaced with a placeholder before any logging callback sees it, whatever store_prompts_in_spend_logs says. That holds for calls made on the MCP endpoint and for tools the gateway runs itself for a /v1/responses request. MCP guardrails still see and can rewrite the real result before it is returned.

Once an agent has the result, it usually sends it back to a model in its next request. When that request goes through the gateway, its messages are logged under the normal prompt logging settings like any other request, so turn off store_prompts_in_spend_logs for keys whose agents read private code if prompts must not be stored.

Results are returned inside markers with a random value per response, and the text rendering escapes < so a docstring cannot close the marker early. Repository content is untrusted input for the agent, and the server's instructions say so.

Webhook deliveries are reduced to the repository id, branch and head commit before anything is stored. Commit messages and author details in a push payload are never kept.

Binding a credential, connecting, reindexing, changing settings, rotating a webhook, disconnecting a repository and installing the GitHub App each write an entry to the audit log when store_audit_logs is on, with who did it, which repository or credential it was about, and the value before and after the change. Repository rows go to the Spanway_CodeRepoTable table and credential rows to Spanway_CodeCredentialTable. When the GitHub App is uninstalled or suspended, a repository is removed from an installation, or the poller finds a repository unreadable, the gateway writes the row itself under the system:code_graph actor. Webhook paths are shown as REDACTED in the audit log because the path acts as a password.

Retention and privacy​

Indexed code, symbols and edges live only in the codegraph schema and are removed as soon as a repository is disconnected or its organization is deleted. The gateway database keeps the repository row, which names the repository and who connected and last changed it, and the index runs, which name who queued them. Set maximum_code_index_run_retention_period to delete finished index runs and maximum_code_repo_retention_period to delete disconnected repositories this long after their index rows were removed, both on the compliance page. Webhook delivery ids and body digests are kept for one day. A data subject erasure replaces the user's id in repository rows, credential bindings and index runs.

Secrets​

Files whose names usually hold secrets, such as .env, *.pem, id_rsa, *.tfstate and credentials.json, are never stored. In every other file, provider keys such as AWS access keys, GitHub tokens, Anthropic and OpenAI keys, Stripe live keys, private key blocks and passwords in connection strings are replaced with <redacted:secret> before the file is stored or parsed. A multi-line key becomes one marker per line, so line numbers still match the repository.

Set up the database​

The application connects with a role that can read and write the codegraph schema but does not own it and cannot bypass row-level security. A separate migration connection creates the schema, the codegraph_owner, codegraph_reader and codegraph_writer group roles and the tables.

CREATE ROLE spanway_code LOGIN PASSWORD 'change-me' IN ROLE codegraph_reader, codegraph_writer;

Create the group roles first by starting the gateway once with the migration URL set, or create them yourself as NOLOGIN roles. Then set

VariablePurpose
SPANWAY_CODE_GRAPH_DATABASE_URLThe application role's connection string. Setting it turns the feature on.
SPANWAY_CODE_GRAPH_MIGRATION_DATABASE_URLA connection that may create roles and schemas. When set, the gateway applies pending schema versions at startup.
SPANWAY_CODE_GRAPH_POOL_SIZEConnections in the application role's pool, 5 by default.
SPANWAY_CODE_GRAPH_PARTITIONSHash partitions per table, 1 by default. Only read when the tables are first created.
SPANWAY_CODE_GRAPH_WORKERembedded (default) indexes and polls inside the gateway process, off serves queries only.
SPANWAY_CODE_GRAPH_POLLon (default) checks branch heads of repositories that get no webhooks, off turns that poller off.
SPANWAY_CODE_GRAPH_GITHUB_APP_CREDENTIALThe name of the stored credential that holds your GitHub App, described below.
SPANWAY_CODE_GRAPH_PARSER_PYTHONThe interpreter that runs the parser, the gateway's own by default. It needs the pinned tree-sitter grammars. At startup the gateway parses a small sample in each indexed language with it and keeps indexing off, logging why, if that fails.
SPANWAY_CODE_GRAPH_PARSER_ISOLATIONlinux_netns (default on Linux) runs the parser in a network namespace, pod_network_policy relies on a Kubernetes network policy instead, darwin_sandbox is for macOS.
SPANWAY_CODE_GRAPH_GITHUB_HOSTSComma-separated GitHub Enterprise Server hosts the gateway may fetch from. The public API host is always allowed.
SPANWAY_CODE_GRAPH_GITLAB_HOSTSComma-separated self-managed GitLab hosts the gateway may fetch from, such as gitlab.example.com. gitlab.com is always allowed.

An unknown SPANWAY_CODE_GRAPH_PARSER_ISOLATION value is treated as linux_netns, any SPANWAY_CODE_GRAPH_WORKER value other than off as embedded, and any SPANWAY_CODE_GRAPH_POLL value other than off as on. A SPANWAY_CODE_GRAPH_POOL_SIZE or SPANWAY_CODE_GRAPH_PARTITIONS that is not a whole number stops the code graph from starting, and the gateway logs Code graph failed to start and stays off. The same variables are listed in the settings reference.

Repository webhook secrets are derived from SPANWAY_SALT_KEY, falling back to the master key, and the GitHub App install link is sealed with SPANWAY_SALT_KEY. Set the same value on every replica.

The license is checked again every minute, so adding a license that lists code_graph to a running gateway turns the feature on without a restart. Until then every code graph route answers 403 and agents do not see spanway_code.

At startup the gateway checks that the application role, and every role it inherits from, is not a superuser, has no BYPASSRLS and owns nothing in the codegraph schema. If any of those is true the feature stays off and the gateway logs why. The gateway keeps serving traffic if the code graph fails to start.

If a connection pooler sits in front of Postgres, the code graph works in transaction mode because every setting it uses is local to one transaction and it never caches prepared statements.

Set up the GitHub App​

A GitHub App is the preferred way to index. It mints a token for each index run that only reaches the one repository being indexed and only reads contents and metadata, and the GitHub App receives push events without a webhook per repository. One App serves the whole gateway, and each installation is bound to exactly one tenant.

  1. In the settings of the account or organization that will own the GitHub App, open Developer settings, GitHub Apps and New GitHub App.
  2. Set the Callback URL to https://<gateway>/ui/code-graph and select Request user authorization (OAuth) during installation. The gateway uses that sign-in only to confirm the installing user can see the installation.
  3. Turn the webhook on, set the Webhook URL to https://<gateway>/code_graph/webhooks/app and set a long random Webhook secret.
  4. Under Repository permissions, give Contents and Metadata read-only access and nothing else. Under Subscribe to events, select Push. Installation events reach every App without subscribing.
  5. Choose whether the App can be installed on other accounts, create it, then generate a private key and download it.
  6. Store the App as a credential with the credentials API. The values are kept encrypted like any other credential.
curl -X POST "$SPANWAY_URL/credentials" \
-H "Authorization: Bearer $SPANWAY_ADMIN_KEY" \
-H "Content-Type: application/json" \
-d @- <<EOF
{
"credential_name": "code-graph-app",
"credential_info": {"description": "Code graph GitHub App"},
"credential_values": {
"app_id": "123456",
"slug": "examplecorp-code-graph",
"client_id": "Iv23li...",
"client_secret": "...",
"webhook_secret": "...",
"private_key": "$(cat examplecorp-code-graph.private-key.pem)"
}
}
EOF
  1. Set SPANWAY_CODE_GRAPH_GITHUB_APP_CREDENTIAL=code-graph-app on every replica and restart. For GitHub Enterprise Server, also add "api_base": "https://ghe.example.com/api/v3" and "web_base": "https://ghe.example.com" to the credential and list the host in SPANWAY_CODE_GRAPH_GITHUB_HOSTS.

To install it, a proxy admin or a holder of code_graph.manage opens Code Graph in the Admin UI and selects Install GitHub App. After the install, the browser comes back to the Admin UI, which sends the installation id and the sign-in code to POST /code_graph/app/install/complete. The gateway exchanges the code for the installing user's token, lists the installations that user can see and binds the installation only if it is among them. The install link expires after ten minutes and only the user who started it can complete it. An installation already bound to another tenant is refused.

The bound installation shows up in GET /code_graph/credentials as github-app-installation-<id>, and you connect repositories with that name as credential_name. When the App is uninstalled or suspended the binding is removed and its repositories are hidden, and a repository removed from the installation is hidden the same way.

Revoke a credential binding​

There is no route that removes a binding on its own. To stop a tenant from indexing with a credential, do one of these. For a GitHub App installation, uninstall or suspend the GitHub App, and the gateway removes the binding when the webhook arrives. For a stored token, delete or rotate the stored credential on the credentials page, after which index runs that use it fail and the repositories keep their last index until you disconnect them. Deleting the organization also removes every binding it holds.

Connect a repository​

You can also index with a fine-grained GitHub token with read access to contents and metadata. Store it with the credentials API as a GitHub Models credential, with the token in api_key, and bind it to the one tenant that may index with it. The bind is refused for any other kind of credential, and for tenant BYOK credentials.

curl -X POST "$SPANWAY_URL/code_graph/credentials/bind" \
-H "Authorization: Bearer $SPANWAY_ADMIN_KEY" \
-H "Content-Type: application/json" \
-d '{"tenant_id": "default", "credential_name": "repo-indexer"}'

Connecting needs proof that both you and the bound credential can read the GitHub repository. Your own GitHub identity comes from the per-user OAuth token of a GitHub MCP server you have already signed in to, named by user_token_server_id. That server's OAuth token URL must be on the public sign-in host when the credential uses the public API, or on the same GitHub Enterprise Server host as the credential, or the gateway treats you as having no GitHub identity.

curl -X POST "$SPANWAY_URL/code_graph/repos/connect" \
-H "Authorization: Bearer $SPANWAY_ADMIN_KEY" \
-H "Content-Type: application/json" \
-d '{
"full_name": "examplecorp/payments",
"external_repo_id": "123456789",
"default_branch": "main",
"credential_name": "github-app-installation-4242",
"owner_team_id": "payments-team",
"user_token_server_id": "source-mcp"
}'

external_repo_id is the numeric id of the GitHub repository. The upstream API must report full_name for that id to both tokens, or the connection is refused with repo_identity_mismatch. Each index run and each poll looks the repository up by its id again, so a renamed repository keeps indexing and polling under its new name.

The response contains the repository, the id of its first index run and a webhook with a path and a secret. A repository indexed with a personal token has no App webhook, so add a repository webhook with the payload URL https://<gateway><path>, content type application/json, the secret and the push event. The secret is only shown in that response. POST /code_graph/repos/{repo_id}/webhook gives the repository a new path and secret, and the old ones stop working.

Use GET /code_graph/repos, GET /code_graph/repos/{repo_id}/runs, POST /code_graph/repos/{repo_id}/reindex and POST /code_graph/repos/{repo_id}/delete to follow and manage it.

Who can manage repositories​

  • Proxy admins can manage repositories in any tenant, and admin viewers can list them.
  • A custom role acts on the repositories of the role holder's own organization. code_graph.read lists repositories, index runs, credentials and the GitHub App status. code_graph.reindex also queues index runs, and code_graph.manage also connects, configures and disconnects repositories, binds credentials and installs the GitHub App. See custom roles.
  • A team admin, or an admin of the team's organization, can connect a repository their team will own and list, reindex, configure and disconnect the repositories that team owns. They pass team_id with each request, and owner_team_id must be the same team. Team admins can only use credentials already bound to the tenant, and cannot bind credentials or install the GitHub App.

Deleting a repository removes every indexed row for it. A run still in progress notices before it activates its generation and removes what it wrote, and sending the delete again for an already deleted repository removes any rows left behind. A deleted repository can be connected again. Deleting an organization deletes its repositories, their indexed rows and its credential bindings the same way. If a repository or organization is deleted while the code graph is turned off, its index rows are removed the next time the gateway starts with the code graph on.

Connect a GitLab project​

GitLab projects on gitlab.com or a self-managed GitLab connect the same way, with a token instead of an App. Create a project access token on the project, a group access token on its group, or a personal access token for a service account, with the read_api scope and at least the Reporter role. Store it with the credentials API with gitlab as custom_llm_provider and the token in api_key. For a self-managed GitLab, add "api_base": "https://gitlab.example.com/api/v4" and list the host in SPANWAY_CODE_GRAPH_GITLAB_HOSTS. Any other API base, a plain http URL, a port or a path other than /api/v4 is refused, and the token is never sent anywhere else.

curl -X POST "$SPANWAY_URL/credentials" \
-H "Authorization: Bearer $SPANWAY_ADMIN_KEY" \
-H "Content-Type: application/json" \
-d '{
"credential_name": "gitlab-indexer",
"credential_info": {"custom_llm_provider": "gitlab"},
"credential_values": {"api_key": "glpat-...", "api_base": "https://gitlab.example.com/api/v4"}
}'

curl -X POST "$SPANWAY_URL/code_graph/credentials/bind" \
-H "Authorization: Bearer $SPANWAY_ADMIN_KEY" \
-H "Content-Type: application/json" \
-d '{"tenant_id": "default", "credential_name": "gitlab-indexer"}'

Connect with "provider": "gitlab", the project's full path as full_name (subgroups are fine) and its numeric project id as external_repo_id. The connecting user's GitLab account comes from the per-user OAuth sign-in of a GitLab MCP server, named by user_token_server_id, whose token URL must be https://<the same GitLab host>/oauth/token. Register an OAuth application in GitLab with the read_user and read_api scopes for that MCP server. The user must be an active member of the project, directly or through a group, with at least the Reporter role. A Guest, a pending invite, a blocked account or a project that is merely public or internal is refused. The bound token must see the project under the same path and be able to read its repository.

curl -X POST "$SPANWAY_URL/code_graph/repos/connect" \
-H "Authorization: Bearer $SPANWAY_ADMIN_KEY" \
-H "Content-Type: application/json" \
-d '{
"provider": "gitlab",
"full_name": "bank/payments/ledger",
"external_repo_id": "4242",
"default_branch": "main",
"credential_name": "gitlab-indexer",
"user_token_server_id": "gitlab-mcp"
}'

The response holds a webhook path under /code_graph/webhooks/gitlab/ and a secret. In GitLab, open the project's Settings, then Webhooks, add https://<gateway><path> as the URL, paste the secret as the Secret token and turn on Push events. GitLab sends the secret back in X-Gitlab-Token, and the gateway compares it in constant time before it reads the body. A missing or wrong token, or a delivery without an Idempotency-Key or X-Gitlab-Event-UUID, is refused, and a delivery id seen in the last day is ignored. Only a push to the connected branch queues a run, and other events are accepted and dropped. Without webhooks, the poller reads the branch head every five minutes, the same as for a GitHub repository.

Permission mirroring works for GitLab projects too. With it on, a caller only sees the project while their own GitLab account, from the per-user sign-in of the GitLab MCP server you name as acl_server_id, is an active member with at least the Reporter role. Any doubt, such as GitLab being unreachable, a reply the gateway cannot read or a token from another host, hides the project.

Machine credentials for GitLab are tokens rather than an OAuth application, because GitLab replaces the refresh token on every use, which needs a writable secret store the code graph does not keep. Project and group access tokens are GitLab's own answer for this and can be rotated without touching a person's account.

A large project whose file list runs past 100 pages of 100 entries is read from the commit's archive.tar.gz instead, with the same archive limits as a GitHub repository. Project ids are only unique per GitLab host, so connecting two projects with the same id from two hosts in one tenant is refused as a duplicate.

How indexing works​

Indexing runs when a repository is connected, when you ask for a reindex, when a push to the indexed branch arrives as a webhook and when the poller sees the branch head move. Every webhook must carry a valid X-Hub-Signature-256 for the App secret or the repository secret, bodies over 5 MB are refused, and each X-GitHub-Delivery id and each signed body is only acted on once within a day, so resending a captured body under a new delivery id changes nothing. A delivery that fails while it is being handled is forgotten again, so redelivering it from the GitHub App's delivery log processes it. A wrong signature and an unknown repository webhook path both get the same 401.

Before an installation event that deletes or suspends the App, or an installation_repositories event that removes repositories, takes access away, the gateway requests a GitHub App installation token for that installation and repository. When the token is still issued, the event is stale and is counted as stale_revocation without changing anything. When the request is refused or the provider cannot be reached, access is taken away.

Pushes are debounced. The first push queues a run that starts ten seconds later, and further pushes before it starts join that run, which indexes whatever the branch head is when it starts. A reindex request joins a waiting run too and starts it straight away. Pushes that arrive while a run waits out a retry backoff join that run, and a run that fails after another run was queued for the same repository is folded into the queued one.

Repositories that have not had a webhook delivery in fifteen minutes are polled every five minutes. The poller asks for the branch head with the last ETag, which is answered with 304 without counting against the rate limit, and queues a run when the head moved. A 403 that carries retry-after or names a secondary rate limit counts as a rate limit, not as lost access. Replicas share the work through the database, so each repository is checked at most once per interval however many replicas run.

Only one run per repository indexes at a time, and a run holds a lease it renews while it works, so a second gateway replica never indexes the same repository in parallel. A run that hits an upstream rate limit or server error is retried with exponential backoff, from one minute up to an hour, and is marked dead after five attempts. Other failures fail the run straight away, and lost access also hides the repository as described above.

Each run lists the tree at the branch head, fetches only blobs it has not stored before, checks that each blob's content matches its git hash, and parses new Python, TypeScript, Java, Go and C# files in batches. When the provider truncates the tree of a very large repository, the run downloads the commit's tarball instead. The tarball must come from the provider's archive host, or for GitHub Enterprise Server from the same host or its codeload. subdomain, the credential is only sent to the API host and never to any other host, and an archive with a path outside the repository, more than 200,000 entries, more than 2 GB unpacked, more than 512 MB of indexable files or a compression ratio above 100 is refused whole.

The parser runs as a separately started process with an empty environment, no network, no file writes and a CPU limit per file, and the gateway validates everything it prints. A file that crashes or stalls the parser is stored as text only and the run carries on.

Every run writes a new generation. Rows carry the generation they appeared in and the one they stopped being true in, so a push only writes the rows that changed and readers keep seeing the previous generation until the new one is complete. After a push, only files that changed, files that import them directly or through other modules, and files that use a name the change defined or removed are resolved again. A change to tsconfig.json, package.json, a Python __init__.py or a TypeScript index.ts resolves the whole repository again. tsconfig.json is read as JSON with comments and trailing commas, the way TypeScript reads it, and a tsconfig.json over 256 KB is ignored. A change to the root go.mod also resolves the whole repository again.

Languages​

LanguageFilesHow references resolve
Python.py, .pyiImports, relative imports, package __init__.py re-exports and self or cls members.
TypeScript.ts, .mts, .cts, .tsx, .d.tsRelative imports, barrels, ESM .js suffixes, tsconfig.json path aliases and this members.
Java.javaAn import of a class resolves to the file whose path ends in that package and class name, so Maven and Gradle source roots need no setup. Unqualified calls inside a class reach its own and inherited members.
Go.goAn import path resolves to a package directory through the module path in the root go.mod, and a name can live in any file of that package. Without a go.mod, only import paths whose first element has a dot (not the standard library) are matched against directories. Methods are named after their receiver type, as in Repo.Save.
C#.csCalls, new expressions and base types resolve within the file and the enclosing class first, then by name across the repository. using directives name namespaces, not files, so they do not narrow a match.

References that cannot be pinned to one definition fall back to a name match and carry a lower confidence. Generated C# files (*.g.cs, *.Designer.cs and anything under obj/) are skipped like other generated code.

Metrics​

The metrics are served on /metrics next to the gateway's other Prometheus metrics, which the gateway only mounts once the Prometheus callback is enabled, for example with success_callback: ["prometheus"] under spanway_settings.

MetricTypeMeaning
spanway_codegraph_index_runs_total{outcome}counterFinished index runs by succeeded, failed, retrying or superseded.
spanway_codegraph_index_run_seconds{outcome}histogramWall-clock time of one index run.
spanway_codegraph_queue_depthgaugeRuns waiting to be claimed, refreshed every minute.
spanway_codegraph_webhook_deliveries_total{outcome}counterWebhook deliveries by what the gateway did with them, such as queued, duplicate, bad_signature or stale_revocation.
spanway_codegraph_poll_checks_total{outcome}counterBranch head checks by unchanged, moved, access_lost or unavailable.
spanway_codegraph_upstream_ratelimit_remaining{provider}gaugeRequests left in the upstream rate limit window, as last reported.
spanway_codegraph_tool_seconds{tool}histogramTime to answer one spanway_code tool call.
spanway_codegraph_tool_failures_total{tool}counterspanway_code tool calls that returned an error.
spanway_codegraph_swept_repos_totalcounterDeleted repositories whose leftover rows the startup sweep removed.

Admin UI​

Code Graph sits under Tools in the Admin UI. It lists the connected repositories with their status, indexed commit, whether updates come from webhooks or the poller, the owner team and the last error. From there you can bind a GitHub token or GitLab token credential, connect a GitHub repository or a GitLab project, see its index runs, queue a reindex, rotate its webhook, turn permission mirroring on or off, disconnect it and install the GitHub App. Each action only shows when the gateway reports that the signed-in user may take it, and the page says which role is missing when it does not. Team admins pick their team in Acting for team to manage the repositories that team owns.

Bind credential shows for proxy admins and holders of code_graph.manage. Enter the name of the stored GitHub token or GitLab token credential and, as a proxy admin, the organization to bind it to. Left empty, it binds to your own organization, or default if you have none.

When the license does not include code_graph, the page says so instead of showing an empty table. It does the same when SPANWAY_CODE_GRAPH_DATABASE_URL is not set, and when your role cannot read repositories, in which case it asks you to get code_graph.read or to pick a team you administer.

Not available yet​

Lazy partial results during a first index, Azure DevOps and other self-hosted Git repositories, installing on GitLab through an OAuth application, a Grafana dashboard row and alerts for the metrics above, and index lag, per-stage and parse failure metrics are not built yet. A caller who has not linked the GitHub identity a mirrored repository needs is not told to link one, and simply does not see that repository. There is no route or Admin UI control that removes a credential binding on its own, see Revoke a credential binding.

Errors​

Code graph routes answer errors as {"detail": {"error": "<message>"}}. The same messages are in the error reference.

StatusMessageMeaning and fix
403The 'code_graph' feature needs a Spanway enterprise license. ...The gateway has no enterprise license. Add one that lists code_graph. The gateway turns the code graph on within a minute, without a restart.
403Your Spanway license does not include the 'code_graph' feature. Contact sales@spanway.ai to add it.The license is valid but leaves the code graph out. Ask for a license that includes it.
403Not allowed to <action> code graph repositories (<reason>)The caller lacks the role, see Who can manage repositories. not_allowed means no role or team admin grant covers the action, tenant_not_allowed means a custom role asked about another organization, and team_admins_cannot_do_this means a team admin tried to bind a credential or install the GitHub App.
403Repository connection refused: <reason>See the reasons below. Nothing is written when a connection is refused.
400Only a stored GitHub personal access token or GitLab access token credential can be bound to the code graphThe named credential is not a stored source control token. Store the token as described in Connect a repository and bind that name.
400Mirroring needs acl_server_id, the GitHub or GitLab MCP server users sign in toSend acl_server_id when turning permission mirroring on.
404No connected repository has that id in this scopeThe id is wrong, or the repository belongs to another team.
409That repository is already connected in this tenantUse the existing connection, or disconnect it first.
503The code graph is not configured on this gatewaySet SPANWAY_CODE_GRAPH_DATABASE_URL and restart.
503Set SPANWAY_SALT_KEY to sign repository webhooksSet SPANWAY_SALT_KEY before connecting or rotating a webhook.
503No GitHub App is configured for the code graph on this gatewaySet SPANWAY_CODE_GRAPH_GITHUB_APP_CREDENTIAL and restart before installing the App.
403Installing the GitHub App needs a signed-in userInstall from an Admin UI session, not with a virtual key.
400The install link expired or was started by someone else, start the install againThe link is older than ten minutes or belongs to another user. Select Install GitHub App again.
400The install link could not be read, start the install againThe link was changed on the way back. Start the install again.
400The install link was started by someone else, start the install againOnly the user who started the install can finish it.
403GitHub did not accept the sign-in code, start the install againThe sign-in code expired or was already used. Start the install again.
502GitHub did not list the installations this user can see, try againThe source host did not answer. Try again in a minute.
403The signed-in GitHub user cannot see that installationSign in with a GitHub identity that can see the installation, such as an owner of the organization that installed the App.
409That GitHub App installation is already bound to another tenantOne installation serves one tenant. Install the App on another organization, or disconnect the other tenant's repositories and remove its binding first.
413Webhook body is larger than 5 MBSent by GitHub or GitLab, not people. Only push events are needed, so turn off other events on the webhook.
400The webhook payload could not be readThe delivery is not JSON or not a push event the gateway understands. Check the webhook content type is application/json.
401The webhook signature does not matchThe webhook secret on the source host differs from the gateway's. Rotate the webhook and paste the new secret.
400The webhook has no delivery id headerA GitLab delivery without Idempotency-Key or X-Gitlab-Event-UUID. Use a GitLab version that sends one.

The reasons after Repository connection refused: are

ReasonWhat it meansFix
credential_not_in_tenantThe credential is not bound to this tenant.Bind it first with POST /code_graph/credentials/bind.
credential_provider_mismatchA GitLab project was connected with a GitHub credential, or the reverse.Pick a credential for the same host.
credential_host_not_allowedThe credential points at a host the gateway may not fetch from.List the host in SPANWAY_CODE_GRAPH_GITHUB_HOSTS or SPANWAY_CODE_GRAPH_GITLAB_HOSTS.
installation_not_bound_to_tenantThe App installation belongs to another tenant.Use an installation bound to this tenant.
owner_team_not_allowedA team admin named another team as owner, or the team is not in the tenant.Set owner_team_id to the team you act for.
actor_has_no_upstream_identityYou have not signed in to the MCP server named by user_token_server_id, or its sign-in is for another host.Sign in to that MCP server in the Admin UI and try again.
actor_cannot_read_repoYour own GitHub or GitLab account cannot read the repository.Ask for read access on the source host.
credential_cannot_read_repoThe bound credential cannot read the repository.Give the token or App installation access to the repository.
repo_identity_mismatchThe source host names another repository for external_repo_id.Check the numeric id and full_name.
upstream_unavailableThe source host did not answer.Try again in a minute.

Logs​

These lines are written to the gateway log. None of them carries code or tokens.

LevelLineMeaningAction needed
INFOCode graph schema versions applied: <versions>The migration connection created or upgraded the codegraph schema at startup.None. Only appears when SPANWAY_CODE_GRAPH_MIGRATION_DATABASE_URL is set.
INFOCode graph is configured but the license does not include 'code_graph'...The database is set but the license leaves the feature out.Add a license that includes it if you want the code graph.
INFOCode graph removed index rows of <n> deleted repositoriesThe startup sweep cleaned up repositories deleted while the code graph was off.None.
WARNINGCode graph startup sweep failed: <error type>The cleanup above could not run.Check the database connection. The sweep runs again on the next start.
ERRORCode graph stays off because its database role is unsafe: <problems>The application role owns the schema or can bypass row-level security.Use a role that is only a member of codegraph_reader and codegraph_writer, see Set up the database.
ERRORCode graph indexing stays off because the sandboxed parser could not parse a sample...The parser interpreter lacks the pinned grammars, so queries work but nothing is indexed.Point SPANWAY_CODE_GRAPH_PARSER_PYTHON at an interpreter with the grammars.
ERRORCode graph failed to start and stays off: <error type>Startup failed, for example the database is unreachable or a variable is not a number. Only the error type, such as ValueError or OperationalError, is logged.A ValueError usually means a SPANWAY_CODE_GRAPH_* variable has a wrong value, a connection error means the database. Check the variables in Set up the database and restart.
WARNINGCode graph metrics could not be registered: <error>The Prometheus metrics above are missing.Check that only one process registers them.
WARNINGCode graph indexing failed for run <run id>: <error type>One index run failed. The run's error is also shown in the runs list.Look at the run's error and reindex once it is fixed.
WARNINGCode graph lease renewal failed for run <run id>: <error type>The worker lost contact with the database during a run. The run is picked up again.Check the database if it repeats.
WARNINGCode graph worker poll failed: <error type>The worker could not claim queued runs this time.Check the database if it repeats.
WARNINGCode graph poll failed for <repo id>: <error type>A branch head check for one repository failed. Other repositories are still checked.Check the credential if it repeats.
WARNINGCode graph poller tick failed: <error type>A whole poll round failed, usually the database.Check the database if it repeats.
WARNINGCode graph maintenance tick failed: <error type>The once-a-minute queue depth refresh and cleanup of old webhook deliveries failed.Check the database if it repeats.

The log reference lists the same lines.