iTranslated by AI
Structuring All Project Code with Tree-sitter for RLM-Powered QA
Introduction
Recently, I learned about a method called "RLM" and experimented with adapting it for QA targeting source code, so I've written this article.
The implementation is published below.
What is RLM?
RLM is a useful technique for handling contexts that are too large for an LLM to process, or for mitigating the drop in accuracy when large amounts of context are input.
The processing flow is as follows:
As you can see from the flow above, the context is NOT passed to the LLM (it is stored in variables of the Python REPL environment). The LLM itself explores and analyzes which parts of the context to look at and how to summarize them. Therefore, even with a context of enormous token size, it is possible to extract information.
Also, unlike standard RAG which retrieves the top N results via vector search, this method can flexibly handle cases requiring searches based on relationships between pieces of information or complex conditions, rather than simple searches.
Note: Since context analysis uses Python code, accuracy heavily depends on the code generation capability of the LLM.
- Paper
What is Tree-sitter?
Tree-sitter is a tool for parsing programming languages, markup languages, etc. Parsed code is represented as a data structure called AST (Abstract Syntax Tree) nodes, which have parent-child relationships.
AST nodes have type names such as classes, functions, arguments, variables, etc. When extracting specific definitions (classes, functions, etc.) from code, you can specify this type name to extract the corresponding code part (each language has its own syntax rules, and the AST node type names differ).
This time, I use it to structure source code into JSON for easier analysis with RLM.
Note: Strictly speaking, Tree-sitter produces a CST (Concrete Syntax Tree), but here we treat it as an AST.
About codetwine
The codetwine tool was created to adapt RLM-based search, Graph RAG, Agentic RAG, etc., for source code. By specifying a project directory, it analyzes the source code within, creates detailed design documents, and saves them as a single JSON file as structured knowledge.
The detailed behavior is as follows (please refer to README.md for schema information and supplementary notes).
Processing steps of codetwine
Step 1: Build the dependency graph of the entire project
- Collect source files with supported extensions from the target directory.
- Scan the collected source files, analyze
importstatements, and identify file-to-file dependencies.
Step 2: Detect changed files
- Compare the hash of source files with the previous output to identify changed files that need reprocessing.
Step 3: Extract dependency information for each file
- Generate a syntax tree using tree-sitter and extract definitions (functions, classes, etc.).
- Based on the dependency graph built in step 1, extract the called and calling files, line numbers, and source code.
Step 4: Generate detailed design documents using an LLM
- Arrange files so that "dependencies → dependents" order is followed, processing from files with no dependencies to their dependents (using topological sort).
- Pass the source code, dependency information, and document summaries of the called files to the LLM, and generate a detailed design document following the template (
doc_template.json). - Create a document summary for each file. This summary is included as input when generating the detailed design document for subsequent files (dependents), allowing the LLM to understand the processing and role of dependency files.
Step 5: Save the created detailed design documents and structured information as JSON
- Saved to
<output directory>/<project name>. - All dependencies and design documents are consolidated into a single JSON file (
project_knowledge.json). - For readability, the dependency graph and detailed design documents are also output in Markdown.
Note:
- Detailed design documents are created to improve the accuracy of keyword searches.
- The LLM is only used in step 4 when generating "detailed design documents" and "summaries." The LLM is not used in other steps. You can disable the generation feature (LLM usage) with the setting (
ENABLE_LLM_DOC="False").
Output files
Multiple files are output, but the basic assumption is to only use project_knowledge.json (since all information is consolidated).
| File | Description |
|---|---|
project_knowledge.json |
JSON consolidating all file dependencies and design documents |
project_dependency_summary.json |
Consolidated JSON of the dependency graph + summary per file |
dependency_graph.md |
Dependency graph in Mermaid format |
<filename>/file_dependencies.json |
Definitions and dependency information for each file |
<filename>/doc.json |
Design document for each file (JSON format) |
<filename>/doc.md |
Design document for each file (Markdown format) |
<filename>/<original filename> |
Copy of the original source code |
Supported languages (identified by extension)
- Python
- JavaScript
- TypeScript
- Java
- Kotlin
- C
- C++
Usage
Prerequisites
- Python 3.11 or higher
- Uses the
uvpackage manager. - You need provider credentials (API key, etc.) matching the LLM you plan to use (not required if using a local LLM like Ollama).
Installation
git clone https://github.com/yumeiriowl/codetwine.git
cd codetwine
uv sync --extra examples # The "--extra" option additionally installs "dspy" used for RLM (without it, only the codetwine core dependencies are installed)
Environment setup
# Copy the configuration file
cp .env.example .env
# Edit the configuration file
nano .env # Edit with any editor
Set the following as a quick start.
| Variable | Description |
|---|---|
LLM_API_KEY |
API key for the LLM provider |
LLM_MODEL |
Model name (litellm format) |
LLM_API_BASE |
API base URL (set when using Ollama, Azure, etc.) |
OUTPUT_LANGUAGE |
Output language for design documents (default is "English") |
Note: litellm is currently restricted to version 1.82.6 or lower.
For other options, please refer to the Configuration Options section in the README.
How to run codetwine (structuring source code)
Execution is done via CLI.
uv run main.py --project-dir /path/to/your/project --output-dir /path/to/output
Set the project path to be analyzed in --project-dir, and the output location path in --output-dir.
Note: As a reference, when using Claude sonnet 4.6 to run codetwine on itself (approx. 4000 lines), the API cost was about $3.5.
Executing QA with RLM
Use the JSON structured by codetwine as input data for the RLM to execute QA.
The codetwine/examples directory in the repository contains sample RLM execution code and a pre-structured version of codetwine itself.
- RLM execution code:
codetwine/examples/rlm_qa - Structured codetwine:
codetwine/examples/sample_output
This time, we will try using codetwine/examples/sample_output, which is placed as a sample, as the QA target for the RLM. If you want to try it with your own source code, you will need to structure it first by referring to the "Usage" section above or the README.md.
About the RLM execution environment
This RLM execution uses DSPy's RLM module. It requires the Deno runtime (a sandbox environment for executing Python), so please install it beforehand (for details, please refer to the DSPy documentation).
Example) Deno installation command (for Linux)
curl -fsSL https://deno.land/install.sh | sh
Execution Code
The following is the RLM execution code (2 files) Note: Long, so it's collapsed.
- rlm_qa_agent.py: RLM execution code
rlm_qa_agent.py
import inspect
import json
import os
import subprocess
import sys
import dspy
from dspy.primitives.python_interpreter import PythonInterpreter
import qa_tools
# Main LLM model name to use in RLM
# Examples: "anthropic/<Model>", "openai/<Model>", "gemini/<Model>", "ollama/<Model>"
LLM_MODEL = "anthropic/claude-opus-4-6"
# Sub-LLM model name to use in RLM
SUB_LLM_MODEL = "anthropic/claude-sonnet-4-6"
# API key (obtained from environment variable)
LLM_API_KEY = os.environ.get("LLM_API_KEY", "")
# API base URL (set when using Ollama, Azure, etc.)
# Example: LLM_API_BASE = "http://localhost:11434"
LLM_API_BASE = None
# Output language for the answer
OUTPUT_LANGUAGE = "Japanese"
# Path to the target "project_knowledge.json"
TARGET_JSON_PATH = f"{os.path.dirname(__file__)}/../sample_output/codetwine/project_knowledge.json"
# Prompt template instructing RLM exploration
INSTRUCTIONS_TEMPLATE = """You are an agent that explores a project design document in JSON format.
Operate on the input project_data variable using Python code, and answer the question.
Be sure to write your answer in <<<RLM_OUTPUT_LANGUAGE>>>.
## Important Rules
**Do not print() the entire project_data**: The data is too large and output will be truncated. Only extract and print() the necessary parts.
## Investigation Rules
- Before answering, be sure to verify the content against the actual source code. Do not answer based solely on memory or speculation.
- Use `definitions[].context` to verify the source code of a specific function/class
- If you need the content of an entire file, use `read_source_file(file_path)`
- When answering about behavior, logic, or data flow, read the relevant code and confirm that the implementation matches your answer
- If the information is not found in the codebase, say so. Never fabricate or speculate.
## JSON Schema
### Top Level
- `project_name` (str): Project name
- `project_dependencies` (array): Dependency graph of the entire project (for understanding overall structure and finding entry points)
- `files` (array): Detailed information per file (dependency details, design documents, source code)
### project_dependencies[]
- `file` (str): File path
- `summary` (str|null): File summary (null if not yet generated)
- `callers` (str[]): Files that call this file (dependents)
- `callees` (str[]): Files that this file calls (dependencies)
### files[]
- `file` (str): File path
- `file_dependencies` (object): Dependency details
- `doc` (object): Design document
### file_dependencies.definitions[]
- `name` (str): Function/class name
- `type` (str): Type of definition ("function_definition", "class_definition", etc.)
- `start_line` (int): Start line number (1-indexed)
- `end_line` (int): End line number (1-indexed)
- `context` (str): Full source code of the definition
### file_dependencies.callee_usages[] (Dependencies used by this file)
- `lines` (int[]): Line numbers where it is used within this file
- `name` (str): Name of the function/class being used
- `from` (str): File path of the dependency
- `target_context` (str): Full source code of the dependency's function/class
### file_dependencies.caller_usages[] (Callers using this file)
- `lines` (int[]): Line numbers where it is used in the caller file
- `name` (str): Name of the function/class being used
- `file` (str): File path of the caller
- `usage_context` (str): Source code of the usage location in the caller
### doc
- `summary` (str): File summary
- `sections` (array): Array of design document sections. Each element has `id` (str), `title` (str), `content` (str)
<<<DOC_SCHEMA>>>
## Code Examples
### Keyword Search (across all fields)
```python
keyword = "search term"
kw = keyword.lower()
for f in project_data["files"]:
fp = f["file"]
deps = f["file_dependencies"]
if kw in f["doc"]["summary"].lower():
print(f"summary: {fp}")
for s in f["doc"]["sections"]:
if kw in s["content"].lower():
print(f"section: {fp} / {s['title']}")
for d in deps["definitions"]:
if kw in d.get("context", "").lower():
print(f"definition: {fp} / {d['name']}")
for u in deps["callee_usages"]:
if u.get("target_context") and kw in u["target_context"].lower():
print(f"callee: {fp} -> {u['from']} / {u['name']}")
for c in deps["caller_usages"]:
if c.get("usage_context") and kw in c["usage_context"].lower():
print(f"caller: {c['file']} -> {fp} / {c['name']}")
```
### Finding Entry Points and Investigating Dependencies
```python
# Find entry points
entry_points = [f["file"] for f in project_data["project_dependencies"] if not f["callers"]]
print(entry_points)
# Investigate dependencies and dependents of a specific file
target = [f for f in project_data["files"] if "module_name" in f["file"]][0]
print("Dependencies:", [(u["from"], u["name"]) for u in target["file_dependencies"]["callee_usages"]])
print("Dependents:", [(c["file"], c["name"]) for c in target["file_dependencies"]["caller_usages"]])
```
"""
```python
def build_doc_schema(project_data: dict) -> str:
"""
Dynamically extracts the list of doc sections from the actual project_knowledge.json data
and generates text to be embedded in the instructions.
Args:
project_data: Loaded project_knowledge.json data
Returns:
Text listing the doc sections
"""
sections = []
for file_entry in project_data.get("files", []):
doc = file_entry.get("doc", {})
if doc.get("sections"):
sections = doc["sections"]
break
section_rows = [f"| `{s['id']}` | {s['title']} |" for s in sections]
section_table = "| id | title |\n|---|---|\n" + "\n".join(section_rows)
return "**List of doc.sections for this project (content is described in the content field of each section):**\n" + section_table
def load_project(json_path: str):
"""Load project_knowledge.json and set variables in the qa_tools module.
Args:
json_path: File path to project_knowledge.json
"""
with open(json_path, "r", encoding="utf-8") as f:
qa_tools.project_data = json.load(f)
qa_tools.base_dir = os.path.dirname(json_path)
print(f"[OK] Loaded project '{qa_tools.project_data['project_name']}' with {len(qa_tools.project_data['files'])} files")
def create_interpreter() -> PythonInterpreter:
"""Create a PythonInterpreter with --node-modules-dir=false and --allow-read configured for Deno 2.x.
Returns:
PythonInterpreter: Interpreter with Deno command set
"""
# Get runner.js path
primitives_dir = os.path.dirname(inspect.getfile(PythonInterpreter))
runner_path = os.path.join(primitives_dir, "runner.js")
# Identify Deno cache directory
deno_dir = os.environ.get("DENO_DIR")
if not deno_dir:
try:
result = subprocess.run(
["deno", "info", "--json"],
capture_output=True, text=True, check=False,
)
if result.returncode == 0:
deno_dir = json.loads(result.stdout).get("denoDir")
except FileNotFoundError:
pass
if not deno_dir:
deno_dir = os.path.expanduser("~/.cache/deno")
# Set DENO_DIR environment variable
os.environ["DENO_DIR"] = deno_dir
deno_command = [
"deno", "run",
"--node-modules-dir=false",
f"--allow-read={runner_path},{deno_dir}",
runner_path,
]
return PythonInterpreter(deno_command=deno_command)
def create_qa_agent(json_path: str) -> dspy.RLM:
"""
Create a dspy.RLM-based Q&A agent.
Args:
json_path: Path to project_knowledge.json
Returns:
Configured dspy.RLM instance
"""
# Load project data
load_project(json_path)
# Initialize LLMs
lm = dspy.LM(LLM_MODEL, api_key=LLM_API_KEY, api_base=LLM_API_BASE)
sub_lm = dspy.LM(SUB_LLM_MODEL, api_key=LLM_API_KEY, api_base=LLM_API_BASE)
# Build instructions by embedding doc schema and output language into template
doc_schema = build_doc_schema(qa_tools.project_data)
instructions = (
INSTRUCTIONS_TEMPLATE
.replace("<<<DOC_SCHEMA>>>", doc_schema)
.replace("<<<RLM_OUTPUT_LANGUAGE>>>", OUTPUT_LANGUAGE)
)
# Create Signature and PythonInterpreter
signature = dspy.Signature(
"project_data, question -> answer",
instructions,
)
interpreter = create_interpreter()
# Create RLM agent
rlm = dspy.RLM(
signature,
tools=[
qa_tools.read_source_file,
qa_tools.get_files_using,
qa_tools.graph_search,
],
verbose=True,
sub_lm=sub_lm,
interpreter=interpreter,
)
# Set LM at module level
rlm.set_lm(lm)
return rlm
def ask(rlm: dspy.RLM, question: str) -> str:
"""
Answer a question using dspy.RLM.
Args:
rlm: dspy.RLM instance
question: User's question
Returns:
Answer text
"""
result = rlm(
project_data=qa_tools.project_data,
question=question,
)
return result.answer
def main():
"""Run interactive session with RLM agent"""
json_path = TARGET_JSON_PATH
if not os.path.exists(json_path):
print(f"Error: {json_path} not found.")
print("Please run `uv run python main.py` first.")
sys.exit(1)
# Initialize RLM agent
print(f"Loading: {json_path}")
rlm = create_qa_agent(json_path)
print("\n[OK] Initialization complete")
print("\nEnter your question (type 'exit', 'quit', or 'q' to quit)\n")
# Interaction loop
try:
while True:
try:
question = input("> ")
if question.lower() in ("exit", "quit", "q"):
break
if not question.strip():
continue
print("\nProcessing...\n")
answer = ask(rlm, question)
print(f"{answer}\n")
except KeyboardInterrupt:
break
finally:
# Shutdown PythonInterpreter (Deno process)
if rlm._interpreter is not None:
rlm._interpreter.shutdown()
if __name__ == "__main__":
main()
- qa_tools.py: Tool set called by RLM
qa_tools.py
import os
from collections import deque
# Module variables set by load_project() (referenced from tool functions)
project_data = None # Entire project_knowledge.json
base_dir = None # Base directory for source files
def read_source_file(path: str) -> str:
"""
Read the source file copied to the output directory.
Args:
path: Path as listed in the JSON file field
(e.g., "code_anarizer/extract_imports/extract_imports.py")
Returns:
String containing the file content. Error message on failure.
Usage:
# Example: Get the line number of a function definition from JSON and extract that part
file_entry = [f for f in project_data["files"] if "extract_imports" in f["file"]][0]
defn = [d for d in file_entry["file_dependencies"]["definitions"] if d["name"] == "extract_imports"][0]
code = read_source_file(file_entry["file"])
lines = code.split("\\n")
function_code = "\\n".join(lines[defn["start_line"]-1:defn["end_line"]])
print(function_code)
"""
if base_dir is None:
return "Error: base_dir not initialized. Call load_project() first."
# Remove project_name/ prefix from file field
project_name = project_data.get("project_name", "")
if project_name and path.startswith(project_name + "/"):
path = path[len(project_name) + 1:]
full_path = os.path.join(base_dir, path)
try:
with open(full_path, "r", encoding="utf-8") as f:
return f.read()
except Exception as e:
return f"Error reading {path}: {e}"
def get_files_using(target_file: str) -> list:
"""
Get files that depend on the specified file (dependents).
Scans callee_usages of all files and collects entries where the from field partially matches target_file.
Args:
target_file: File path to search for (partial match)
Returns:
List in the form [{"file": str, "usage": dict}, ...]
Usage:
users = get_files_using("ts_parser/ts_parser.py")
for u in users:
print(f"{u['file']} uses {u['usage']['name']}")
"""
results = []
for file_entry in project_data["files"]:
for usage in file_entry.get("file_dependencies", {}).get("callee_usages", []):
if target_file in usage.get("from", ""):
results.append({
"file": file_entry["file"],
"usage": usage
})
return results
def graph_search(name: str, hops: int = 1, direction: str = "both") -> dict:
"""
Perform BFS (breadth-first search) for dependency relationships within N hops from the specified definition name.
Treats definitions as nodes and dependencies as edges.
Args:
name: Definition name (searched by exact match, falls back to partial match if not found)
hops: Number of hops to search (1=direct dependencies only, 2=up to dependencies of dependencies)
direction: "outgoing" (dependencies), "incoming" (dependents), "both" (both)
Returns:
{
"start": "file:name", # Start node
"hops": int,
"direction": str,
"nodes": [ # List of discovered definitions
{"key": "file:name", "file": str, "name": str, "type": str,
"hop": int, "via": "outgoing"|"incoming"}
],
"edges": [ # List of edges
{"source": "file:name", "target": "file:name", "hop": int}
]
}
Usage:
# Search direct dependencies and dependents of extract_imports (1 hop)
result = graph_search("extract_imports", hops=1, direction="both")
for r in result["nodes"]:
print(f" hop {r['hop']}: {r['key']} ({r['via']})")
# Search only dependents within 2 hops of node_text
result = graph_search("node_text", hops=2, direction="incoming")
for r in result["nodes"]:
print(f" hop {r['hop']}: {r['name']} in {r['file']}")
"""
if project_data is None:
return {"error": "project_data not loaded. Call load_project() first."}
# File data index (for searching by file path)
file_index = {f["file"]: f for f in project_data["files"]}
# Search for start definition (exact match -> partial match fallback)
candidates = []
for f in project_data["files"]:
for d in f.get("file_dependencies", {}).get("definitions", []):
if d["name"] == name:
candidates.append({"file": f["file"], "definition": d})
if not candidates:
for f in project_data["files"]:
for d in f.get("file_dependencies", {}).get("definitions", []):
if name.lower() in d["name"].lower():
candidates.append({"file": f["file"], "definition": d})
if not candidates:
return {"error": f"Definition '{name}' not found"}
start_file = candidates[0]["file"]
start_def = candidates[0]["definition"]
start_key = f"{start_file}:{start_def['name']}"
# BFS search
visited = {start_key}
queue = deque([(start_key, start_file, start_def["name"], 0)])
nodes = []
edges = []
seen_edges = set()
while queue:
current_key, current_file, current_name, current_hop = queue.popleft()
if current_hop >= hops:
continue
file_data = file_index.get(current_file)
if not file_data:
continue
deps = file_data.get("file_dependencies", {})
# Get line range of current definition
current_def = None
for d in deps.get("definitions", []):
if d["name"] == current_name:
current_def = d
break
next_hop = current_hop + 1
# Outgoing: other definitions used by this definition (callee_usages)
if direction in ("outgoing", "both"):
for usage in deps.get("callee_usages", []):
# Check if usage line is within the current definition's line range
if current_def:
in_range = any(
current_def["start_line"] <= line <= current_def["end_line"]
for line in usage.get("lines", [])
)
elif current_name == "__module__":
all_defs = deps.get("definitions", [])
in_range = any(
not any(d["start_line"] <= line <= d["end_line"] for d in all_defs)
for line in usage.get("lines", [])
)
else:
in_range = False
if not in_range:
continue
target_file = usage.get("from", "")
target_name = usage.get("name", "")
target_key = f"{target_file}:{target_name}"
# Get type of target definition
target_type = ""
target_file_data = file_index.get(target_file)
if target_file_data:
for d in target_file_data.get("file_dependencies", {}).get("definitions", []):
if d["name"] == target_name:
target_type = d.get("type", "")
break
edge_id = (current_key, target_key, "outgoing")
if edge_id not in seen_edges:
seen_edges.add(edge_id)
edges.append({
"source": current_key,
"target": target_key,
"hop": next_hop
})
if target_key not in visited:
visited.add(target_key)
nodes.append({
"key": target_key,
"file": target_file,
"name": target_name,
"type": target_type,
"hop": next_hop,
"via": "outgoing"
})
queue.append((target_key, target_file, target_name, next_hop))
# Incoming: other definitions that use this definition (caller_usages)
if direction in ("incoming", "both"):
for usage in deps.get("caller_usages", []):
if usage.get("name") != current_name:
continue
source_file = usage.get("file", "")
source_file_data = file_index.get(source_file)
# Identify which definition in the source file is using this
source_name = "__module__"
source_type = ""
if source_file_data:
source_deps = source_file_data.get("file_dependencies", {})
for line in usage.get("lines", []):
for d in source_deps.get("definitions", []):
if d["start_line"] <= line <= d["end_line"]:
source_name = d["name"]
source_type = d.get("type", "")
break
if source_name != "__module__":
break
source_key = f"{source_file}:{source_name}"
edge_id = (source_key, current_key, "incoming")
if edge_id not in seen_edges:
seen_edges.add(edge_id)
edges.append({
"source": source_key,
"target": current_key,
"hop": next_hop
})
if source_key not in visited:
visited.add(source_key)
nodes.append({
"key": source_key,
"file": source_file,
"name": source_name,
"type": source_type,
"hop": next_hop,
"via": "incoming"
})
queue.append((source_key, source_file, source_name, next_hop))
return {
"start": start_key,
"hops": hops,
"direction": direction,
"nodes": nodes,
"edges": edges
}
The above code is placed as a sample in codetwine/examples/rlm_qa (the version in the repository has comments and prompts in English). When trying it out, modify the following configuration values in rlm_qa_agent.py as needed, then execute.
| Configuration Value | Description |
|---|---|
LLM_MODEL |
Main LLM model name used in RLM (default: Claude opus 4.6) |
SUB_LLM_MODEL |
Sub-LLM model name used in RLM (default: Claude sonnet 4.6) |
LLM_API_KEY |
API key (obtained from environment variable) |
LLM_API_BASE |
API base URL (set when using Ollama, Azure, etc.) |
OUTPUT_LANGUAGE |
Output language for answers |
TARGET_JSON_PATH |
Path to the project_knowledge.json output by codetwine (the JSON file aggregating analysis results) |
- Regarding
TARGET_JSON_PATH, the default path points to the "project_knowledge.json" withincodetwine/examples/sample_output(the analysis result of codetwine itself), so there is no need to change it when trying out (If you have analyzed other projects with codetwine, you can specify the path to that project's "project_knowledge.json").
- Execution
cd codetwine
uv run python examples/rlm_qa/rlm_qa_agent.py
Code Points
The processing logic of RLM is implemented as an RLM module in DSPy, so only parameter settings are needed; however, the "instruction prompt" and "callable tools" are created specifically for project_knowledge.json.
About the "Instruction Prompt"
In addition to exploration methods and rules for the agent, INSTRUCTIONS_TEMPLATE provides the schema information of project_knowledge.json, allowing the LLM to understand how to extract information using Python code without putting the JSON file into the context.
About "Callable Tools (qa_tools.py)"
Basically, the LLM autonomously creates Python code, but for tasks requiring accuracy or where creation is difficult, we prepare them and inform the LLM of how to use them.
Specifically, the following three tools:
-
read_source_file: Read the contents of a source file -
get_files_using: Identify detailed usage locations of all files that call the target source code -
graph_search: Graph search for dependency relationships of definitions (classes, functions, etc.)
Treats definitions as nodes and dependency relationships as edges, retrieving information up to N hops (1=direct dependency, 2=depdency of dependency, etc.)
Execution Results
I ran examples/rlm_qa/rlm_qa_agent.py with OUTPUT_LANGUAGE changed to Japanese and all other values at their defaults (the answer will be in Japanese).
By default, it targets the codetwine processing. When trying it out, refer to the "codetwine Processing Steps" section in this article and input your questions.
The following output is the result of inputting "How are design document summaries created and used?".
RLM Agent Exploration Process (the exploration process is printed to the console because the `dspy.RLM` parameter has `verbose=True`)
> 設計書の要約はどのように作成されて利用していますか?
Processing...
2026/04/05 16:56:19 INFO dspy.predict.rlm: RLM iteration 1/20
Reasoning: The question asks: "設計書の要約はどのように作成されて利用していますか?" (How are design document summaries created and used?)
I need to understand:
1. How summaries (doc.summary) are generated
2. How they are used in the project
Let me start by exploring the project structure and finding files related to summary generation.
Code:
```python
# First, let's understand the project structure
print("Project name:", project_data["project_name"])
print("\nFiles count:", len(project_data["files"]))
print("\nFile list:")
for f in project_data["project_dependencies"]:
print(f" {f['file']} - callers: {len(f['callers'])}, callees: {len(f['callees'])}")
```
2026/04/05 16:56:27 INFO dspy.predict.rlm: RLM iteration 2/20
Reasoning: I need to find how design document summaries are created and used. The key files are likely `doc_creator.py` (for creating docs/summaries) and `pipeline.py` (for orchestrating the process). Let me search for "summary" across the codebase.
Code:
```python
# Search for "summary" keyword across the project
keyword = "summary"
kw = keyword.lower()
for f in project_data["files"]:
fp = f["file"]
deps = f["file_dependencies"]
if kw in f["doc"]["summary"].lower():
print(f"summary match: {fp}")
for s in f["doc"]["sections"]:
if kw in s["content"].lower():
print(f"section: {fp} / {s['title']}")
for d in deps["definitions"]:
if kw in d.get("context", "").lower():
print(f"definition: {fp} / {d['name']}")
for u in deps["callee_usages"]:
if u.get("target_context") and kw in u["target_context"].lower():
print(f"callee: {fp} -> {u['from']} / {u['name']}")
for c in deps["caller_usages"]:
if c.get("usage_context") and kw in c["usage_context"].lower():
print(f"caller: {c['file']} -> {fp} / {c['name']}")
```
2026/04/05 16:56:33 INFO dspy.predict.rlm: RLM iteration 3/20
Reasoning: Now I need to look deeper into the key files involved in summary creation and usage:
1. `doc_creator.py` - has functions like `_build_summary_prompt`, `_generate_summary`, `_build_callee_context_summary`
2. `output.py` - has `build_summary_map`, `save_dependency_summary`
3. `pipeline.py` - orchestrates the process
Let me examine the source code of `doc_creator.py` first, focusing on summary-related functions.
Code:
```python
# Look at doc_creator.py definitions related to summary
doc_creator = [f for f in project_data["files"] if "doc_creator" in f["file"]][0]
for d in doc_creator["file_dependencies"]["definitions"]:
if "summary" in d["name"].lower():
print(f"=== {d['name']} (lines {d['start_line']}-{d['end_line']}) ===")
print(d["context"])
print()
```
2026/04/05 16:56:40 INFO dspy.predict.rlm: RLM iteration 4/20
Reasoning: I now understand how summaries are generated in `doc_creator.py`. Now I need to understand:
1. How summaries are used - specifically `build_summary_map` in `output.py` and how the pipeline orchestrates everything
2. How summaries feed back into the process (like `_build_callee_context_summary` using summaries of dependencies)
Let me look at `_generate_file_doc` to understand the full flow, then `output.py`'s summary-related functions, and the pipeline.
Code:
```python
# Look at _generate_file_doc to understand how summary fits in the doc generation flow
doc_creator = [f for f in project_data["files"] if "doc_creator" in f["file"]][0]
for d in doc_creator["file_dependencies"]["definitions"]:
if d["name"] == "_generate_file_doc":
print(f"=== {d['name']} (lines {d['start_line']}-{d['end_line']}) ===")
print(d["context"])
print()
```
2026/04/05 16:56:45 INFO dspy.predict.rlm: RLM iteration 5/20
Reasoning: Now I need to understand how summaries are used after creation. Let me look at:
1. `generate_all_docs` to see the orchestration and how `doc_map` is built
2. `build_summary_map` and `save_dependency_summary` in `output.py`
3. `process_all_files` in `pipeline.py` to see the full flow
Code:
```python
# Look at generate_all_docs
doc_creator = [f for f in project_data["files"] if "doc_creator" in f["file"]][0]
for d in doc_creator["file_dependencies"]["definitions"]:
if d["name"] == "generate_all_docs":
print(f"=== {d['name']} (lines {d['start_line']}-{d['end_line']}) ===")
print(d["context"])
print()
```
2026/04/05 16:56:51 INFO dspy.predict.rlm: RLM iteration 6/20
Reasoning: I need to continue investigating the remaining parts. Let me look at:
1. The rest of `generate_all_docs` to see how doc_map is populated and used
2. `build_summary_map` and `save_dependency_summary` in output.py
3. `process_all_files` in pipeline.py to see how summaries flow through the pipeline
Code:
```python
# Read the full source of generate_all_docs (it was truncated)
doc_creator_file = [f for f in project_data["files"] if "doc_creator" in f["file"]][0]
code = read_source_file(doc_creator_file["file"])
lines = code.split("\n")
# _generate_file_doc ends at 527, generate_all_docs starts at 732
for d in doc_creator_file["file_dependencies"]["definitions"]:
if d["name"] == "generate_all_docs":
print("\n".join(lines[d["start_line"]-1:d["end_line"]]))
```
2026/04/05 16:56:56 INFO dspy.predict.rlm: RLM iteration 7/20
Reasoning: I need to see the rest of `generate_all_docs` and also look at `output.py`'s `build_summary_map` and `save_dependency_summary`, plus `pipeline.py`'s `process_all_files`. Let me get the tail of `generate_all_docs` and the output.py functions.
Code:
```python
# Get the rest of generate_all_docs (from line 850 onwards)
doc_creator_file = [f for f in project_data["files"] if "doc_creator" in f["file"]][0]
code = read_source_file(doc_creator_file["file"])
lines = code.split("\n")
# Print from line 850 to end of generate_all_docs (line 899)
print("\n".join(lines[849:899]))
```
2026/04/05 16:57:02 INFO dspy.predict.rlm: RLM iteration 8/20
Reasoning: Now I need to look at the output.py functions `build_summary_map` and `save_dependency_summary`, and the pipeline.py `process_all_files` to understand how summaries are used after creation. Let me examine those.
Code:
```python
# Look at output.py summary-related functions
output_file = [f for f in project_data["files"] if "output_py/output.py" in f["file"]][0]
for d in output_file["file_dependencies"]["definitions"]:
if "summary" in d["name"].lower():
print(f"=== {d['name']} (lines {d['start_line']}-{d['end_line']}) ===")
print(d["context"])
print("\n")
```
2026/04/05 16:57:06 INFO dspy.predict.rlm: RLM iteration 9/20
Reasoning: Now let me look at `process_all_files` in `pipeline.py` to see how the summaries are used in the overall pipeline, and also check `save_consolidated_json` to understand the final output that includes summaries.
Code:
```python
# Look at pipeline.py process_all_files
pipeline_file = [f for f in project_data["files"] if "pipeline" in f["file"]][0]
for d in pipeline_file["file_dependencies"]["definitions"]:
if d["name"] == "process_all_files":
print(f"=== {d['name']} (lines {d['start_line']}-{d['end_line']}) ===")
print(d["context"])
```
2026/04/05 16:57:12 INFO dspy.predict.rlm: RLM iteration 10/20
Reasoning: Now I have a comprehensive understanding of how summaries are created and used. Let me also check `save_consolidated_json` to see how summaries are embedded in the final consolidated JSON, and look at how `_build_callee_context_summary` is used in section generation to understand the feedback loop. Then I'll compile the answer.
Let me also check the `save_consolidated_json` function to see how summaries end up in the final output.
Code:
```python
# Look at save_consolidated_json in output.py
output_file = [f for f in project_data["files"] if "output_py/output.py" in f["file"]][0]
for d in output_file["file_dependencies"]["definitions"]:
if d["name"] == "save_consolidated_json":
print(f"=== {d['name']} (lines {d['start_line']}-{d['end_line']}) ===")
print(d["context"])
```
2026/04/05 16:57:41 INFO dspy.predict.rlm: RLM iteration 11/20
Reasoning: I now have a comprehensive understanding of how design document summaries are created and used in the codetwine project. Let me compile my answer in Japanese based on all the code I've verified.
Key findings:
1. **Creation**: `_generate_summary` in `doc_creator.py` generates summaries by sending all section contents to the LLM
2. **Prompt building**: `_build_summary_prompt` assembles the prompt with file path, all section contents, and character limit
3. **Dependency context**: `_build_callee_context_summary` uses previously generated summaries of dependency files as context for generating new documents
4. **Topological ordering**: `generate_all_docs` processes files in topological sort order so dependency summaries are available
5. **Usage in pipeline**: `build_summary_map` reads summaries from doc.json, then they're used in `save_dependency_summary` and `save_consolidated_json`
6. **Two output files**: summaries appear in both `project_dependency_summary.json` and `project_knowledge.json`
Code:
```python
answer = """
## 設計書の要約(summary)の作成と利用について
### 1. 要約の作成プロセス
設計書の要約は `doc_creator.py` の `_generate_summary` 関数で作成されます。具体的な流れは以下の通りです:
#### (1) セクション生成後に要約を生成
`_generate_file_doc` 関数内で、各ファイルの設計書セクション(Overview、Definition Design Specifications、Dependency Description、Data Flow、Error Handling)がすべてLLMで生成された後、最後のステップとして要約が生成されます。
#### (2) プロンプトの組み立て(`_build_summary_prompt`)
要約生成用のプロンプトは以下の要素で構成されます:
- 対象ファイルのパス
- 生成済みの全セクションの内容(タイトルと本文)
- テンプレートで定義された要約指示文(`summary_prompt`)
- 最大文字数制限(`SUMMARY_MAX_CHARS`で設定)
- 出力言語の指示
#### (3) LLMによる生成
`llm_client.generate(prompt)` を呼び出し、LLMが全セクション内容を要約した短いテキストを返します。失敗時は `None` を返し、空文字列として扱われます。
### 2. トポロジカルソートによる依存順序の処理
`generate_all_docs` 関数は、プロジェクトの依存グラフをトポロジカルソートし、レベル(深さ)ごとにファイルを処理します。依存先がないファイル(レベル0)から順に処理し、生成済みの設計書を `doc_map`(キー:ファイル相対パス、値:設計書dict `{file, sections, summary}`)に蓄積します。
### 3. 要約の利用方法
#### (a) 依存先ファイルのコンテキストとして利用(作成時のフィードバック)
`_build_callee_context_summary` 関数が、`doc_map` から依存先ファイルの要約テキストのみを取得し、セクション生成プロンプトのコンテキストとして付加します。これにより、上位レベルのファイルの設計書生成時に、依存先の概要を参照できます。`compact=True` の場合は各要約を先頭100文字に切り詰めた簡易版も生成され、コンテキストウィンドウ超過時のフォールバックとして使われます。
#### (b) `build_summary_map` による一括読み込み(パイプラインでの利用)
`pipeline.py` の `process_all_files` 関数内で、設計書生成完了後に `output.py` の `build_summary_map` が呼ばれます。この関数は各ファイルの `doc.json` から要約を読み取り、`{ファイル相対パス: 要約テキスト or None}` の辞書を返します。
#### (c) `save_dependency_summary` による軽量JSON出力
`summary_map` とシンボルレベルの依存情報を組み合わせて、`project_dependency_summary.json` として出力します。各ファイルのエントリに `file`、`summary`、`callers`、`callees` が含まれます。
#### (d) `save_consolidated_json` によるプロジェクト全体の統合JSON出力
`project_knowledge.json` として、プロジェクト全体の分析結果を1つのJSONに統合します。この中の `project_dependencies` 配列の各エントリに要約が付与され、また `files` 配列内の各ファイルの `doc` オブジェクトにも要約が含まれます。
#### (e) 変更検知時の完全性チェック
`_is_doc_complete` 関数で、既存の設計書に要約が存在するかをチェックし、要約が空の場合は不完全とみなしてLLMによる再生成の対象となります。
### まとめ
設計書の要約は、LLMが全セクション内容を基に文字数制限付きで生成し、(1) 後続ファイルの設計書生成時の依存先コンテキストとして、(2) プロジェクト全体の依存グラフ+要約の軽量JSON(`project_dependency_summary.json`)として、(3) 全分析結果を統合した `project_knowledge.json` のメタデータとして利用されています。
"""
SUBMIT(answer)
```
## 設計書の要約(summary)の作成と利用について
### 1. 要約の作成プロセス
設計書の要約は `doc_creator.py` の `_generate_summary` 関数で作成されます。具体的な流れは以下の通りです:
#### (1) セクション生成後に要約を生成
`_generate_file_doc` 関数内で、各ファイルの設計書セクション(Overview、Definition Design Specifications、Dependency Description、Data Flow、Error Handling)がすべてLLMで生成された後、最後のステップとして要約が生成されます。
#### (2) プロンプトの組み立て(`_build_summary_prompt`)
要約生成用のプロンプトは以下の要素で構成されます:
- 対象ファイルのパス
- 生成済みの全セクションの内容(タイトルと本文)
- テンプレートで定義された要約指示文(`summary_prompt`)
- 最大文字数制限(`SUMMARY_MAX_CHARS`で設定)
- 出力言語の指示
#### (3) LLMによる生成
`llm_client.generate(prompt)` を呼び出し、LLMが全セクション内容を要約した短いテキストを返します。失敗時は `None` を返し、空文字列として扱われます。
### 2. トポロジカルソートによる依存順序の処理
`generate_all_docs` 関数は、プロジェクトの依存グラフをトポロジカルソートし、レベル(深さ)ごとにファイルを処理します。依存先がないファイル(レベル0)から順に処理し、生成済みの設計書を `doc_map`(キー:ファイル相対パス、値:設計書dict `{file, sections, summary}`)に蓄積します。
### 3. 要約の利用方法
#### (a) 依存先ファイルのコンテキストとして利用(作成時のフィードバック)
`_build_callee_context_summary` 関数が、`doc_map` から依存先ファイルの要約テキストのみを取得し、セクション生成プロンプトのコンテキストとして付加します。これにより、上位レベルのファイルの設計書生成時に、依存先の概要を参照できます。`compact=True` の場合は各要約を先頭100文字に切り詰めた簡易版も生成され、コンテキストウィンドウ超過時のフォールバックとして使われます。
#### (b) `build_summary_map` による一括読み込み(パイプラインでの利用)
`pipeline.py` の `process_all_files` 関数内で、設計書生成完了後に `output.py` の `build_summary_map` が呼ばれます。この関数は各ファイルの `doc.json` から要約を読み取り、`{ファイル相対パス: 要約テキスト or None}` の辞書を返します。
#### (c) `save_dependency_summary` による軽量JSON出力
`summary_map` とシンボルレベルの依存情報を組み合わせて、`project_dependency_summary.json` として出力します。各ファイルのエントリに `file`、`summary`、`callers`、`callees` が含まれます。
#### (d) `save_consolidated_json` によるプロジェクト全体の統合JSON出力
`project_knowledge.json` として、プロジェクト全体の分析結果を1つのJSONに統合します。この中の `project_dependencies` 配列の各エントリに要約が付与され、また `files` 配列内の各ファイルの `doc` オブジェクトにも要約が含まれます。
#### (e) 変更検知時の完全性チェック
`_is_doc_complete` 関数で、既存の設計書に要約が存在するかをチェックし、要約が空の場合は不完全とみなしてLLMによる再生成の対象となります。
### まとめ
設計書の要約は、LLMが全セクション内容を基に文字数制限付きで生成し、(1) 後続ファイルの設計書生成時の依存先コンテキストとして、(2) プロジェクト全体の依存グラフ+要約の軽量JSON(`project_dependency_summary.json`)として、(3) 全分析結果を統合した `project_knowledge.json` のメタデータとして利用されています。
The agent successfully explored across multiple files in the project and accurately answered the entire flow from summary creation to usage. You can check the detailed process (Python-based exploration) that led to the answer in the "RLM Agent Exploration Process" section above.
Here are the costs:
RLM iteration count: 11 (max 20)
Exploration time: 1m22s
API cost: 0.66$
Regarding cost, we expect it will not vary significantly even for repositories and projects other than codetwine.
Since RLM does not pass the context itself to the LLM but instead builds the answer through exploration using Python code, even if the number of source code files or lines increases, the cost can remain almost constant as long as the LLM's exploration efficiency is sufficient.
However, conversely, it is affected by the LLM's coding performance (Python), and even a small amount of source code incurs a certain cost for exploration.
Therefore, from a cost-performance perspective, it is best to target source code of several thousand lines or more with a model that has high coding ability (such as Claude Sonnet 4.6 or Claude Opus 4.6).
- Depending on the scattering of related information across multiple files and the complexity of the question, the exploration scope may widen and costs may increase (this is heavily influenced by the LLM's coding performance and exploration efficiency).
Conclusion
In this article, I tried adapting RLM for source code.
The idea comes from the same concept as my previous article — that structured source code is easier to search.
RLM searches autonomously (using Python), but I thought that similarly, passing the data as a JSON rather than raw code makes it easier to grasp as a fixed format, and by teaching the schema in advance, we can improve search accuracy.
While there is the overhead of structuring the source code, once done, QA can be performed at an almost constant speed (codetwine supports incremental updates for changes, so when the source code is modified, only the differences are regenerated upon re-execution).
If you are interested, please give it a try.
Thank you for reading this far.
I hope to see you again next time.
References
Discussion