Standardizing Agent Memory with OKF and Codebase Knowledge Graphs
How to combine Google's Open Knowledge Format with self-updating codebase graphs to give coding agents portable, versioned, and token-efficient repository memory.

Coding agents are excellent at reading code, but they are poor at remembering a codebase between sessions. Each new task can trigger the same expensive routine: search for entry points, open files, trace imports, reconstruct architecture, and infer which tests matter.
A durable repository memory changes that workflow. Instead of treating a repo as a pile of files to rediscover, an agent can consult a maintained map of its symbols, dependencies, concepts, and design rationale.
Two technologies make this practical:
- Open Knowledge Format (OKF) provides a portable, vendor-neutral way to store knowledge as Markdown files with YAML frontmatter.
- Codebase knowledge graphs extract and maintain structural relationships across code, documentation, schemas, tests, and other repository assets.
OKF standardizes how durable knowledge is written and exchanged. A code graph handles extraction, traversal, and updates. Together, they create a version-controlled memory layer that coding agents can query before falling back to raw files.
The Short Version
A practical agent-memory architecture has four layers:
| Layer | Responsibility | Typical implementation |
|---|---|---|
| Extraction | Parse files and identify entities and relationships | Tree-sitter, SCIP, language servers, semantic extraction |
| Graph storage | Persist symbols, links, dependencies, and communities | JSON, SQLite, or a graph database |
| Knowledge bundle | Preserve curated concepts, rationale, and runbooks | OKF Markdown files in git |
| Agent interface | Retrieve the smallest useful context for a task | MCP tools, CLI queries, skills, and hooks |
The graph should be authoritative for mechanically extracted structure. The OKF bundle should provide a portable, human-readable layer for meaning, decisions, and operational knowledge.
This distinction matters. A call graph can prove that one function invokes another. It cannot reliably explain why a team chose that dependency, which failure mode operators fear, or which migration constraint still applies. That is where curated knowledge belongs.
What Is Open Knowledge Format?
Google introduced Open Knowledge Format as an open specification for the "LLM wiki" pattern: a directory of Markdown documents that can be read by people, agents, source control, and ordinary text tools without a proprietary SDK.[1]
An OKF concept document contains YAML frontmatter followed by a Markdown body. The only universally required frontmatter field is type. Fields such as title, description, resource, tags, and timestamps add useful structure without imposing a centralized taxonomy.[2]
---
type: Service
title: Billing API
description: Handles subscription billing and invoicing.
resource: /services/billing/README.md
tags: [payments, critical-path]
---
# Billing API
The billing service owns subscription state and invoice generation.
## Dependencies
- [Authentication service](/services/auth.md)
- [Payments database](/databases/payments.md)
Standard Markdown links connect concepts. The directory hierarchy supplies broad organization, while links turn the bundle into a graph that agents and humans can traverse.
Reserved files have special roles:
index.mdprovides progressive disclosure and navigation for a directory.log.mdrecords a chronological history of changes.
OKF is deliberately a format, not a platform. It does not prescribe a database, query language, retrieval engine, agent runtime, or model provider. This makes an OKF bundle easy to commit to git, review in a pull request, copy between systems, or consume with basic file tools.
From OKF v0.1 to v0.2
The original v0.1 specification established the minimal Markdown and frontmatter conventions. OKF v0.2 adds first-class vocabulary for provenance, verification, freshness, lifecycle, and attestation while keeping those additions optional.[2][3]
Those trust signals answer questions that become critical when agents maintain the corpus:
- What source produced this concept?
- Who or what verified it?
- Is the information still fresh?
- Is this the current version?
- Can a claimed computation be reproduced and attested?
This makes v0.2 especially relevant to codebase memory. A generated architecture document can identify the commit it came from, record whether a deterministic extractor or an LLM produced it, and indicate whether a human has reviewed it.
The important compatibility rule remains unchanged: consumers should tolerate unknown types and fields. Teams can extend the format without waiting for a central schema registry.
Why a Knowledge Graph Is Needed
OKF makes knowledge portable, but it does not keep that knowledge synchronized with a changing repository.
A coding agent regularly needs answers such as:
- Where is authentication implemented?
- Which endpoints depend on this service?
- What calls this function?
- Which tests cover the affected path?
- Which configuration and documentation describe the same behavior?
- What is the likely blast radius of this change?
Plain retrieval can find text that resembles a query, but code questions often depend on explicit relationships. Imports, calls, inheritance, ownership, test coverage, and cross-repository references are graph-shaped facts.
A codebase graph models those facts directly:
Route handler
-> calls authentication service
-> reads session repository
-> emits audit event
-> covered by integration test
-> documented by security runbook
The agent can retrieve that small neighborhood instead of opening every file that mentions "authentication."
This does not eliminate file reads. Once the graph identifies the relevant symbols, the agent still needs source code for exact implementation details. The graph reduces the search space; it does not replace the source of truth.
Tools for Building Codebase Graphs
Graphify
Graphify is an open-source codebase graph tool designed for coding assistants. It uses Tree-sitter for deterministic code parsing and can apply semantic extraction to documentation, PDFs, images, and video.[4]
A typical run creates three artifacts under graphify-out/:
graph.jsonfor machine queriesGRAPH_REPORT.mdfor a compact human and agent overviewgraph.htmlfor interactive exploration
Graphify distinguishes explicitly extracted edges from inferred relationships. That is useful for agent reasoning because a static call edge deserves more confidence than a semantic association inferred from prose.
Its CLI supports scoped operations such as:
graphify query "show the authentication flow"
graphify path "LoginRoute" "SessionStore"
graphify explain "TokenValidator"
Graphify also provides assistant integrations and git hooks for incremental graph maintenance.
code-review-graph
code-review-graph is a local-first graph focused on review context and blast-radius analysis.[5] It parses code with Tree-sitter, stores relationships in SQLite, and exposes the graph through CLI and MCP tools.
Its graph can represent:
- Functions and classes
- Imports and calls
- Inheritance
- Tests and coverage relationships
- Execution flows
- Communities and risk information
The recommended MCP workflow starts with get_minimal_context_tool, then uses targeted tools such as query_graph_tool, get_impact_radius_tool, detect_changes_tool, and get_review_context_tool.[6]
Sourcegraph and SCIP
At organizational scale, Sourcegraph demonstrates the same architecture across many repositories. SCIP indexes provide precise definition and reference data, while search and code intelligence expose the resulting graph to developers and agents.[7]
The storage and deployment model differs from local tools, but the principle is the same: compute reusable structural context once, update it incrementally, and query it instead of reconstructing it for every task.
Designing Self-Updating Repository Memory
A robust implementation separates generated structure from curated knowledge.
1. Extract deterministic facts
Use AST parsers, SCIP indexes, language servers, schema readers, and configuration parsers to capture facts that can be reproduced from the repository:
- File and symbol definitions
- Imports and references
- Call relationships
- Inheritance and interface implementations
- Routes, schemas, and database objects
- Test mappings
These facts should include source locations and the commit or content hash from which they were derived.
2. Add semantic relationships carefully
Some useful relationships cannot be recovered from syntax alone. Documentation may explain that two services participate in the same business flow, or that a migration exists because of a regulatory requirement.
Semantic extraction can add those connections, but inferred edges should be labeled and assigned lower confidence than deterministic edges. Agents should know when a relationship is proven by code and when it is a hypothesis derived from text.
3. Persist the graph
Choose storage according to scale and query requirements:
| Storage | Best fit | Trade-off |
|---|---|---|
| JSON | Portable snapshots and simple tooling | Expensive for complex or repeated traversal |
| SQLite | Local-first indexing and targeted queries | Less natural for distributed, cross-repo graphs |
| Graph database | Large, shared, relationship-heavy systems | More operational complexity |
For a single repository, JSON or SQLite is often enough. A graph database is not a prerequisite for graph-backed memory.
4. Generate OKF concepts
Map important graph entities and communities into a small, stable vocabulary such as:
ServiceModuleAPI EndpointData FlowArchitecture ViewPlaybookRunbook
Generated concepts can summarize dependencies and link to source resources. Human-authored sections should preserve rationale, constraints, and operational knowledge that static analysis cannot infer.
Avoid regenerating an entire document if it would overwrite human edits. Prefer one of these patterns:
- Keep generated and curated concepts in separate directories.
- Mark generated sections with stable boundaries and update only those sections.
- Store generated facts in frontmatter while keeping the body human-owned.
5. Track provenance and freshness
Every generated concept should identify its origin. Useful metadata includes:
type: Architecture View
title: Authentication Flow
resource: /src/auth
generated_at: "2026-08-08T10:00:00Z"
git_commit: "abc1234"
generator: "repo-graph/1.4.0"
When using OKF v0.2, prefer its standardized provenance and verification fields over custom equivalents. CI can then detect concepts generated from an older commit or flag resources that no longer exist.
Keeping the Graph Fresh with Git and CI
A self-updating pipeline usually has three stages.
Local incremental updates
A post-commit or post-checkout hook reparses changed code and updates graph artifacts. Graphify provides:
graphify hook install
The installed hooks perform code-only incremental updates and configure a merge driver for graph artifacts.[4] Teams should still test hook behavior in their own workflow. Post-commit generation can leave the worktree dirty, and hooks are not guaranteed to run in every GUI, CI environment, or contributor setup.
Pull request validation
CI should verify that:
- The graph can be rebuilt successfully.
- Committed graph artifacts match the source revision.
- Every OKF concept has valid YAML frontmatter and a non-empty
type. - Internal links resolve.
- Referenced source files and symbols still exist.
- Generated concepts carry current provenance metadata.
Validation is more reliable than assuming every developer installed the local hooks.
Scheduled reconciliation
A periodic full rebuild catches drift that incremental processing can miss. Compare the full graph with the incrementally maintained graph, report orphaned concepts, and require review when high-value architecture or runbook documents become stale.
Integrating Graphify with Claude Code and Codex
Install Graphify with an isolated Python tool environment:
uv tool install graphifyy
Register it with the detected assistant:
graphify install
For a project-scoped installation:
graphify install --project
For Codex:
graphify install --project --platform codex
For Claude Code, an always-on project integration can be installed with:
graphify claude install --project
Graphify's Claude integration adds project instructions and a PreToolUse hook that nudges the assistant toward graph queries before broad file search. Strict mode blocks the first raw source read in a session until the graph is consulted:
graphify install --project --strict
Strict routing can reduce unnecessary exploration, but it should not block direct reads when the graph is missing, stale, or unable to answer a precise implementation question.
Integrating code-review-graph with MCP
Install and build the local graph:
pip install code-review-graph
code-review-graph build
Start a focused MCP server:
code-review-graph serve --tools query_graph_tool,semantic_search_nodes_tool,detect_changes_tool,get_review_context_tool
Then configure the agent to follow a graph-first review workflow:
- Call
get_minimal_context_toolonce at the start of the task. - Use
detail_level="minimal"for initial queries. - For reviews, call
detect_changes_toolbefore opening files. - Retrieve only the relevant snippets with
get_review_context_tool. - Expand to raw source when the graph context is insufficient.
This progression keeps context compact without pretending that summaries can replace code inspection.
Exposing OKF to Agents
Do not load every concept into every prompt. Large always-loaded bundles recreate the token problem the graph is meant to solve.
Use progressive disclosure instead:
- Load the bundle's root
index.mdas a map. - Route by the
type, tags, and links of likely concepts. - Read the smallest relevant set of concept documents.
- Query the graph for current structural evidence.
- Read raw files for exact code, configuration, or tests.
Project instructions can state:
## Repository knowledge
For architecture, dependency, or rationale questions:
1. Read the relevant OKF index and concept documents under `knowledge/okf/`.
2. Query the repository graph for current symbols and relationships.
3. Read raw source files only for details the knowledge layer cannot answer.
4. Treat deterministic graph edges as structural evidence and inferred edges as leads to verify.
5. Check provenance before relying on generated concepts.
The same policy works in CLAUDE.md, AGENTS.md, or another assistant-specific instruction file.
Do Knowledge Graphs Really Save Tokens?
Yes, but benchmark interpretation matters.
Graphify reports large reductions when comparing a compact graph query with reading an entire mixed corpus.[8] code-review-graph reports substantial per-question reductions when comparing targeted graph context with a whole-repository baseline.[9]
Those comparisons demonstrate the upper bound of avoidable context, not the guaranteed savings over a competent coding agent. A strong agent rarely reads an entire repository for every question. It already uses search, targeted reads, language intelligence, and cached context.
The fairest evaluation compares:
- A graph-first agent
- A search-first agent with the same model and tools
- The same set of real repository tasks
- Total input tokens, tool calls, latency, answer quality, and defect rate
- Graph construction and maintenance cost amortized across tasks
Graphs tend to help most with:
- Architecture questions
- Cross-module and cross-language flows
- Blast-radius analysis
- Code review
- Test discovery
- Large repositories and monorepos
- Repeated tasks over the same codebase
They help less with:
- Tiny repositories
- Isolated single-file edits
- Tasks that require reading most of a file anyway
- Reflection-heavy or dynamically generated systems
- Stale graphs with weak source coverage
Token reduction is only valuable if answer quality remains stable or improves. A smaller but incomplete context can be cheaper and wrong.
A Practical Adoption Checklist
Phase 1: Establish the knowledge bundle
- Create
knowledge/okf/ordocs/okf/. - Add a root
index.md. - Define a small set of concept types.
- Document ownership for generated and human-authored content.
- Add provenance and freshness metadata.
Phase 2: Build the graph
- Select Graphify, code-review-graph, SCIP-based indexing, or an equivalent tool.
- Run an initial full build.
- Inspect false edges, missing languages, and generated-code noise.
- Decide which artifacts belong in git and which remain local or in CI.
Phase 3: Connect the layers
- Generate OKF concepts only for high-value services, flows, and runbooks.
- Link concepts to source resources and graph node identifiers.
- Keep deterministic facts separate from inferred semantic relationships.
- Protect human-authored rationale from regeneration.
Phase 4: Automate freshness
- Install local incremental hooks where appropriate.
- Rebuild or validate the graph in CI.
- Check OKF frontmatter, internal links, and referenced resources.
- Schedule periodic full reconciliation.
Phase 5: Teach agents to retrieve progressively
- Start with OKF indexes and compact graph queries.
- Use task-specific MCP tools before broad exploration.
- Fall back to source files whenever exact implementation details matter.
- Record whether an answer relied on stale or inferred knowledge.
Phase 6: Measure the result
Track real work before and after adoption:
- Input tokens per completed task
- Tool calls and files opened
- Time to first correct architectural answer
- Review defects found and missed
- Graph build and maintenance cost
- Frequency of stale-context failures
The goal is not the largest benchmark multiplier. The goal is a lower total cost for correct work.
The Emerging Pattern
OKF and codebase graphs solve different parts of the same problem.
OKF makes knowledge portable, reviewable, and independent of any one agent platform. A codebase graph makes structural context queryable and maintainable. Git supplies history and collaboration. MCP, skills, and hooks expose the memory layer to coding agents.
The result is best understood as compiled repository memory:
- Source code and documentation are the inputs.
- Extractors compile relationships into a graph.
- Curated concepts add meaning and rationale.
- Provenance records when and how the memory was produced.
- Agents query the compiled view, then verify important details against source.
This architecture will not remove the need for search or code reading. It makes both more selective. Instead of rebuilding a mental model from scratch, an agent begins with a shared map, follows the relevant relationships, and spends its context window on the code that actually matters.
Sources
[1] How the Open Knowledge Format can improve data sharing - Google Cloud
[2] Open Knowledge Format specification - GoogleCloudPlatform/knowledge-catalog
[3] OKF v0.2 adds trust signals - Google Cloud
[4] Graphify repository and documentation
[5] code-review-graph repository
[6] code-review-graph agent instructions
[7] Sourcegraph code search and code intelligence
