We are going to design an AI-assisted codebase documentation generator that incorporates:
- Embedding strategies: to convert code into vector representations for semantic search.
- Chunk linking: to link related chunks of code and documentation.
- Human validation loops: to involve developers in validating and improving the generated documentation.
- Freshness guarantees: to ensure the documentation stays up-to-date with code changes.
We'll break down the system into components and describe the workflow.
Components:
- Code Parser and Chunker
- Embedding Model
- Vector Database
- Documentation Generator (using an LLM)
- Chunk Linker
- Human Validation Interface
- Freshness Monitor
Workflow:
Step 1: Parsing and Chunking
- Parse the codebase (support multiple languages) and break it into meaningful chunks (e.g., functions, classes, modules).
- For each chunk, extract:
- Code snippet
- Context (file path, surrounding code, imports, etc.)
- Metadata (language, author, creation date, etc.)
Step 2: Embedding and Storage
- Use an embedding model (e.g., OpenAI's text-embedding-ada-002, or an open-source alternative) to convert each chunk (code and possibly existing comments) into a vector.
- Store the vector along with the chunk's metadata in a vector database (e.g., Pinecone, Weaviate, or pgvector).
Step 3: Initial Documentation Generation
- For each code chunk, use an LLM (e.g., GPT-4) to generate documentation (e.g., docstrings, comments, README snippets) by providing:
- The code chunk
- Context from the vector database (similar chunks or related code)
- Instructions (e.g., "Write a docstring for this function in the style of Google")
- Store the generated documentation along with the chunk and a flag indicating it's AI-generated and pending validation.
Step 4: Chunk Linking
- Build a graph of chunks based on:
- Code references (function calls, imports, inheritance)
- Semantic similarity (embedding similarity)
- Co-occurrence in the same file or module
- Store these links in a graph database (e.g., Neo4j) or as edges in the vector database (if supported) or in a relational database.
Step 5: Human Validation Loop
- Provide an interface (web or IDE plugin) for developers to review AI-generated documentation.
- For each code chunk, show:
- The code
- The generated documentation
- Links to related chunks (from the chunk linker)
- Allow the developer to:
- Approve the documentation.
- Edit the documentation.
- Reject the documentation (and optionally provide a reason).
- When a developer edits, use the edited version as the new documentation and mark it as human-validated.
- Periodically, retrain the embedding model (or fine-tune) on the approved documentation to improve future generations.
Step 6: Freshness Guarantees
- Monitor the codebase for changes (using git hooks, CI/CD integration, or periodic scans).
- When a code chunk is modified:
- Flag the associated documentation as stale.
- Re-run the documentation generation for that chunk (and possibly for linked chunks if the change might affect them).
- Push the new documentation for validation (if the change is significant) or automatically update if the change is minor and the previous documentation was human-validated (with a confidence threshold).
- Also, schedule periodic re-validation of documentation that hasn't been touched in a while (e.g., every 6 months) to catch drift.
Step 7: Querying and Retrieval
- When a developer searches for documentation (via IDE plugin or web interface):
- Use the vector database to find relevant chunks by semantic search.
- Use the chunk links to expand the context (e.g., show related functions, classes).
- Return the documentation (prioritizing human-validated, then AI-generated with high confidence, then stale ones with a warning).
Additional Considerations:
- Multi-language support: The chunker and embedding model must handle multiple programming languages. We might use language-specific parsers (e.g., tree-sitter) and then a universal embedding model.
- Scalability: The system must scale with the codebase size. We can use incremental updates (only process changed files) and efficient vector search.
- Privacy: If using external LLMs, ensure code is not leaked. Consider on-premise LLMs for sensitive codebases.
Implementation Outline:
-
Set up a vector database (e.g., Pinecone) with an index for code chunks.
-
Build a code parser for each supported language (or use a unified parser like tree-sitter). We can use existing tools like ast for Python, javaparser for Java, etc.
-
Create a chunking strategy that respects language semantics (e.g., a function, a class, a module). We might also allow configuration for chunk size (e.g., 50 lines) for languages that are more script-like.
-
For each chunk, generate an embedding and store in the vector database with metadata (file path, chunk type, start line, end line, language, etc.).
-
Build a service that, given a code chunk (or a query), uses the LLM to generate documentation. Use few-shot prompting with examples of good documentation (from human-validated ones) to improve quality.
-
Implement a chunk linker that:
a. Extracts references (e.g., for Python, use ast to get function calls, imports, etc.) and creates directed edges.
b. Computes embedding similarity between chunks and creates edges for top-N similar (above a threshold).
-
Build a human validation interface. This could be a web app that shows a list of pending validations, or an IDE plugin that shows the generated docstring next to the code and allows editing.
-
Set up a freshness monitor:
a. Listen to git events (e.g., via webhooks) or poll the repository for changes.
b. When a file changes, re-chunk the changed parts and update the vector database (remove old chunks, add new ones). Also, re-run documentation generation for the new chunks and for any chunk that links to the changed chunk (if the change might affect the meaning of the linked chunk).
c. Invalidate the documentation of the changed chunks (and possibly linked ones) until re-validated.
-
Query service: Given a natural language query or a code reference, retrieve relevant chunks and their documentation.
-
Analytics: Track the validation rate, the time taken for validation, and the quality of AI-generated documentation (by comparing with human-edited versions) to improve the system.
This is a high-level design. Each component can be expanded with more details.
Let's write the code for a minimal prototype that demonstrates the core concepts.
We'll focus on:
- Python code only for simplicity.
- Use a simple chunking strategy (by function and class).
- Use OpenAI's embedding and GPT-3.5/4 for generation.
- Use a vector database (we'll use Pinecone for example, but can be replaced).
- Store linked chunks in a simple in-memory graph for now (or use a dictionary of edges).
Steps in code:
- Parse a Python file and break into chunks (functions and classes).
- Generate embeddings for each chunk (code string) and store in Pinecone.
- For each chunk, generate documentation using GPT.
- Build a graph: for each function call within a chunk, link to the chunk that defines that function (if in the same codebase). Also, link by embedding similarity.
- Provide a simple CLI or web interface for validation.
However, note that building a full system is beyond a single code response. We'll outline the key functions and classes.
Let's create:
class CodeChunk:
file_path: str
start_line: int
end_line: int
code: str
language: str
chunk_type: str # 'function', 'class', 'module', etc.
embedding: list[float] # will be stored in vector DB
documentation: str # generated or validated
status: str # 'ai_generated', 'human_validated', 'stale'
links: list[str] # list of chunk ids that this chunk links to
class CodebaseParser:
def parse_file(file_path: str) -> list[CodeChunk]
class EmbeddingService:
def get_embedding(text: str) -> list[float]
class VectorDB:
def upsert(chunks: list[CodeChunk])
def query(query_embedding: list[float], top_k: int) -> list[CodeChunk]
class DocumentationGenerator:
def generate_doc(chunk: CodeChunk, context_chunks: list[CodeChunk]) -> str
class ChunkLinker:
def build_links(chunks: list[CodeChunk]) -> dict[str, list[str]]
class FreshnessMonitor:
def on_code_change(changed_files: list[str]):
# re-parse changed files, update chunks, invalidate documentation, regenerate if needed.
class ValidationInterface:
def get_pending_validations() -> list[CodeChunk]
def validate(chunk_id: str, new_doc: str) -> None
We'll also need a way to track chunk IDs (maybe hash of file_path+start_line+end_line).
However, note that when code changes, the chunk might shift. So we need a more robust way to track chunks across changes?
Alternatively, we can use the content hash to identify chunks? But if the content changes, it's a new chunk.
Let's assume we use (file_path, start_line, end_line) as a primary key for a chunk version. When a file changes, we remove the old chunks for that file and add new ones.
But note: if a function is moved, the start_line and end_line change, but the function is the same. We might want to track by function name and context? That's complex.
For simplicity, we'll assume that when a file changes, we re-chunk the entire file and replace all chunks for that file.
Implementation of the parser for Python:
Use the ast module to parse and extract function and class definitions.
Example:
import ast
def parse_python_file(file_path):
with open(file_path) as f:
tree = ast.parse(f.read())
chunks = []
for node in ast.walk(tree):
if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)):
chunk = CodeChunk(
file_path=file_path,
start_line=node.lineno,
end_line=node.end_lineno,
code=ast.get_source_segment(source, node), # we need the source string
language='python',
chunk_type='function' if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)) else 'class',
)
chunks.append(chunk)
return chunks
But note: ast.get_source_segment requires the source string and the node. We have to keep the source string.
Alternatively, we can use asttokens or inspect but for simplicity, we assume we have the source.
Actually, we can read the file and then use ast.parse and ast.get_source_segment if we have the source.
However, note that the node.lineno and node.end_lineno are 1-indexed.
Also, we might want to include the entire module as a chunk? Maybe for module-level docstrings.
We'll stick to functions and classes for now.
We'll also want to extract the function signature and the docstring if present.
But for the embedding, we might use the entire function code (including signature and body).
For the documentation generation, we might only need the signature and the body? But the embedding should capture the entire function.
We'll store the entire code snippet for the chunk.
Now, the embedding:
We'll use OpenAI's embedding. We have to consider the token limit (8192 for ada-002). Our chunks should be within that.
For the documentation generation, we'll use GPT-4 (or 3.5) and prompt:
You are an expert software engineer. Write a detailed docstring for the following {chunk_type} in the style of Google.
Code:
{code}
Context (similar code in the project):
{context_code}
Docstring:
We'll provide context by retrieving similar chunks from the vector database (using the embedding of the current chunk) and including their code and existing documentation (if any) as context.
But note: we are generating for the first time, so existing documentation might be none. We can still provide similar code without documentation.
Chunk Linker:
We'll build two types of links:
1. Static links: by parsing the code for function calls, imports, etc. For a function chunk, we look at the function body and see which functions/classes are called. Then we link to the chunks that define those (if they are in our codebase). We need a symbol table to map from name to chunk. We can build this by indexing all chunks by their qualified name (for classes, the class name and for functions, the function name and the class if it's a method). But note: the same function name might exist in multiple classes. We need to consider the context.
For simplicity, we can build a mapping from (file_path, class_name, function_name) for methods and (file_path, function_name) for functions, and for classes (file_path, class_name). Then when we see a call to `foo.bar()`, we look for a method `bar` in class `foo`? But we don't know the type of `foo`. This is complex without type information.
Alternatively, we can use the embedding similarity to find the most similar chunk that defines the function? That might be error-prone.
Given the complexity, we might skip the static linking for now and rely on embedding similarity for linking? Or we can do a simple text-based linking: if a function name appears in the code of another chunk, link them? But that's too broad.
Let's think: we want to link a function to the functions it calls. We can use the AST to extract the names of called functions and then try to resolve them to chunks by matching the name and the module (if available). We can also consider the imports.
This is a research problem in itself. For a prototype, we can do:
For each function chunk, extract the names of all functions and classes that are called (using ast.Call nodes and ast.Attribute nodes). Then, for each name, look for a chunk that defines a function/class with that name in the same file or in an imported module? But we don't have the full project symbol table.
Alternatively, we can build a project-wide index of all defined functions and classes by their name (and possibly their fully qualified name if we can infer from the file path and class structure). Then when we see a call to `foo()`, we look for a function named `foo` that is in scope. But without a full type system, we cannot be sure.
Given the complexity, we might start with embedding-based linking only.
2. Embedding-based linking: for each chunk, find the top-N most similar chunks (by cosine similarity of embeddings) and create bidirectional links? Or directed? We can start with bidirectional.
We'll store the links in the vector database as metadata? Or in a separate graph database? For simplicity, we can store the links in a dictionary in memory and also in the chunk's metadata (as a list of linked chunk IDs). But then when we update a chunk, we have to update the links of the linked chunks? That might be messy.
Alternatively, we can store the links in a separate graph structure that we update when chunks are updated.
For the prototype, we'll store the links in a separate dictionary:
links = {
chunk_id: [linked_chunk_id1, linked_chunk_id2, ...]
}
And when we re-chunk a file, we remove all links for the old chunks and rebuild for the new ones.
Freshness Monitor:
We can use a simple file watcher (like watchdog) for development. In production, we might use git hooks or CI/CD.
When a file is changed, we re-parse the file, get new chunks, and:
For each new chunk:
- If there's an old chunk with the same (file_path, start_line, end_line) then we consider it an update? But if the code changed, the same line numbers might have different code. So we cannot rely on line numbers.
Instead, we can generate a chunk ID by hashing the code? But if the code changes, the hash changes and it's a new chunk.
Alternatively, we can use the function/class name and the file path? But if the function is moved, the file path changes.
We need a way to track the same logical function across changes. This is a hard problem.
For simplicity, we will treat every parse of a file as producing a new set of chunks. We will delete all old chunks for that file and insert the new ones. Then we will invalidate the documentation for all chunks that are linked (by our link graph) to the changed chunks? Or just the changed ones?
We'll do:
When a file changes:
1. Get the old chunks for that file (from our vector DB) and note their IDs.
2. Parse the file and get new chunks.
3. For each new chunk, generate an embedding and store in the vector DB. The chunk ID will be the hash of (file_path, start_line, end_line, code) or just a random UUID? But we want to be able to track across updates? Actually, we don't need to track across updates if we are going to invalidate and regenerate.
4. We will delete the old chunks from the vector DB and from the link dictionary.
5. Then, for each new chunk, we will:
a. Generate new documentation (AI) and mark as 'ai_generated'.
b. Build links for the new chunk (both static and embedding-based) with other new chunks and existing chunks (from other files that didn't change). But note: the embedding-based links might change because the code changed.
6. We also need to update the links of other chunks that linked to the old chunks? Since we deleted the old chunks, those links are broken. So we should rebuild the entire link graph? That might be expensive.
Alternatively, we can rebuild the entire link graph for the whole codebase periodically (e.g., daily) and on every change rebuild only for the changed file? But the links from other files to the changed file might be broken until the next full rebuild.
We can do:
On file change:
- Re-chunk the file and replace its chunks in the vector DB.
- Recompute the embedding-based links for the new chunks with all other chunks (including the ones from the same file and other files). But that's O(N) for each new chunk? We can do a vector search for each new chunk to find its top-N similar chunks and update the links accordingly.
We also have static links (by symbol) that we can recompute for the changed file. For the static links, we need to update the symbol table for the whole project? Or just for the changed file? Actually, if a function is defined in the changed file, then the calls from other files to that function will still point to the same function (by name) but the chunk ID might change because the line numbers might change. So we need to update the symbol table mapping from function name to chunk ID. We can rebuild the symbol table for the whole project? Or incrementally?
Given the complexity, we might start with only embedding-based links and rebuild the entire graph periodically (or on every change for the changed file, but then we have to update the links of other chunks that point to the changed file?).
Let's simplify: we'll store the links only by chunk ID. When we delete the old chunks, we remove all links that involve those chunks (from the link dictionary). Then we generate new links for the new chunks (with other existing chunks and among themselves). We don't update the links of existing chunks that linked to the old chunks because we removed those links. But then the existing chunks might have broken links? We can either:
Option 1: When we delete old chunks, we also remove all links that point to them from the link dictionary. Then the existing chunks that had links to the old chunks will lose those links. Then we can run a link rebuild for the existing chunks that lost links? Or just leave them with fewer links until the next full rebuild.
Option 2: We rebuild the entire link graph for the whole codebase on every change? That might be too heavy.
We'll go with Option 1 for now.
Steps for freshness on file change:
1. Identify the file that changed.
2. Query the vector DB for all chunks in that file (old chunks). Get their IDs.
3. Delete these old chunks from the vector DB and from the link dictionary (remove these IDs from all link lists).
4. Parse the file and create new chunks.
5. For each new chunk:
a. Get embedding and upsert into vector DB.
b. Generate documentation (AI) and store with status 'ai_generated'.
6. For each new chunk, find its top-N similar chunks (from the entire vector DB, including the new ones and existing ones) and create bidirectional links? Or directed? We'll do bidirectional for now.
7. Also, if we have static linking (by symbol), we would update the symbol table and then link by symbol. But we are skipping static for now.
8. Now, the existing chunks that had links to the old chunks will have lost those links. We can leave them as is, or we can try to find new links for them? We can run a periodic full rebuild to fix these.
We'll schedule a full rebuild (recompute all links) once a day to fix any broken links.
Human Validation:
We'll have a simple command-line interface that lists all chunks with status 'ai_generated' and allows the user to edit the documentation and mark as validated.
Alternatively, we can build a web interface that shows the code and the generated doc and allows editing.
We'll store the validated documentation in the chunk's record and update the status to 'human_validated'.
We might also want to store the validator's name and timestamp.
Querying:
We'll have a function that takes a natural language query or a code snippet and returns the top-K relevant chunks with their documentation.
Steps:
- Get the embedding of the query.
- Query the vector DB for the top-K chunks (by similarity).
- For each chunk, get its documentation (if human_validated, use that; else if ai_generated, use that; else if stale, still show but mark as stale).
- Also, follow the links (e.g., get the top-3 linked chunks) and include their documentation? We can do a graph traversal.
We can return:
[
{
"chunk": chunk,
"documentation": doc,
"status": status,
"links": [linked_chunk_ids]
}
]
This is a high-level design and a lot of details are omitted.
Let's write some skeleton code for the main components.
We assume:
- We have an OpenAI API key for embeddings and GPT.
- We use Pinecone as the vector DB (but we can abstract it).
We'll create:
- A class for CodeChunk.
- A parser for Python.
- A service for embeddings.
- A service for the vector DB.
- A generator for documentation.
- A linker (for now, only embedding-based).
- A freshness monitor (using watchdog to watch a directory).
- A simple CLI for validation.
However, note that this is a huge project. We'll write a minimal version that demonstrates the idea.
Let's start by setting up the environment and the basic classes.
We'll use:
openai
pinecone
watchdog
But note: we might not want to use Pinecone for a prototype because it requires an account. We can use a local vector DB like chroma or just a simple in-memory list with cosine similarity for small codebases.
For the sake of simplicity in this example, we'll use an in-memory list and compute cosine similarity with numpy.
Steps:
- Parse a Python file and get chunks.
- For each chunk, compute embedding (using OpenAI) and store in a list.
- For each chunk, generate documentation (using OpenAI).
- Build links: for each chunk, compute cosine similarity with every other chunk and keep top 5 (excluding itself).
- When a file changes, re-parse that file and replace its chunks in the list, then rebuild links for those chunks with all others.
We'll also store the links in a dictionary: {chunk_id: [linked_chunk_ids]}
We'll assign a unique ID to each chunk (uuid).
But note: when we re-parse a file, the old chunks are gone and new ones are created. We cannot easily match old and new chunks. So we just remove the old ones and add new ones.
We'll have:
chunks = [] # list of CodeChunk objects
links = {} # dict: chunk_id -> list of chunk_id
When we add a new chunk, we compute its links (top 5 similar from the current list of chunks) and update the links dict.
When we remove chunks (because a file changed), we remove them from the chunks list and from the links dict (and also from the links of other chunks).
We'll also have a separate list for pending validations? Or we can just filter by status.
Let's code accordingly.
However, note: the embedding model and the documentation generator are expensive. We don't want to run them on every change for every chunk? We'll run them on the new chunks.
We'll also have a way to avoid re-generating documentation for a chunk that hasn't changed? But if the context (other chunks) changed, we might want to regenerate? We'll regenerate for new chunks and for chunks that are linked to the changed ones? We'll keep it simple: only new chunks get new AI documentation.
But what if a function that is called by many others changes? The documentation of the callers might still be valid? Or maybe not? We'll leave that for future.
Let's code the basic components.
We'll create:
class CodeChunk:
id: str
file_path: str
start_line: int
end_line: int
code: str
language: str
chunk_type: str
embedding: list[float]
documentation: str
status: str # 'ai_generated', 'human_validated'
created_at: datetime
updated_at: datetime
class CodebaseIndex:
def __init__(self):
self.chunks = [] # list of CodeChunk
self.links = {} # dict: chunk_id -> set of chunk_id
def add_chunk(self, chunk: CodeChunk):
# compute embedding for the chunk if not already computed?
# then find top 5 similar chunks from existing ones and create bidirectional links.
# But note: we are adding one by one? Or we add a list of chunks (from a file) and then link among them and with existing ones.
def remove_chunks(self, chunk_ids: list[str]):
# remove from self.chunks and from self.links
def update_file(self, file_path: str, new_chunks: list[CodeChunk]):
# remove old chunks of this file, then add new ones.
def get_similar_chunks(self, chunk: CodeChunk, top_k=5) -> list[CodeChunk]:
# compute cosine similarity with all other chunks and return top_k.
def rebuild_links_for_chunk(self, chunk: CodeChunk):
# remove old links for this chunk and compute new ones.
def rebuild_links(self):
# rebuild for all chunks (expensive)
But note: when we add a new chunk, we want to link it to existing chunks. Also, when we add multiple chunks from the same file, we might want to link them among themselves? Yes.
We'll do:
When we add a list of new_chunks (from a file):
For each new_chunk in new_chunks:
- Compute its embedding.
- Find top 5 similar chunks from the entire index (including the new_chunks that we are adding? But note: the new_chunks are not yet in the index). So we first add the new_chunks to the index? Then when we compute for the first new_chunk, the other new_chunks are not in the index yet.
We can do:
1. Compute embeddings for all new_chunks.
2. Then for each new_chunk, find top 5 similar from (existing chunks + other new_chunks). But we have to avoid linking to itself and also we want to link to the other new_chunks? Yes.
So we can do:
all_chunks = self.chunks + new_chunks # but note: self.chunks doesn't have the new_chunks yet.
Then for each new_chunk, we compute similarity with all_chunks (excluding itself) and take top 5.
Then we add the new_chunks to self.chunks.
Then we update the links for the existing chunks that might now have new links to the new_chunks? We don't do that automatically. We only set the links for the new_chunks. But the existing chunks won't have links to the new_chunks until we rebuild their links? We can either:
Option A: When we add new_chunks, we also update the links of the existing chunks that are in the top 5 of the new_chunks? But then we have to update the existing chunks' link sets. This might be asymmetric.
Option B: We only set the links from the new_chunks to the existing ones (and among themselves). Then the existing chunks don't have links to the new_chunks until we rebuild their links.
We want bidirectional links? If we want bidirectional, then we should update both sides.
Let's do:
For each new_chunk, we find top 5 similar chunks (from all_chunks, which includes existing and other new). Then we set:
self.links[new_chunk.id] = set( [similar_chunk.id for similar_chunk in top5] )
And also for each similar_chunk in top5, we add new_chunk.id to self.links[similar_chunk.id] (if similar_chunk is an existing chunk, we update its links; if it's a new_chunk, we are already going to set its links when we process it? But we are processing new_chunks one by one, so when we process the first new_chunk, the second new_chunk is not in the index yet? We are using all_chunks which includes all new_chunks, so when we process the first new_chunk, the second new_chunk is in all_chunks but not in self.links yet. We will add the first new_chunk to the second's links when we process the second? That's messy.
Alternatively, we can:
Step 1: Compute embeddings for all new_chunks.
Step 2: Combine existing chunks and new_chunks into a temporary list (all_chunks).
Step 3: For each chunk in all_chunks (both existing and new), compute its top 5 similar from all_chunks (excluding itself) and set its links.
But that would rebuild links for existing chunks too, which might be expensive.
We can do:
We only update the links for the new_chunks and for the existing chunks that are in the top 5 of any new_chunk? But then we might miss that an existing chunk should now link to a new_chunk? Actually, if a new_chunk is similar to an existing chunk, then the existing chunk should also be linked to the new_chunk? That's bidirectional.
Let's do:
For each new_chunk, we find its top 5 similar from all_chunks (existing+new). Then:
self.links[new_chunk.id] = set( [similar.id for similar in top5] )
And for each similar in top5:
if similar.id in self.links:
self.links[similar.id].add(new_chunk.id)
else:
# if similar is a new_chunk that we haven't processed yet, we will set its links later? But we are processing new_chunks in order, so when we process the first new_chunk, the second new_chunk might not be in self.links yet. So we have to initialize self.links for new_chunks as an empty set before the loop? Or we can do:
We can first initialize self.links for all new_chunks as empty sets.
Then for each new_chunk:
compute top5 (from all_chunks, excluding itself)
set self.links[new_chunk.id] = set(top5_ids)
for each top5_id in top5_ids:
self.links[top5_id].add(new_chunk.id)
This way, we update the existing chunks' links (if they are in top5) and also the new_chunks' links (when we process them, we add the new_chunk.id to the existing chunk's links, and when we process a new_chunk that is in the top5 of another new_chunk, we add the other new_chunk.id to its links).
But note: when we process the first new_chunk, the second new_chunk is in all_chunks and might be in the top5 of the first. Then we add the first new_chunk.id to the second new_chunk's links. But when we process the second new_chunk, we set its links to its top5 (which might include the first) and then add the second to the first's links? That would be symmetric.
However, we are adding the first to the second's links when processing the first, and then when processing the second we set its links to its top5 (which includes the first) and then add the second to the first's links? That's redundant but okay.
But note: when we process the first new_chunk, the second new_chunk might not be in self.links yet? We have to initialize self.links for all new_chunks first.
Let's change:
Before the loop, for each new_chunk in new_chunks:
self.links[new_chunk.id] = set()
Then for each new_chunk in new_chunks:
compute top5 from all_chunks (excluding new_chunk itself) -> list of chunk ids
for top5_id in top5_ids:
self.links[new_chunk.id].add(top5_id)
self.links[top5_id].add(new_chunk.id)
This way, we ensure that for every pair of similar chunks (among the new and existing) we have a bidirectional link.
But note: if two existing chunks are already linked, and we add a new_chunk that is similar to both, we are adding the new_chunk to the existing chunks' links, but we are not changing the link between the two existing chunks (which is already there). That's fine.
However, what if an existing chunk is not in the top5 of any new_chunk? Then we don't update its links. That's acceptable because we only care about the new_chunks getting linked.
But what if the new_chunks are so相似 that they are in each other's top5? Then we link them.
This algorithm is O(N^2) for the new_chunks? Actually, for each new_chunk we compare with all_chunks (which is existing_count + new_count). And we do that for each new_chunk. So it's O(new_count * (existing_count + new_count)). If existing_count is large, that's expensive.
We can use the vector database to do approximate nearest neighbor search. But in our in-memory implementation, we are doing exact search.
For a large codebase, we need an approximate method. We'll use Pinecone or similar in production.
For the prototype, we assume small codebase.
Now, the freshness monitor:
We'll use watchdog to monitor a directory for .py file changes.
When a .py file is modified, we:
1. Parse the file and get new_chunks.
2. Call index.update_file(file_path, new_chunks)
The update_file method:
old_chunks = [chunk for chunk in self.chunks if chunk.file_path == file_path]
old_ids = [chunk.id for chunk in old_chunks]
# Remove old chunks and their links
self.remove_chunks(old_ids)
# Then add the new_chunks
for chunk in new_chunks:
chunk.id = str(uuid.uuid4()) # new id
# compute embedding? We'll do in add_chunk?
self.add_chunk(chunk) # this will compute embedding and links.
# Then generate documentation for the new_chunks (using the DocumentationGenerator)
But note: the add_chunk method we described above already computes links for the new_chunk with the existing chunks and other new_chunks. But when we remove the old chunks, the existing chunks' links to the old chunks are removed. Then we add the new_chunks and link them to the existing chunks. So the existing chunks now have links to the new_chunks (if similar) and the new_chunks have links to the existing and to each other.
However, the existing chunks that were linked to the old chunks (which are now gone) will have lost those links. We don't automatically find replacements for those links. We can leave them as is, or we can try to find new links for them? We'll leave them for now.
We'll also generate documentation for the new_chunks. But what about the existing chunks that are linked to the new_chunks? Their documentation might be stale because they call a function that changed? We don't know. We'll leave them as is.
We can also invalidate the documentation of the existing chunks that are linked to the changed file? We can do:
When a file changes, we not only remove the old chunks and add new ones, but also mark all chunks that are linked (directly or indirectly) to the changed file as stale? That might be too aggressive.
Alternatively, we can mark the new_chunks as 'ai_generated' (or if they were human_validated before, we might keep the validation? But the code changed, so the old documentation might be invalid. We'll mark the new_chunks as 'ai_generated' regardless of the old status.
For the existing chunks that are not changed but are linked to the new_chunks, we leave their status as is.
Human Validation:
We'll have a simple loop that prints each ai_generated chunk and allows the user to edit the documentation.
We can do:
for chunk in index.chunks:
if chunk.status == 'ai_generated':
print(f"File: {chunk.file_path}")
print(f"Code:\n{chunk.code}")
print(f"Generated doc:\n{chunk.documentation}")
action = input("(a)pprove, (e)dit, (s)kip: ")
if action == 'a':
chunk.status = 'human_validated'
elif action == 'e':
new_doc = input("Enter new doc: ")
chunk.documentation = new_doc
chunk.status = 'human_validated'
# else skip
But we might want to see the linked chunks? We can show the linked chunks' code and documentation? That might help.
We'll leave that for future.
This is a very basic prototype.
Let's code accordingly.
Note: We are using OpenAI for embeddings and generation. We'll need an API key.
We'll set up:
import openai
openai.api_key = "..."
We'll use:
embedding model: "text-embedding-ada-002"
generation model: "gpt-3.5-turbo" or "gpt-4"
We'll write functions:
def get_embedding(text):
response = openai.Embedding.create(input=text, model="text-embedding-ada-002")
return response['data'][0]['embedding']
def generate_doc(chunk, context_chunks=[]):
context_str = "\n".join([f"Code:\n{c.code}\nDoc:\n{c.documentation}" for c in context_chunks])
prompt = f"""You are an expert software engineer. Write a detailed docstring for the following {chunk.chunk_type} in the style of Google.
Code:
{chunk.code}
Context (similar code in the project):
{context_str}
Docstring:
"""
response = openai.ChatCompletion.create(
model="gpt-3.5-turbo",
messages=[{"role": "user", "content": prompt}]
)
return response.choices[0].message.content.strip()
We'll call generate_doc with the top 3 similar chunks (from the index) as context.
But note: when we generate for a new_chunk, we have to find its similar chunks first. But we are in the process of adding the new_chunks. We don't have the embeddings for the new_chunks yet? We compute the embedding for the new_chunk and then use it to find similar chunks.
We'll do in add_chunk:
chunk.embedding = get_embedding(chunk.code)
# then find similar chunks from (self.chunks + new_chunks_being_added) but note: we haven't added the new_chunks to self.chunks yet? We are adding one by one? Or we add a list?
We'll change the add_chunk to add a list of chunks at once? Because we want to link among the new_chunks and with existing ones.
Let's change the index to have:
def add_chunks(self, new_chunks: list[CodeChunk]):
# Compute embeddings for all new_chunks
for chunk in new_chunks:
chunk.embedding = get_embedding(chunk.code)
# Combine existing and new
all_chunks = self.chunks + new_chunks
# For each new_chunk, find top 5 similar from all_chunks (excluding itself)
for new_chunk in new_chunks:
# compute similarity with all_chunks
similarities = []
for other in all_chunks:
if other.id == new_chunk.id:
continue
sim = cosine_similarity(new_chunk.embedding, other.embedding)
similarities.append((sim, other))
top5 = sorted(similarities, key=lambda x: x[0], reverse=True)[:5]
top5_chunks = [other for sim, other in top5]
# Initialize link set for new_chunk
self.links[new_chunk.id] = set()
for other in top5_chunks:
self.links[new_chunk.id].add(other.id)
# Ensure other is in links dict
if other.id not in self.links:
self.links[other.id] = set()
self.links[other.id].add(new_chunk.id)
# Now add the new_chunks to self.chunks
self.chunks.extend(new_chunks)
# Generate documentation for new_chunks (using the top5_chunks as context? But we have the links now, so we can use the linked chunks as context)
for new_chunk in new_chunks:
context_chunks = [self.get_chunk_by_id(cid) for cid in self.links[new_chunk.id]]
# But note: the new_chunk might be linked to other new_chunks that we haven't generated documentation for? We are generating for each new_chunk in order. We can generate documentation after all new_chunks are added and linked? Then we can use the linked chunks' documentation (if any) as context. But the other new_chunks don't have documentation yet (they are about to be generated). So we can use the code of the linked chunks as context? Or we can generate in two passes?
We'll do:
First, add all new_chunks and build links.
Then, for each new_chunk, generate documentation using the linked chunks' code (and if they have documentation, use that? But they are new and don't have documentation yet). So we just use the code.
We can do:
for new_chunk in new_chunks:
context_chunks = [self.get_chunk_by_id(cid) for cid in self.links[new_chunk.id]]
# We only use the code of the context_chunks because they are new and don't have documentation.
# But we can use the code of the context_chunks as context.
new_chunk.documentation = generate_doc(new_chunk, context_chunks)
new_chunk.status = 'ai_generated'
But note: the context_chunks might be existing chunks that have documentation (human_validated or ai_generated). We can pass the existing documentation as context? Yes, that would be better.
So in generate_doc, we can use:
context_str = ""
for c in context_chunks:
if c.documentation:
context_str += f"Code:\n{c.code}\nDoc:\n{c.documentation}\n\n"
else:
context_str += f"Code:\n{c.code}\n\n"
Then the prompt becomes:
You are an expert software engineer. Write a detailed docstring for the following {chunk.chunk_type} in the style of Google.
Here are some similar code snippets from the project with their documentation (if available):
{context_str}
Now, write a docstring for this code:
{chunk.code}
We'll adjust the prompt accordingly.
We'll need a method to get a chunk by id.
This is a basic design. There are many edge cases and optimizations.
Let's code the in-memory version.
We'll also need to compute cosine similarity. We'll use numpy.
Steps:
import numpy as np
def cosine_similarity(a, b):
return np.dot(a, b) / (np.linalg.norm(a) * np.linalg.norm(b))
But note: the embeddings are lists of floats. We'll convert to numpy arrays.
However, for large vectors, this might be slow. We'll use it for now.
We'll also note that the OpenAI embeddings are normalized? According to the docs, they are normalized to length 1. So cosine similarity is just dot product.
So we can do:
sim = np.dot(a, b)
But we'll still use the formula to be safe.
Let's code accordingly.
We'll also need to handle the case when there are no existing chunks (first file).
We'll write the CodebaseIndex class accordingly.
We'll also need to persist the index? We can pickle it? But for a real system, we would use a database.
We'll skip persistence for the prototype.
Now, the watchdog:
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
class CodebaseChangeHandler(FileSystemEventHandler):
def __init__(self, index, parser):
self.index = index
self.parser = parser
def on_modified(self, event):
if event.src_path.endswith('.py'):
print(f"File {event.src_path} has been modified")
new_chunks = self.parser.parse_file(event.src_path)
self.index.update_file(event.src_path, new_chunks)
Then we set up the observer.
But note: on_modified might be triggered multiple times. We might want to debounce.
We'll keep it simple.
Now, the CLI for validation:
We can have a separate script that loads the index (from pickle?) and then runs the validation loop.
But we don't have persistence, so we'll run everything in one process.
We'll structure:
main.py:
- set up the index
- parse initial files (maybe a directory)
- add all chunks
- start the watchdog
- then run the validation loop in a separate thread? Or we can run the validation loop manually by calling a function.
We'll leave the validation as a separate script that can be run to review the ai_generated chunks.
Let's write:
validate.py:
from main import index # but we need to load the index from disk? We'll skip.
We'll instead have a simple loop in the main that every minute checks for ai_generated chunks and prompts the user? That might be intrusive.
We'll separate: the main runs the index and the watchdog, and then we have a separate command to validate.
But without persistence, we cannot run the validator separately.
We'll skip the watchdog and persistence for the first version and just do:
index = CodebaseIndex()
for file in python_files:
chunks = parser.parse_file(file)
index.add_chunks(chunks)
Then we run the validation on the index.
Then we can simulate changes by re-parsing a file and calling update_file.
Let's do a minimal example without watchdog.
We'll create:
parser = PythonParser()
index = CodebaseIndex()
# Initial load
for file in glob("src/**/*.py", recursive=True):
chunks = parser.parse_file(file)
index.add_chunks(chunks)
# Then validate
validate(index)
# Then simulate a change
changed_file = "src/example.py"
new_chunks = parser.parse_file(changed_file)
index.update_file(changed_file, new_chunks)
# Then validate again
We'll write the PythonParser.
Let's code accordingly.
Note: This is a prototype and not production-ready.
We'll now write the code for the classes.
Due to the complexity, we cannot write the entire system in one response, but we can outline the key parts.
Let's write the CodeChunk, CodebaseIndex, and the parser.
We'll assume the codebase is small and we can load all files.
We'll also assume we have an OpenAI API key set in the environment variable.
Let's code.
I'll design a comprehensive AI-Assisted Codebase Documentation Generator with the four pillars you've specified. This system automatically generates, maintains, and validates documentation with human-in-the-loop quality control.
System Architecture
┌─────────────────────────────────────────────────────────────┐
│ USER INTERFACE LAYER │
├─────────────────────────────────────────────────────────────┤
│ • IDE Plugins (VS Code, IntelliJ) │
│ • Web Dashboard │
│ • CLI Tools │
│ • Slack/Teams Bots │
└──────────────────────────────┬──────────────────────────────┘
│
┌──────────────────────────────▼──────────────────────────────┐
│ ORCHESTRATION ENGINE │
├─────────────────────────────────────────────────────────────┤
│ • Change Detection Service │
│ • Scheduling & Prioritization │
│ • Validation Workflow Manager │
│ • Freshness Monitor │
└───────┬──────────────────────┬─────────────────────────────┘
│ │
┌───────▼──────────┐ ┌────────▼──────────────────────────────┐
│ EMBEDDING & │ │ DOCUMENTATION │
│ RETRIEVAL │ │ GENERATION │
├───────────────────┤ ├──────────────────────────────────────┤
│ • Multi-strategy │ │ • Context-aware Generation │
│ embeddings │ │ • Template-based &自由形式 │
│ • Hybrid search │ │ • Multi-language support │
│ • Chunk linking │ │ • Versioned outputs │
│ • Semantic graph │ │ • Quality scoring │
└───────────────────┘ └───────────────┬──────────────────────┘
│
┌────────────────────────────────────────▼─────────────────────┐
│ STORAGE LAYER │
├─────────────────────────────────────────────────────────────┤
│ • Vector DB (Pinecone/Weaviate) │
│ • Graph DB (Neo4j) for relationships │
│ • Metadata DB (PostgreSQL) │
│ • Blob storage (code snapshots, docs) │
└─────────────────────────────────────────────────────────────┘
1. Embedding Strategies
Multi-Modal Embedding Pipeline
class EmbeddingStrategy:
def __init__(self):
self.strategies = {
'code_structure': CodeStructureEmbedder(), # AST-based
'semantic': SemanticCodeEmbedder(), # Text-based (CodeBERT)
'hybrid': HybridEmbedder(), # Combined approach
'cross_modal': CrossModalEmbedder() # Code + Docs + Issue linking
}
def generate_embeddings(self, code_unit, context=None):
embeddings = {}
for name, strategy in self.strategies.items():
embeddings[name] = strategy.embed(code_unit, context)
return self.fusion_layer(embeddings)
class ASTEmbedder:
"""Extracts structural embeddings from Abstract Syntax Tree"""
def embed(self, code_unit):
tree = ast.parse(code_unit.source)
# Extract: node types, control flow, dependencies, metrics
features = {
'node_types': self.extract_node_distribution(tree),
'cyclomatic': self.calculate_complexity(tree),
'dependency_graph': self.build_dependency_graph(tree)
}
return self.feature_vector(features)
class ContextAwareEmbedder:
"""Considers surrounding files, imports, and project structure"""
def embed(self, code_unit, context):
# Context includes:
# - Imported modules and their usage patterns
# - Call graphs to/from this unit
# - Related test files
# - Historical change patterns
return enhanced_embedding
Chunk Optimization
class SmartChunker:
"""Intelligently splits code into documentation-worthy units"""
CHUNKING_STRATEGIES = {
'function': self.chunk_by_function,
'class': self.chunk_by_class,
'module': self.chunk_by_module,
'dependency_cluster': self.chunk_by_dependency,
'change_cluster': self.chunk_by_change_history
}
def optimal_chunk(self, code_unit):
# Determine best chunking strategy based on:
# - Language conventions
# - Code complexity metrics
# - Historical documentation patterns
# - Co-change frequency
strategy = self.select_strategy(code_unit)
return strategy(code_unit)
2. Chunk Linking System
Relationship Graph Construction
class ChunkLinker:
def __init__(self, graph_db):
self.graph = graph_db
self.link_types = {
'calls': self.detect_call_relationships,
'inherits': self.detect_inheritance,
'tests': self.detect_test_relationships,
'configures': self.detect_configuration_links,
'modifies': self.detect_state_modifications,
'domain': self.detect_domain_similarity # Semantic
}
def build_links(self, chunks):
"""Create bidirectional relationships between chunks"""
for chunk in chunks:
for link_type, detector in self.link_types.items():
relationships = detector(chunk, all_chunks)
for target, confidence in relationships:
self.graph.add_relationship(
source=chunk.id,
target=target.id,
type=link_type,
weight=confidence,
metadata={'generated': datetime.now()}
)
def get_relevant_context(self, chunk, max_depth=2):
"""Retrieve linked chunks for documentation context"""
neighborhood = self.graph.neighborhood(
chunk.id,
max_depth=max_depth,
relationship_weights={'calls': 0.8, 'tests': 0.6}
)
return self.rank_by_relevance(neighborhood, chunk)
Dynamic Context Assembly
class ContextAssembler:
def assemble_context(self, target_chunk):
"""Build documentation context from linked chunks"""
context = {
'direct_dependencies': self.get_direct_dependencies(target_chunk),
'test_coverage': self.get_associated_tests(target_chunk),
'similar_patterns': self.get_semantic_similars(target_chunk),
'change_history': self.get_recent_changes(target_chunk),
'issue_references': self.get_linked_issues(target_chunk)
}
return self.prioritize_context(context, target_chunk.type)
3. Human Validation Loops
Validation Workflow
class ValidationWorkflow:
STAGES = ['automated_generation', 'peer_review', 'expert_approval', 'publication']
def __init__(self):
self.validators = {
' junior_dev': JuniorDevValidator(),
'senior_dev': SeniorDevValidator(),
'tech_lead': TechLeadValidator(),
'domain_expert': DomainExpertValidator()
}
def create_validation_task(self, doc_unit):
"""Create multi-stage validation tickets"""
task = ValidationTask(
doc_unit=doc_unit,
checks=[
CompletenessCheck(),
AccuracyCheck(),
StyleGuideCheck(),
SecurityReview()
],
assignees=self.assign_by_expertise(doc_unit),
deadlines=self.calculate_deadlines(doc_unit.priority)
)
return task
class InteractiveValidator:
"""IDE-integrated validation interface"""
def validate_in_context(self, code_file, generated_doc):
"""Show doc alongside code with inline editing"""
return {
'approve': self.quick_approve(),
'edit': self.open_editor(code_file, generated_doc),
'reject': self.reject_with_feedback(),
'delegate': self.assign_to_other()
}
Validation Metrics & Feedback Loop
class ValidationAnalytics:
def track_validation(self, validation_event):
"""Learn from human corrections"""
self.record_metrics({
'time_to_validate':validation_event.duration,
'edit_distance': self.calculate_diff(
validation_event.original_doc,
validation_event.final_doc
),
'validator_expertise': validation_event.validator.level,
'code_complexity': self.measure_complexity(
validation_event.code_unit
)
})
# Retrain embedding model with corrections
self.retrain_embeddings(validation_event)
# Update chunking strategy based on feedback
self.adjust_chunking_strategy(validation_event)
4. Freshness Guarantees
Change Detection System
class FreshnessMonitor:
def __init__(self):
self.change_trackers = {
'git_hook': GitHookTracker(),
'ci_cd': CIDetector(),
'ide_activity': IDEActivityMonitor(),
'dependency_update': DependencyTracker()
}
def detect_changes(self):
"""Multi-source change detection"""
changes = []
for tracker in self.change_trackers.values():
changes.extend(tracker.scan())
return self.deduplicate_and_prioritize(changes)
def impact_analysis(self, change):
"""Determine what documentation needs updating"""
affected_chunks = self.chunk_linker.get_affected_chunks(change)
return {
'direct': self.get_directly_modified_chunks(change),
'transitive': self.get_transitive_impacts(affected_chunks),
'critical_path': self.identify_critical_dependencies(affected_chunks),
'test_impacts': self.identify_test_updates(affected_chunks)
}
Automated Update Pipeline
class UpdatePipeline:
def process_change(self, change_event):
"""End-to-end documentation update"""
with Transaction() as txn:
# 1. Invalidate affected documentation
self.invalidate_docs(change_event.affected_chunks)
# 2. Regenerate with latest context
for chunk in change_event.affected_chunks:
if self.needs_regeneration(chunk):
new_doc = self.generate_documentation(
chunk,
context=self.get_fresh_context(chunk)
)
self.queue_for_validation(new_doc)
# 3. Schedule validation based on priority
self.schedule_validation(change_event.priority)
# 4. Track freshness metrics
self.metrics.record_freshness(
change_event,
time_to_update=datetime.now() - change_event.timestamp
)
Guarantee Mechanisms
class FreshnessGuarantees:
SLAS = {
'critical_path': {'max_age': '24h', 'auto_publish': True},
'api_surface': {'max_age': '72h', 'require_review': True},
'internal': {'max_age': '7d', 'batch_updates': True}
}
def enforce_freshness(self):
"""Ensure no stale documentation exists"""
stale_docs = self.find_stale_documents()
for doc in stale_docs:
if self.is_critical(doc):
self.force_regenerate(doc)
self.escalate_to_owner(doc)
else:
self.add_freshness_warning(doc)
self.schedule_update(doc)
def can_publish(self, documentation):
"""Check if documentation meets freshness criteria"""
age = datetime.now() - documentation.last_updated
sla = self.SLAS[documentation.category]
return {
'fresh': age < sla['max_age'],
'needs_review': sla.get('require_review', False),
'auto_publish': sla.get('auto_publish', False)
}
Implementation Roadmap
Phase 1: Foundation (Weeks 1-4)
- Set up vector + graph database
- Implement basic code parser with AST analysis
- Build embedding generation pipeline
- Create simple CLI for single file documentation
Phase 2: Linking & Context (Weeks 5-8)
- Implement chunk relationship detection
- Build context assembly for documentation
- Create basic web dashboard
- Add freshness tracking
Phase 3: Human Validation (Weeks 9-12)
- Build validation workflow system
- Create IDE plugins (VS Code first)
- Implement feedback learning loop
- Add validation analytics
Phase 4: Productionization (Weeks 13-16)
- CI/CD integration
- Multi-language support (Python, JS, Java, Go)
- Scalability optimizations
- SLA monitoring & alerting
Key Innovations
- Multi-Strategy Embedding Fusion: Combines structural (AST), semantic (text), and relational (graph) embeddings
- Impact-Based Prioritization: Uses change impact analysis to determine update urgency
- Progressive Validation: Different validation levels based on documentation criticality
- Feedback-Weighted Generation: LLM prompts improve based on human corrections
- SLA-Driven Freshness: Different freshness guarantees per documentation category
Technical Stack
- Embeddings: CodeBERT + AST-based features + Sentence Transformers
- Vector DB: Weaviate (supports hybrid search + metadata filtering)
- Graph DB: Neo4j (for relationship queries)
- LLM: GPT-4 + fine-tuned CodeLlama for domain-specific generation
- Orchestration: Temporal.io for workflow management
- Frontend: React + Monaco Editor for IDE-like experience
- Monitoring: Prometheus + Grafana with custom freshness metrics
Success Metrics
- Documentation Coverage: % of codebase with ≥ basic documentation
- Freshness SLA Compliance: % of docs meeting age requirements
- Validation Throughput: Time from generation to validation
- Accuracy Score: Human-rated correctness (1-5 scale)
- Developer Adoption: % of team using the system regularly
This system creates a self-improving documentation ecosystem where AI generation, human validation, and automatic freshness tracking form a virtuous cycle. The chunk linking ensures contextual accuracy, while the embedding strategies capture both syntactic and semantic relationships across the codebase.