跪拜 Guibai
← Back to the summary

CodeGraph Cuts AI Coding Token Costs by 52% with Frontend-Aware Knowledge Graphs

Agentic Search

Coding agents like Claude Code, Codex, Cursor, OpenCode, and Trae can implement features, refactor code, and fix bugs for our projects on one condition: they need to understand your code repository.

Typically, a user inputs a natural language question: "Please help me look up the order placement process and how to ensure order status consistency." At this point, the agent first needs to understand what the order placement process is. It will query rewrite this question into corresponding keywords, such as: order|orderStatus|orderProcess, and then use these keywords to find the relevant code snippets:

Through multiple rounds of querying, fragmented information is organized into logical context.

image.png

However, this query method has the following problems:

CodeGraph

CodeGraph is a method that converts a code repository into a searchable, traversable code knowledge graph (composed of entities and relationships) through static analysis (Tree-sitter, etc.). It captures context such as files, functions, methods, classes, call relationships, dependencies, field reads/writes, and state flows, and provides relevant APIs for callers to retrieve. This allows AI to move beyond keyword search and truly understand the relationships between code.

Here are some well-known code knowledge graph solutions:

Project One-liner Positioning Core Technology Graph Design How to Recall Relevant Code Update Method Most Outstanding Feature
GitNexus A full-featured code knowledge graph and Graph RAG platform Tree-sitter + LadybugDB; supports browser WASM Files, functions, classes, call relationships, with pre-computed functional communities and execution flows BM25 keyword + vector semantic search + RRF fusion, then combined with call chains and functional communities Re-execute analysis; incremental capability is still evolving Relatively complete retrieval, impact analysis, flow analysis, and visualization
code-review-graph Oriented towards code review and change risk analysis Tree-sitter + SQLite, optional vector model Functions, classes, imports, calls, inheritance, test relationships, and identifies code communities and execution flows Full-text search + optional semantic vectors + graph traversal, focusing on finding the scope of change impact Watch, Git Hook, and incremental updates Best suited for PR reviews, test gaps, and risk scoring
codebase-memory-mcp A code graph backend pursuing extreme performance and language coverage Tree-sitter + Hybrid LSP + SQLite, static binary Besides code symbols, also models HTTP routes, infrastructure resources, and cross-service relationships Name/regex search, graph traversal, Cypher queries, and code search Background auto-sync, can also share compressed graph database Wide language coverage, fast queries, few dependencies
CodeGraph Provides AI coding agents with always-up-to-date, precise code context Rust native parsing kernel + Tree-sitter + SQLite/FTS5 Nodes are files and code symbols; edges are calls, imports, inheritance, implementation, and framework routes First uses full-text search to locate entry points, then expands along call relationships; returns source code, call paths, and impact scope at once Watches file changes, only syncs changed parts Runs locally, auto-refreshes, and converges complex queries into a single explore tool
Graphify Unifies code, docs, PDFs, configs, etc., into a browsable knowledge graph Tree-sitter; LLM can be used for non-code content extraction Concept-level graph; each edge labeled as "source-extracted" or "inferred"; uses Leiden for community partitioning Does not use a vector library, mainly recalls via subgraphs, neighbors, and shortest paths Supports manual updates, Watch, and Git Hook Richest data sources, graph relationships are explainable, easy to visualize and share within teams

After comparing various industry solutions, we ultimately adopted the CodeGraph solution. It includes complete benchmark tests, has relatively good productization, and aligns with our early exploration based on the theory of LocAgent at the end of 2025 (we had already implemented a version of CodeGraph based on this theory before). It is also a relatively pure, purely engineering-side foundational capability.

Its core process can be summarized as: FTS is responsible for precise symbol and keyword positioning, and CodeGraph is responsible for expanding context along call and reference relationships. When combined, the recall results are explainable and highly deterministic.

Business Practice

To enhance frontend semantics, we established standards for the CodeGraph graph: the design of entities and edges.

Entity Types

General Entities

General entities are used to describe the basic structure of the codebase and language-level symbolic relationships, applicable across different languages.

Entity Meaning Description
file File The carrier unit for all code, configuration, and resources
directory Directory The basic structural entity of the repository
function Function or inline callback A callable logic unit at the language level
method Method A method within a class, object, or framework object
class Class The type and inheritance structure at the language level
import Import definition The entry point for module dependencies and symbol references
export Export definition The symbols exposed by a module to the outside world

Framework Entities (Vue/Mpx/React)

Framework entities describe the semantics generated by frontend applications through frameworks or runtime conventions like Vue, Mpx, and React (frontend-specific semantics). These entities are often not fully expressible by a pure language AST and require a combination of framework parsers, configuration parsing, and convention recognition.

Entity Meaning Description
app Application entry point Application startup, mounting, and global configuration entry point
page Page entry point Frontend business page or route page
component UI component Vue/Mpx component or React component
reactive_state Local reactive state, e.g., prop, data, ref, useState, computed Internal state of a component or page
global_state Global state, e.g., store, model, global atom State shared across pages and components
event_channel Event channel, e.g., emit/on, event bus Component events, page events, or global event communication

Relationship Types

General Edges

General edges describe structural, dependency, and call relationships that hold true across technology stacks.

Edge Meaning Description
contains Structural containment relationship Hierarchical relationships of directories, files, classes, methods, and functions
invokes Ordinary call relationship Calls between functions, methods, and callbacks
imports Module dependency relationship Import dependencies between files or modules
extends Inheritance relationship A subclass inheriting from a parent class
resolves_to Configuration or symbol resolves to a target entity, e.g., a route resolves to a page Resolution results for import/export, routes, configuration, etc.
depends_on General dependency relationship, typically used for weaker or less specifically classifiable dependencies A fallback dependency edge, suitable for relationships with lower resolution confidence

Framework Edges (Vue/Mpx/React)

Framework edges describe UI composition, page navigation, data reads/writes, event side effects, service calls, and platform capabilities specific to frontend frameworks.

Edge Meaning Description
navigates_to Navigation relationship, e.g., page jumps, route jumps, parameter passing Jump links between pages and routes
reads_data Reads local or global state Pages, components, or functions reading reactive_state or global_state
writes_data Writes local or global state Pages, components, or functions writing reactive_state or global_state
provides_to Provider provides dependency to consumer Framework dependency injection or context provision relationship
injects_from Consumer injects dependency from provider Framework dependency injection or context consumption relationship

Based on the structured expression of entities and edges, we ultimately obtain a complete relationship graph describing the structure and semantics of the code repository. It can clearly express the relationships between code with different responsibilities.

image.png

View Layering

To better understand the repository, we created a view abstraction: you can focus on a specific area by layering the views. This layering is designed based on frontend frameworks like Vue/Mpx/React and is mainly divided into four layers:

The following examples are generated based on the open-source project vue-admin-better:

image.png

image.png

image.png

image.png

image.png

Covered Scenarios

General Scenarios (Cross-language)

Scenario Description
Structure Navigation Browse the hierarchy of directories, files, classes, methods, and functions
Call Chain Analysis Trace the call paths between functions and methods
Dependency Analysis Analyze file-level import relationships and module dependencies
Symbol Location Locate code positions by file name, function name, method name, or class name

Frontend Scenarios (Vue/Mpx/React)

Frontend Context Recall: Find relevant pages, components, states, navigation chains, and API links for AI Coding.

Scenario Description
Page Jump Analysis Trace page jumps and parameter passing
Component Usage Analysis Analyze the rendering relationships between pages and components
Data Flow Analysis Analyze the reading, writing, and side effects of local and global state

Applied to the open-source CodeGraph, adapted for internal tech projects.

Benchmark

To verify the actual benefits of frontend semantic enhancement, we selected 5 projects—Ride Code, Passenger Mini-Program, tianji-sale-car, VS Code, and Excalidraw—with 17 real code understanding questions for testing. Each case was executed 4 times as an Agent task (claude code + deepseek-v4-flash), and the median of the four rounds was used for statistics.

The test included three groups:

The test model was deepseek-v4-flash.

Metric Without Main CodeGraph CodeGraph vs Main CodeGraph vs Without
Total Time 2119.6s 1672.4s 1430.6s -14.5% -32.5%
Total Cost ¥22.735 ¥16.302 ¥13.097 -19.7% -42.4%
Total Tokens 57.45M 33.18M 27.39M -17.4% -52.3%
Tool Calls 764.5 320.0 321.5 +0.5% -57.9%

See the specific data below:

image.png

Improved CodeGraph VS without

image.png

Improved CodeGraph VS Original CodeGraph VS without

Overall, the frontend semantic enhancement achieved clear positive gains. Compared to Main (the original upstream), CodeGraph, with a basically flat number of tool calls, reduced total time by 14.5%, cost by 19.7%, and token consumption by 17.4%. This indicates the benefit is not simply from reducing tool calls, but that the semantic graph helps the Agent locate the relationships between pages, components, states, and services faster, reducing ineffective code reading and context expansion.

Compared to not using CodeGraph at all, the semantically enhanced version reduced time by 32.5%, cost by 42.4%, token consumption by 52.3%, and tool calls by 57.9%, demonstrating the significant value of graph recall for Agent code understanding in large code repositories.

Existing Problems

CodeGraph provides the capability to efficiently query and organize code context for AI Agents. It is a deterministic result produced by the engineering side. In the vast majority of scenarios, it is a tool autonomously invoked by the Agent (via CLI commands, MCP, skills, etc.) that does not affect the accuracy of the final output (only affecting time consumption, token consumption, etc.).

image.png

However, in our actual application scenarios, the first step determining query quality is often the user's input query:

image.png

image.png

Therefore, we have recently been trying to construct a Business Knowledge System. It is a business-domain-oriented knowledge base, a topological structure describing the relationships between various business entities.

Our frontend and backend can generate a knowledge graph about the code repository based on this topological structure, such as some business-explanatory md files about the code repository generated by LLM Wiki. By parsing these files, we obtain a relationship (index) between business semantics and code symbols (such as page, component, function addresses, etc.). Establishing a relationship between business semantics and related code subgraphs enables the same set of relationships to support bidirectional querying:

This is the bidirectional traceability relationship between business semantics and code.

This BKS is cross-repository and cross-technology-stack. For example, the frontend and backend are in the same PRD and have different specific code implementations for the same business scenario. At the abstraction layer, the business semantics are actually the same, while the specific code query (CodeGraph) can be optimized according to the corresponding team's technology stack. In this way, we can not only answer which code corresponds to a certain function, but also conversely answer which business the current code belongs to. Thus, when modifying a function, we can reverse-engineer which business modules will be affected. Theoretically, this can solve all scenarios: Coding, issue location, bugfix, knowledge Q&A, etc.