GitHub

Python API

Everything RCE Code does is reached through one class: CodeEngine, the public facade over an index. It owns the SQLite database, the embedder, and the lexical, semantic, symbol, hybrid, and grep searchers, and exposes them as plain methods. This page documents every public method — exact signature, return type, and behavior — followed by the dataclasses those methods return.

Import the facade and the data types from the package root:

imports
from rce.code import (
CodeEngine, CodeConfig,
SearchResult, Chunk, Symbol, Reference, GrepHit, IndexStats,
ChunkKind, SymbolKind, SearchSource, Freshness,
)

One facade, one database

A CodeEngine instance wraps a single SQLite index for one repository. Construct it with CodeEngine.open_or_create(...) — never call CodeEngine(...) directly — and call close() when you are done. All query methods are read paths over the same database; only index(), refresh(), and embed() mutate it.

Lifecycle

open_or_create is the sole constructor. It builds a CodeConfig if you do not pass one, opens the SQLite database, and runs migrations before returning a ready instance.

MethodSignatureReturnsDescription
open_or_createopen_or_create(repo_path: str | Path, config: CodeConfig | None = None, embedder: Embedder | None = None)CodeEngineClassmethod. Open (or create) the index DB for repo_path and return a ready CodeEngine. Runs migrations; db_path defaults to <repo>/.rce/code/index.db. Defaults to the offline HashingEmbedder when no embedder is given.
closeclose()NoneClose the underlying database connection.

Indexing

index() builds (and incrementally updates) the index; refresh() is an alias of it; embed() fills in vector embeddings for chunks that lack a current one. See the Indexing Pipeline for what each stage does.

MethodSignatureReturnsDescription
indexindex()IndexSummaryBuild or update the index for the repo (walk → parse → chunk → symbols → refs → resolve). Idempotent; unchanged files are hash-skipped.
refreshrefresh()IndexSummaryRe-index the repo incrementally (alias of index): hash-skips unchanged files, re-parses changed ones, and drops files that no longer exist.
embedembed()intEmbed chunks that lack a current embedding. Returns the count embedded. Required before search_semantic returns anything; see Embedders.

Search

Four query paths over the indexed corpus. The three search_* methods return SearchResult lists ranked by score; grep runs live ripgrep over the working tree and returns GrepHit lists. See Search & Retrieval for when to reach for each.

MethodSignatureReturnsDescription
search_lexicalsearch_lexical(query: str, top_k: int = 10)list[SearchResult]FTS5 BM25 lexical search over indexed chunks; returns the top_k SearchResults. See Lexical Search.
search_semanticsearch_semantic(query: str, top_k: int = 10)list[SearchResult]Embedding cosine-KNN search over indexed chunks; returns the top_k SearchResults (empty if nothing is embedded yet). See Semantic Search.
search_hybridsearch_hybrid(query: str, top_k: int = 10)list[SearchResult]Reciprocal-Rank-Fusion of lexical + semantic + symbol search; returns the top_k fused SearchResults. See Hybrid Search.
grepgrep(pattern: str, *, glob: str | None = None, regex: bool = False, case_sensitive: bool = False, max_count: int | None = None, raw: bool = False)list[GrepHit]Live ripgrep over the working tree (fixed-string by default; regex if regex=True); honours the index ignore set unless raw=True. Returns GrepHits. See Grep.

grep keyword-only options

Every grep parameter after pattern is keyword-only (note the * in the signature). Pass them by name, e.g. engine.grep("TODO", glob="*.py", max_count=20).

Structural

Symbol- and reference-level queries over the resolved call graph. Methods that take a symbol_id expect the id of a Symbol you already have (typically from find_symbol or get_definitions). See Symbols & References.

MethodSignatureReturnsDescription
find_symbolfind_symbol(name: str, kind: SymbolKind | None = None)list[Symbol]Symbol definitions matching the exact name, optionally filtered by kind.
get_definitionsget_definitions(file: str)list[Symbol]All symbol definitions in the given file, in source order.
get_definition_atget_definition_at(file: str, line: int, col: int)Symbol | NoneInnermost symbol whose span contains (line, col), or None (col is 0-indexed).
get_symbols_in_chunkget_symbols_in_chunk(chunk_id: int)list[Symbol]Symbol definitions that belong to the given chunk.
find_referencesfind_references(name: str, is_import: bool | None = None)list[Reference]References by target name (resolved or not), optionally filtered to imports only.
get_references_fromget_references_from(symbol_id: int)list[Reference]Outgoing references originating in the given symbol's body (by name; may be unresolved).
get_referencesget_references(symbol_id: int)list[Reference]Resolved references whose target is this symbol (incoming).
get_callersget_callers(symbol_id: int)list[Symbol]Symbols that call the given symbol (resolved call graph).
get_calleesget_callees(symbol_id: int)list[Symbol]Symbols called by the given symbol (resolved call graph).

get_references vs. get_references_from

These names are easy to mix up. get_references(symbol_id) returns the incoming resolved references whose target is this symbol; get_references_from(symbol_id) returns the outgoing references that originate inside this symbol's body (which may still be unresolved).

Discovery

File-level helpers for listing and reading source. find_files and read_file work against the working tree on disk; list_files reads the set of files already in the index.

MethodSignatureReturnsDescription
find_filesfind_files(glob: str)list[str]Repo-relative paths of files on disk matching the glob, sorted.
read_fileread_file(rel_path: str, line_range: tuple[int, int] | None = None)strRead a repo-relative file as UTF-8 text; if line_range=(lo, hi) is given, return only those 1-indexed inclusive lines.
list_fileslist_files(language: str | None = None)list[str]Indexed file paths, sorted; optionally filtered to a single language.

Repo map

A single method produces an Aider-style, relevance-ranked map of the codebase, fit to a token budget. See Repo Map.

MethodSignatureReturnsDescription
build_repo_mapbuild_repo_map(focused_files: list[str] | None = None, mentioned_idents: list[str] | None = None, token_budget: int = 1024)strAider-style relevance-ranked repo map as text, fit to token_budget; bias toward focused_files / mentioned_idents.

Health

MethodSignatureReturnsDescription
statsstats()IndexStatsIndex health snapshot: file/chunk/symbol/ref counts, embedding coverage, last sync, and FTS status.

Return types

All return types are frozen dataclasses (and string enums) from rce.code.types. The tables below cover the fields you will use most; every dataclass is immutable.

SearchResult

Returned by search_lexical, search_semantic, and search_hybrid.

FieldTypeDescription
chunkChunkThe matched chunk (see below).
scorefloatRelevance score; higher is better. Comparable within one modality.
sourceSearchSourceWhich modality produced the hit: lexical, semantic, symbol, or hybrid.
freshnessFreshnessStaleness / embedding status of the underlying file (see below).
snippetstr | NoneAn optional highlighted excerpt of the match.
matched_termslist[str]The query terms that matched.

Chunk

A stored chunk — the unit of retrieval. Reached via SearchResult.chunk.

FieldTypeDescription
idintStable chunk id.
file_idintId of the file this chunk belongs to.
file_pathstrDenormalized repo-relative path of the file.
start_line / end_lineint1-indexed inclusive line span.
start_byte / end_byteintByte offsets of the chunk in the file.
kindChunkKindfunction, class, method, module, block, or doc.
namestr | NoneDefinition name, when the chunk is a named definition.
parent_chunk_idint | NoneEnclosing chunk, e.g. the class a method lives in.
is_skeletonboolTrue for a structural skeleton chunk rather than full body.
contentstrThe chunk's source text.
search_termsstrExpanded terms indexed for lexical search (e.g. identifier sub-tokens).
content_hashstrContent-address used for incremental indexing.
token_countintToken count of the chunk.
truncatedboolTrue if the chunk content was truncated.
languagestrDetected language of the file.

Symbol

A stored symbol definition. Returned by find_symbol, get_definitions, get_definition_at, get_symbols_in_chunk, get_callers, and get_callees.

FieldTypeDescription
idintStable symbol id — pass this to the call-graph and reference methods.
namestrBare symbol name.
qualified_namestrFully-qualified name, e.g. module.Class.method.
kindSymbolKindfunction, method, class, interface, type, enum, variable, constant, field, parameter, or module.
file_id / file_pathint / strOwning file (id and denormalized repo-relative path).
chunk_idint | NoneThe chunk this symbol resolves into, if any.
start_line / start_colintDefinition start position (col 0-indexed).
end_line / end_colintDefinition end position.
parent_idint | NoneEnclosing symbol (e.g. the class of a method).
signaturestr | NoneExtracted signature text, when available.
docstringstr | NoneAttached docstring, when present.
visibilityVisibility | Nonepublic, private, protected, or internal, when inferable.
languagestrLanguage of the defining file.

Reference

A stored reference (call or import). Returned by find_references, get_references_from, and get_references.

FieldTypeDescription
idintStable reference id.
from_symbol_idint | NoneSymbol the reference originates in, if attributable.
from_file_id / from_file_pathint / strSource file the reference appears in.
to_namestrTarget name as written at the reference site.
to_symbol_idint | NoneResolved target symbol; None until the resolver matches it.
resolution_confidencefloatConfidence of the resolution.
is_importboolTrue for an import reference, false for a call.
line / colintPosition of the reference site.
languagestrLanguage of the source file.

GrepHit

Returned by grep — one per matching line.

FieldTypeDescription
file_pathstrRepo-relative path of the matching file.
lineint1-indexed line number of the match.
columnintColumn of the match within the line.
line_textstrFull text of the matching line.
context_before / context_afterlist[str]Surrounding context lines (empty unless requested).

IndexStats

Returned by stats().

FieldTypeDescription
files / chunks / symbols / refsintRow counts for each indexed entity.
embedding_coveragefloatFraction of chunks that have a current embedding (0.0–1.0).
last_full_sync_atfloat | NoneUnix timestamp of the last full sync, or None.
stale_filesintCount of files newer on disk than in the index.
skippeddict[str, int]Skip reasons mapped to counts (e.g. too_large, binary).
fts_okboolWhether the FTS5 lexical index is healthy.

IndexSummary

Returned by index() and refresh() — the result of one indexing run.

FieldTypeDescription
files_indexedintFiles added or re-indexed this run.
files_deletedintFiles removed from the index (no longer on disk).
skippeddict[str, int]Skip reasons mapped to counts.

Freshness

Carried on every SearchResult as result.freshness.

FieldTypeDescription
file_mtimefloatOn-disk modification time of the file.
indexed_atfloatWhen the file was last indexed.
is_staleboolTrue if the file changed on disk after it was indexed.
has_embeddingboolTrue if the chunk has a current embedding.

End-to-end examples

Open or create an index, build it, embed pending chunks, and run each modality:

end_to_end.py
from rce.code import CodeEngine
engine = CodeEngine.open_or_create("/path/to/repo")
# Build (or incrementally update) the index, then embed pending chunks.
summary = engine.index()
print(f"indexed {summary.files_indexed}, deleted {summary.files_deleted}")
engine.embed()
# Lexical, semantic, and hybrid search all return list[SearchResult].
for hit in engine.search_hybrid("authentication middleware", top_k=5):
c = hit.chunk
print(round(hit.score, 3), hit.source, f"{c.file_path}:{c.start_line}", c.name)
# Live grep over the working tree (keyword-only options).
for h in engine.grep("TODO", glob="*.py", max_count=10):
print(f"{h.file_path}:{h.line}:{h.column} {h.line_text}")
# Repo map fit to a token budget.
print(engine.build_repo_map(focused_files=["src/auth.py"], token_budget=1024))
engine.close()

Walk the call graph from a named definition — resolve the symbol, then ask for its callers and callees:

call_graph.py
from rce.code import CodeEngine, SymbolKind
engine = CodeEngine.open_or_create("/path/to/repo")
engine.index()
for sym in engine.find_symbol("login", kind=SymbolKind.FUNCTION):
print("definition:", sym.qualified_name, f"{sym.file_path}:{sym.start_line}")
for caller in engine.get_callers(sym.id):
print(" called by:", caller.qualified_name)
for callee in engine.get_callees(sym.id):
print(" calls:", callee.qualified_name)
# Incoming resolved references vs. outgoing references from the body.
print(" incoming refs:", len(engine.get_references(sym.id)))
print(" outgoing refs:", len(engine.get_references_from(sym.id)))
engine.close()

Construct once, reuse

open_or_create runs migrations and opens the database, so call it once per repo and reuse the instance for many queries. Pair it with a try/finally that calls close(), or wrap the lifetime in your own context manager.