Build a live semantic index over a codebase with CocoIndex V1. Point it at a repo, and you get a vector index you can search in natural language (“where do we embed chunks?”). In live mode the index follows your edits, which gives a coding agent current context. The indexing pipeline is about 120 lines of async Python (200 with the query demo), with Tree-sitter chunking built in.
Incremental processing, change tracking and managed targets run in a Rust engine. With a source that watches for changes, like the local filesystem in live mode, the index tracks your edits as they happen: save a file, and only the chunks whose text changed are embedded again; their rows are inserted and the old ones deleted.
What the index is for
- Code context for agents: semantic context for Claude, Codex, OpenCode, Factory.
- Code search: natural-language and semantic search over your repo.
- Review & refactor agents: context for code review, security analysis, and large-scale refactoring.
Why CocoIndex for codebase indexing
Code needs structure-aware chunks, and it changes all the time:
- Chunks follow code structure (functions, classes, blocks) instead of arbitrary line windows. Tree-sitter grammars for the common languages are built into the splitter.
- Most commits touch a few files. CocoIndex re-embeds only the chunks that changed, and with
live=Truepluscocoindex update -Lit keeps watching and applies each edit as it happens. - The engine is Rust. The run below indexed 622 files of the CocoIndex repo in 43 seconds from an empty table; after that, a save re-processes one file.
- The pipeline is ordinary
asyncPython and your own types. You choose the embedding model, the chunking and the vector database.
examples/code_embeddingThe whole example is about 200 lines of plain Python, including the query demo. Clone it, point it at your repo, and swap in another model or vector store.
Overview
- source
localfs.files under sourcedir that match the patterns; live=True watches for changeswalk_dir mount_each(process_file, ...): one processing component per file, memoized- transform
detect_code_languagefile name to language, for example main.py to python - transform · Tree-sitter
RecursiveSplitter.split along the syntax tree into chunks, each with text, start.line and end.linesplit coco.map(process_chunk, chunks, ...): one call per chunk- transform
SentenceTransformerEmbedder.chunk text to a 384-dimension vector, memoized by textembed - target state
table.id, filename, code, embedding, start_line, end_linedeclare_row( CodeEmbedding)
- transform
- transform
- target
Postgres + pgvectortable code_embeddings with a vector index on embedding
The steps:
- Read code files from a local directory.
- Split each file into syntax-aware chunks with Tree-sitter, then embed every chunk.
- Store the chunks and their embeddings in Postgres (as target states).
With CocoIndex, you declare the transformation logic in Python: the target state is a function of the source state, and you write no update logic.
When your codebase changes, or your processing logic changes (a different embedding model, a new chunk size), only the difference is reprocessed. The Incremental updates section shows what each kind of change recomputes.
Setup
In this example we store the indexed rows in Postgres with the pgvector extension. Your metadata and the vector search index both live there. CocoIndex also writes to other targets.
-
Get the example and start Postgres. If you already run Postgres with pgvector, skip the
docker composeline.git clone https://github.com/cocoindex-io/cocoindex.git cd cocoindex docker compose -f dev/postgres.yaml up -d cd examples/code_embedding -
Copy the environment file. It sets
POSTGRES_URLfor the target table andCOCOINDEX_DB, the local file where CocoIndex keeps its own state. ThecocoindexCLI loads.envfrom the current directory.cp .env.example .env -
Install CocoIndex and the dependencies.
pip install -U "cocoindex[postgres,sentence_transformers]" asyncpg pgvector numpy python-dotenv
Define the App
Apps are the top-level runnable unit in CocoIndex. An app names your pipeline and binds a main function with its parameters.
Define the data and shared resources
This block sets up two things the rest of the code builds on. CodeEmbedding defines one row of the output table: each chunk of code becomes one row, with its text, location, and embedding vector. coco_lifespan provides the shared resources every step needs, the Postgres connection pool and the embedding model, built once at startup instead of per file.
import os
import pathlib
from dataclasses import dataclass
from typing import AsyncIterator, Annotated
import asyncpg
from numpy.typing import NDArray
import cocoindex as coco
from cocoindex.connectors import localfs, postgres
from cocoindex.ops.text import RecursiveSplitter, detect_code_language
from cocoindex.ops.sentence_transformers import SentenceTransformerEmbedder
from cocoindex.resources.chunk import Chunk
from cocoindex.resources.file import FileLike, PatternFilePathMatcher
from cocoindex.resources.id import IdGenerator
DATABASE_URL = os.getenv("POSTGRES_URL", "postgres://cocoindex:cocoindex@localhost/cocoindex")
TABLE_NAME = "code_embeddings"
PG_SCHEMA_NAME = "coco_examples"
EMBED_MODEL = "sentence-transformers/all-MiniLM-L6-v2"
PG_DB = coco.ContextKey[asyncpg.Pool]("code_embedding_db")
EMBEDDER = coco.ContextKey[SentenceTransformerEmbedder]("embedder", detect_change=True)
_splitter = RecursiveSplitter()
@dataclass
class CodeEmbedding:
id: int
filename: str
code: str
embedding: Annotated[NDArray, EMBEDDER]
start_line: int
end_line: int
@coco.lifespan
async def coco_lifespan(builder: coco.EnvironmentBuilder) -> AsyncIterator[None]:
async with asyncpg.create_pool(DATABASE_URL) as pool:
builder.provide(PG_DB, pool)
builder.provide(EMBEDDER, SentenceTransformerEmbedder(EMBED_MODEL))
yield
Define file processing
With the row schema and shared resources in place, we can write the per-file work: turning a file into rows.
Process file
@coco.fn(memo=True)
async def process_file(
file: FileLike,
table: postgres.TableTarget[CodeEmbedding],
) -> None:
text = await file.read_text()
language = detect_code_language(filename=str(file.file_path.path.name))
chunks = _splitter.split(
text,
chunk_size=1000,
min_chunk_size=300,
chunk_overlap=300,
language=language,
)
id_gen = IdGenerator()
await coco.map(process_chunk, chunks, file.file_path.path, id_gen, table)
process_file runs once per file. It reads the file, detects the language so Tree-sitter can parse it, splits the code along the syntax tree, and maps each chunk to process_chunk. How Tree-sitter works explains how the splitter walks that tree and which chunks change when you edit a file.
The splitter places chunk boundaries between syntax nodes (definitions, statements, blocks) where it can, so a chunk usually holds whole functions or statements rather than an arbitrary window of lines. A definition longer than chunk_size (in bytes) is split at its inner blocks. All major languages are supported (Python, Rust, JavaScript, TypeScript, Java, C++, and more); unknown file types fall back to plain text.
Note that @coco.fn with memo=True is what makes this incremental: if a file’s content and this function’s code are both unchanged, the whole file is skipped on the next run. coco.map fans out to one process_chunk call per chunk.
Here is what chunking produces for one file the example indexes, python/cocoindex/resources/id.py from the CocoIndex repo (225 lines), with the settings above:
| Lines | Chunk holds |
|---|---|
| 1–25 | module docstring, imports |
| 18–31 | imports, start of generate_id() |
| 32–57 | rest of generate_id() |
| 60–86 | generate_uuid() |
| 89–104 | IdGenerator docstring |
| 101–124 | end of the docstring, IdGenerator.__init__() |
| 126–149 | IdGenerator.next_id() |
| 152–168 | UuidGenerator docstring |
| 165–188 | end of the docstring, UuidGenerator.__init__() |
| 190–213 | UuidGenerator.next_uuid() |
| 216–225 | _generate_next_id(), _generate_next_uuid() |
The long generate_id() is split between its signature and the rest of the function. Neighboring chunks overlap by up to chunk_overlap=300 bytes, so text near a boundary appears in both: lines 101–104 of the IdGenerator docstring are in the chunks at 89–104 and 101–124.
Process chunk
Next, we embed the chunk with the shared embedder and declare the target row.
@coco.fn
async def process_chunk(
chunk: Chunk,
filename: pathlib.PurePath,
id_gen: IdGenerator,
table: postgres.TableTarget[CodeEmbedding],
) -> None:
embedding = await coco.use_context(EMBEDDER).embed(chunk.text)
table.declare_row(
row=CodeEmbedding(
id=await id_gen.next_id(chunk.text),
filename=str(filename),
code=chunk.text,
embedding=embedding,
start_line=chunk.start.line,
end_line=chunk.end.line,
),
)
We use SentenceTransformerEmbedder with all-MiniLM-L6-v2; there are 12k+ sentence-transformer models on Hugging Face, so swap in whichever you prefer. Note chunk.start.line and chunk.end.line: V1 carries line numbers through, so search results point straight at the lines that matched.
Define the main function
app_main wires the source to the target. It mounts the Postgres table (with a vector index), walks the codebase, and mounts one processing component per file.
@coco.fn
async def app_main(sourcedir: pathlib.Path) -> None:
target_table = await postgres.mount_table_target(
PG_DB,
table_name=TABLE_NAME,
table_schema=await postgres.TableSchema.from_class(
CodeEmbedding, primary_key=["id"],
),
pg_schema_name=PG_SCHEMA_NAME,
)
target_table.declare_vector_index(column="embedding")
files = localfs.walk_dir(
sourcedir,
recursive=True,
path_matcher=PatternFilePathMatcher(
included_patterns=["**/*.py", "**/*.rs", "**/*.toml", "**/*.md", "**/*.mdx"],
excluded_patterns=["**/.*", "**/target", "**/node_modules"],
),
live=True, # watch for changes; pass -L to `cocoindex update` to run live
)
await coco.mount_each(process_file, files.items(), target_table)
We walk the codebase from sourcedir (point this at the repository you want to index). We index files with the extensions .py, .rs, .toml, .md, .mdx, and skip dot-directories, target, and node_modules.
mount_table_target creates and manages the Postgres table (coco_examples.code_embeddings) for you: the schema, the pgvector index, and inserts, updates and deletes by primary key, including deletion of rows whose file is gone. live=True makes the filesystem source watch for changes, and mount_each runs one component per file so the engine can track and update them independently.
Create the App
Bind app_main into a coco.App and point it at the codebase root.
app = coco.App(
coco.AppConfig(name="CodeEmbeddingV1"),
app_main,
sourcedir=pathlib.Path(__file__).parent / ".." / "..", # index from repo root
)
Run the pipeline
Run the cocoindex CLI to set up and update the index. Choose catch-up (scan, sync, exit) or live (catch up, then keep watching):
# Catch-up run
cocoindex update main
# Live run: keep watching for file changes
cocoindex update -L main
The CLI prints a per-function summary of the update:
✅ app_main: 1 total | 1 added
✅ declare_target_state_with_child: 1 total | 1 added
✅ _MountEachLiveComponent.process: 1 total | 1 added
✅ process_file: 622 total | 622 added
⏳ Elapsed: 43.4s
Query the index
We match user text against the index with a plain SQL query, using the same embedding model as the indexing flow so queries and chunks land in the same vector space.
import asyncio
import sys
from dotenv import load_dotenv
from pgvector.asyncpg import register_vector
TOP_K = 5
async def query_once(pool, embedder, query: str, *, top_k: int = TOP_K) -> None:
query_vec = await embedder.embed(query)
async with pool.acquire() as conn:
rows = await conn.fetch(
f"""
SELECT filename, code, embedding <=> $1 AS distance, start_line, end_line
FROM "{PG_SCHEMA_NAME}"."{TABLE_NAME}"
ORDER BY distance ASC
LIMIT $2
""",
query_vec, top_k,
)
for r in rows:
score = 1.0 - float(r["distance"])
print(f"[{score:.3f}] {r['filename']} (L{r['start_line']}-L{r['end_line']})")
print(f" {r['code']}")
print("---")
async def query(text: str) -> None:
embedder = SentenceTransformerEmbedder(EMBED_MODEL)
async with asyncpg.create_pool(DATABASE_URL, init=register_vector) as pool:
await query_once(pool, embedder, text)
if __name__ == "__main__":
load_dotenv()
asyncio.run(query(" ".join(sys.argv[1:])))
embedder.embed returns a NumPy array. init=register_vector registers pgvector’s type with each connection in the pool, so asyncpg can send that array as a vector parameter; without it, the query fails. The <=> operator is pgvector’s cosine distance. We turn it into a similarity score and print the filename, the matched line range, and the chunk. Run it against your index:
python main.py "where do we embed chunks"
It prints the top 5 chunks, each with its similarity score, file, and line range. Chunks are cut to their first lines here (…):
[0.527] rust/ops_text/src/split/by_separators.rs (L72-L94)
let bytes = text.as_bytes();
// Collect raw chunks (byte ranges)
struct RawChunk {
start: usize,
end: usize,
…
---
[0.459] rust/ops_text/src/split/by_separators.rs (L116-L138)
let mut positions: Vec<Position> = raw_chunks
.iter()
.flat_map(|c| vec![Position::new(c.start), Position::new(c.end)])
.collect();
set_output_positions(text, positions.iter_mut());
…
---
[0.448] rust/ops_text/src/split/recursive.rs (L560-L578)
fn split_root_chunk(&self, kind: ChunkKind<'t>) -> Vec<ChunkOutput> {
let mut atom_collector = AtomChunksCollector {
full_text: self.full_text,
min_level: 0,
curr_level: 0,
atom_chunks: Vec::new(),
…
---
[0.447] rust/sdk/cocoindex/tests/code.rs (L300-L314)
#[test]
fn code_ast_split_chunk_positions_are_accurate() {
// Three-line Python source; verify start/end positions of first chunk.
let src = "a = 1\nb = 2\nc = 3\n";
let ast = CodeAst::new(src, "python").unwrap();
let chunks = ast.split(200, None, None).unwrap(); // one big chunk
…
---
[0.444] rust/sdk/cocoindex/src/ops/code.rs (L315-L341)
let config = RecursiveChunkConfig {
chunk_size,
min_chunk_size,
chunk_overlap,
};
let raw = chunker.split(&self.source, config);
…
---
Incremental updates
You change the code or the pipeline, and CocoIndex works out what to embed, insert, update and delete. Two mechanisms decide it:
- What to recompute.
process_fileis@coco.fn(memo=True): a file is skipped when its content and the code ofprocess_file(and the functions it calls) are unchanged.SentenceTransformerEmbedder.embedis memoized too, so a chunk whose text this file embedded on the previous run gets its vector without a model call. - What to write. Each row’s id comes from
IdGenerator.next_id(chunk.text), so the same chunk text keeps the same id from run to run.mount_table_targetcompares the rows declared in this run with the rows already in Postgres: a new id is inserted, a missing id is deleted, and a row whose columns changed is updated.
Pick an edit to see what the next run does to one file of the indexed repository, the id.py from the table above:
What the next run does after an edit
One file of the indexed repository, python/cocoindex/resources/id.py (225 lines, 11 chunks), split with the example's settings. Each edit changes the file's text; the last two scenarios change the pipeline and the repository.
process_file- runs
- Embedding calls
- 11
- Rows written
- +11 −0 ~0 inserted, deleted, updated
- Rows kept
- 0
| Lines | Chunk | Row |
|---|---|---|
| 1–25 | module docstring, | embedded, inserted |
| 18–31 | imports, | embedded, inserted |
| 32–57 | generate_id() | embedded, inserted |
| 60–86 | generate_uuid() | embedded, inserted |
| 89–104 | IdGenerator docstring | embedded, inserted |
| 101–124 | IdGenerator docstring, | embedded, inserted |
| 126–149 | IdGenerator. | embedded, inserted |
| 152–168 | UuidGenerator docstring | embedded, inserted |
| 165–188 | UuidGenerator docstring, | embedded, inserted |
| 190–213 | UuidGenerator. | embedded, inserted |
| 216–225 | _generate_next_id(), | embedded, inserted |
Every chunk is new: 11 embedding calls and 11 rows inserted. Neighboring chunks overlap by up to 300 bytes, so their line ranges overlap too.
process_file- skipped
- Embedding calls
- 0
- Rows written
- none inserted, deleted, updated
- Rows kept
- 11
| Lines | Chunk | Row |
|---|---|---|
| 1–25 | module docstring, | kept |
| 18–31 | imports, | kept |
| 32–57 | generate_id() | kept |
| 60–86 | generate_uuid() | kept |
| 89–104 | IdGenerator docstring | kept |
| 101–124 | IdGenerator docstring, | kept |
| 126–149 | IdGenerator. | kept |
| 152–168 | UuidGenerator docstring | kept |
| 165–188 | UuidGenerator docstring, | kept |
| 190–213 | UuidGenerator. | kept |
| 216–225 | _generate_next_id(), | kept |
The file and the pipeline code are unchanged, so the memoized process_file does not run: no split, no embedding call, no row written.
- # Get and increment ordinal for this fingerprint+ # Look up and bump the ordinal for this fingerprintprocess_file- runs
- Embedding calls
- 1
- Rows written
- +1 −1 ~0 inserted, deleted, updated
- Rows kept
- 10
| Lines | Chunk | Row |
|---|---|---|
| 1–25 | module docstring, | kept |
| 18–31 | imports, | kept |
| 32–57 | generate_id() | kept |
| 60–86 | generate_uuid() | kept |
| 89–104 | IdGenerator docstring | kept |
| 101–124 | IdGenerator docstring, | kept |
| 126–149 | IdGenerator. | deleted |
| 126–149 | IdGenerator. | embedded, inserted |
| 152–168 | UuidGenerator docstring | kept |
| 165–188 | UuidGenerator docstring, | kept |
| 190–213 | UuidGenerator. | kept |
| 216–225 | _generate_next_id(), | kept |
The file is read and split again. Only the chunk that holds the edit has new text, so it gets a new id: its old row is deleted and the new chunk is embedded and inserted. The other 10 chunks have the same text and lines, so their embeddings come from the memo and their rows are not written.
+ and unlike a counter, it is stable across runs,process_file- runs
- Embedding calls
- 1
- Rows written
- +1 −1 ~6 inserted, deleted, updated
- Rows kept
- 4
| Lines | Chunk | Row |
|---|---|---|
| 1–25 | module docstring, | kept |
| 18–31 | imports, | kept |
| 32–57 | generate_id() | kept |
| 60–86 | generate_uuid() | kept |
| 89–104 | IdGenerator docstring | deleted |
| 89–105 | IdGenerator docstring | embedded, inserted |
| 102–125was 101–124 | IdGenerator docstring, | lines updated |
| 127–150was 126–149 | IdGenerator. | lines updated |
| 153–169was 152–168 | UuidGenerator docstring | lines updated |
| 166–189was 165–188 | UuidGenerator docstring, | lines updated |
| 191–214was 190–213 | UuidGenerator. | lines updated |
| 217–226was 216–225 | _generate_next_id(), | lines updated |
The chunk that holds the new line is replaced. The 6 chunks after it keep their text, so they keep their ids and embeddings; each row is rewritten with its new start_line and end_line, one line further down.
+ # deps separates generators within one componentprocess_file- runs
- Embedding calls
- 2
- Rows written
- +2 −2 ~5 inserted, deleted, updated
- Rows kept
- 4
| Lines | Chunk | Row |
|---|---|---|
| 1–25 | module docstring, | kept |
| 18–31 | imports, | kept |
| 32–57 | generate_id() | kept |
| 60–86 | generate_uuid() | kept |
| 89–104 | IdGenerator docstring | deleted |
| 89–110 | IdGenerator docstring | embedded, inserted |
| 101–124 | IdGenerator docstring, | deleted |
| 106–125 | IdGenerator docstring, | embedded, inserted |
| 127–150was 126–149 | IdGenerator. | lines updated |
| 153–169was 152–168 | UuidGenerator docstring | lines updated |
| 166–189was 165–188 | UuidGenerator docstring, | lines updated |
| 191–214was 190–213 | UuidGenerator. | lines updated |
| 217–226was 216–225 | _generate_next_id(), | lines updated |
One new line, and the splitter places the boundary before it differently: the chunk at lines 89–104, which does not hold the edit, is replaced along with the one that does. The splitter balances chunk sizes, so an edit can move a nearby boundary.
- def generate_uuid(...) # 27 lines with its decoratorprocess_file- runs
- Embedding calls
- 0
- Rows written
- +0 −1 ~7 inserted, deleted, updated
- Rows kept
- 3
| Lines | Chunk | Row |
|---|---|---|
| 1–25 | module docstring, | kept |
| 18–31 | imports, | kept |
| 32–57 | generate_id() | kept |
| 60–86 | generate_uuid() | deleted |
| 60–75was 89–104 | IdGenerator docstring | lines updated |
| 72–95was 101–124 | IdGenerator docstring, | lines updated |
| 97–120was 126–149 | IdGenerator. | lines updated |
| 123–139was 152–168 | UuidGenerator docstring | lines updated |
| 136–159was 165–188 | UuidGenerator docstring, | lines updated |
| 161–184was 190–213 | UuidGenerator. | lines updated |
| 187–196was 216–225 | _generate_next_id(), | lines updated |
The chunk that held the function is deleted. Every chunk after it keeps its text and moves up 29 lines (the function and the 2 blank lines after it), so 7 rows are rewritten with new line numbers and no chunk is embedded.
- EMBED_MODEL = "…/all-MiniLM-L6-v2"+ EMBED_MODEL = "…/another-model"process_file- runs
- Embedding calls
- 11
- Rows written
- +0 −0 ~11 inserted, deleted, updated
- Rows kept
- 0
| Lines | Chunk | Row |
|---|---|---|
| 1–25 | module docstring, | re-embedded, updated |
| 18–31 | imports, | re-embedded, updated |
| 32–57 | generate_id() | re-embedded, updated |
| 60–86 | generate_uuid() | re-embedded, updated |
| 89–104 | IdGenerator docstring | re-embedded, updated |
| 101–124 | IdGenerator docstring, | re-embedded, updated |
| 126–149 | IdGenerator. | re-embedded, updated |
| 152–168 | UuidGenerator docstring | re-embedded, updated |
| 165–188 | UuidGenerator docstring, | re-embedded, updated |
| 190–213 | UuidGenerator. | re-embedded, updated |
| 216–225 | _generate_next_id(), | re-embedded, updated |
EMBEDDER is declared with detect_change=True, so a new embedder invalidates the memo of process_file for every file. Each chunk is embedded again, but its text is unchanged, so it keeps its id: each row is updated in place, with no rows added or removed. If the new model has another dimension, the column type changes too.
- python/cocoindex/resources/id.pyprocess_file- not mounted
- Embedding calls
- 0
- Rows written
- +0 −11 ~0 inserted, deleted, updated
- Rows kept
- 0
| Lines | Chunk | Row |
|---|---|---|
| 1–25 | module docstring, | deleted |
| 18–31 | imports, | deleted |
| 32–57 | generate_id() | deleted |
| 60–86 | generate_uuid() | deleted |
| 89–104 | IdGenerator docstring | deleted |
| 101–124 | IdGenerator docstring, | deleted |
| 126–149 | IdGenerator. | deleted |
| 152–168 | UuidGenerator docstring | deleted |
| 165–188 | UuidGenerator docstring, | deleted |
| 190–213 | UuidGenerator. | deleted |
| 216–225 | _generate_next_id(), | deleted |
The source no longer lists the file, so its processing component is not mounted, and the 11 rows it owned are deleted.
Chunks come from RecursiveSplitter in cocoindex 1.1.1 with chunk_size=1000, min_chunk_size=300, chunk_overlap=300, before and after each edit. Row ids follow IdGenerator.next_id(chunk.text): the same chunk text keeps the same id. Unchanged text gets its embedding from the memo of SentenceTransformerEmbedder.embed, with no model call.
Changes to the indexed code
- A file is added: only that file is split and embedded, and its rows are inserted. The rest of the repo is untouched.
- A file is deleted: its rows are removed from the target.
- A file is edited: the whole file is read and split again. A chunk with unchanged text keeps its id and its embedding. If its lines moved, its row is rewritten with the new
start_lineandend_line, with no embedding call. A chunk with new text is embedded and inserted, and a chunk whose text is gone is deleted. In 3 of the demo’s 4 edits to the file’s text, only the chunk that holds the edit is replaced (or, for the deleted function, deleted). Because the splitter balances chunk sizes, an edit can also move a nearby boundary: the line inserted at line 123 also replaces the chunk at lines 89–104.
Changes to the pipeline
Pipeline changes are reconciled the same way: CocoIndex compares the new rows with the rows already in Postgres and applies only the difference.
- Change the file patterns (
included_patterns/excluded_patterns): files that now match are indexed, and rows of files that no longer match are deleted. - Tune the chunking (
chunk_size,chunk_overlap): the code ofprocess_filechanged, so every file is split again. Chunks whose text is unchanged keep their rows and embeddings; the rest are embedded and inserted, and the old ones deleted. - Swap the embedding model:
EMBEDDERis declared withdetect_change=True, so every chunk is embedded again. The chunk text is unchanged, so the ids stay the same: theembeddingcolumn is updated in place, with no rows added or removed. If the new model has a different dimension, CocoIndex also changes the column type (recreating the column if needed) and rewrites every row.
In live mode (cocoindex update -L main), each change is applied as you save.
Next steps
The full, runnable example is in the CocoIndex repo: examples/code_embedding, with a walkthrough in the index-codebase example.
- Point
sourcedirat your own repository. - Swap the embedding model or the target store; the pipeline is plain Python.
- Read the CocoIndex V1 docs for more on incremental processing, components, and targets.
Issues and contributions are welcome on GitHub.
Frequently asked questions
How does Tree-sitter improve RAG accuracy for codebases?
Fixed-size or line-window chunking cuts code at arbitrary offsets, so a chunk often starts mid-function or drops the signature, the imports, or the closing scope. Retrieval then returns fragments the model can't act on. CocoIndex chunks with Tree-sitter along the syntax tree: boundaries fall between syntax nodes where possible, so a chunk usually holds whole functions, classes or blocks, and a match comes back as code you can read and edit. A definition longer than the chunk size is split at its inner blocks. See Define file processing for the chunking step.
Each chunk also carries its start and end line, so results point at the matched lines.
How do I index a large codebase so AI coding agents can understand it?
The standard recipe is: walk the repository, split each file into syntax-aware chunks, embed every chunk, and store the vectors in a database your agent can search by similarity. Natural-language or code queries ("where do we embed chunks?") then retrieve the most relevant chunks as context. With CocoIndex the indexing pipeline is about 120 lines of Python. See the Overview for the three-step flow.
The engine handles fan-out across files, the managed vector index, and incremental updates so re-runs only touch what changed. Point sourcedir at your repo and run it; the full example lives at examples/code_embedding.
What is the best way to index a monorepo for AI code assistants?
A monorepo adds many languages, constant churn and paths you don't want indexed. CocoIndex's splitter is syntax-aware (Tree-sitter) for about 40 languages and falls back to separator-based splitting for 110 more, so polyglot repos need no per-language wiring. CocoIndex's PatternFilePathMatcher lets you include just the extensions you care about and exclude vendored or generated trees (node_modules, target, dot-directories). See Define the main function.
The churn problem is solved by incremental processing: a commit that touches 10 files re-processes those 10 files and re-embeds only their changed chunks, not the whole monorepo, so the index can be updated on every merge instead of in a nightly batch.
How do tools like Cursor or Aider index your codebase?
They represent two different families. Cursor builds an embedding index: it chunks files, embeds them, stores the vectors in a cloud index, and syncs on change using a Merkle tree so only changed files are re-uploaded. Aider uses a Tree-sitter "repo map" that extracts symbols and ranks them with a PageRank-style graph, then feeds the top signatures into the model's context. It uses no embeddings and no vector index.
CocoIndex is the build-your-own version of the embedding approach, with two differences: the index lives in your infrastructure, and the embedder can run locally, so you decide what scales to the cloud and what stays on the machine.
When should you use a dedicated codebase indexer like CocoIndex instead?
Reach for a dedicated indexer when you need control the IDE's built-in index doesn't give you: your choice of embedding model, vector store and chunking, and one index that's shared across tools (coding agents, review bots, search UIs) rather than locked inside a single editor. It also fits when the index has to stay live without a nightly rebuild, or when indexing is part of a product you ship. See Why CocoIndex for codebase indexing.
If you want autocomplete and chat in one editor, the built-in index is fine.
What is the difference between CocoIndex and built-in IDE code search?
Built-in IDE search is lexical and structural: it matches exact tokens, symbols, and definitions (grep, "go to definition", workspace symbol index). It's fast and precise when you know the name you're looking for. CocoIndex builds a semantic index with embeddings, so a query matches on meaning rather than spelling, which is what lets "where do we embed chunks?" find the right function even if those words never appear in the code. See Query the index.
The two are complementary: CocoIndex adds the retrieval layer that AI agents need, and because the index is a vector store you own, the same index is reusable outside the editor, including in review pipelines, MCP servers, or your own apps.
How do I choose between local-only codebase indexing and cloud-based indexing?
Local-only keeps the source and the embeddings on your machine and has no API cost; local compute sets the capacity. Cloud-based indexing scales to large codebases and lets a team share one index, at the cost of code or embeddings leaving the machine.
This example uses a local sentence-transformers embedder, and the target store is pluggable (Postgres/pgvector, Qdrant, LanceDB, and more), so the same pipeline runs fully local or points at a hosted vector database without changing the indexing code.
With a large corpus and many engineers, a shared index pays off: it is built and updated once, incrementally, instead of every engineer re-indexing the same repositories on their own machine. CocoIndex Code Plus (ccx) runs that shared index on your infrastructure and serves search, grep, and symbol definitions and references over the ccx CLI and MCP. See CocoIndex Code Plus, or contact us at [email protected].
How can I keep an AI codebase index in sync with frequent Git commits and CI/CD?
Re-process only the files and chunks that changed. CocoIndex fingerprints each file and each processing function with memoization; if neither changed, the file is skipped, so a commit that touches a few files re-processes only those files and re-embeds only their changed chunks. A delete removes its rows. See Incremental updates.
Two operating modes cover CI/CD and local dev. Run a catch-up pass (cocoindex update) as a post-merge step in your pipeline, or run live mode (cocoindex update -L) to watch the working tree and apply each change as you save.
What is the best way to handle private repositories and access control when indexing code?
Because CocoIndex runs the whole pipeline in your own infrastructure and can use a local embedder, source never has to hit a third-party API to be indexed. You also own the target store, so the vectors and metadata land where your existing access controls already apply.
For shared or multi-tenant indexes, give each row a stable key scoped per repository (or per team) and declare it that way, then filter at query time so each caller only retrieves what they're allowed to see. Keeping secrets out of the index is handled the same way you'd exclude any path: via the include/exclude patterns on the source.
Build fresh context for your agents.
CocoIndex keeps derived data in sync with its sources. Only what changed re-runs.


