Skip to main content

code

Index a repository’s source code with kosha, search the files on disk with ripgrep, and combine both with the vault’s prose in one ranking

An index built for prose is a poor fit for source code. The useful units of code are functions and classes. The useful names are identifiers. What matters is which function calls which. kosha is the code index of the vault. It splits source files into functions and classes with their syntax tree. It embeds them with a model trained on code. It builds a call graph in which each symbol has a PageRank score, a measure of how central the symbol is. kosha keeps its index in .kosha/ inside the repository. It does not keep the index in the vault file.

index_code(dir) builds or updates that index. Later calls index only the files that changed. code_search searches the index. symbol(name) returns one function or class with its file, PageRank, callers and callees. where_to_add(description) ranks the places in the repository where a described change belongs.


source

Vault.index_code

def index_code(
    dir:str=None, # repo to index
    graph:bool=True, # also build the AST call graph (callers, callees, PageRank)
    env:bool=False, # also index installed packages (slow the first time)
    force:bool=False, # reindex everything, graph included, rather than what changed
    verbose:bool=False, **kw
)->dict: # forwarded to kosha's `sync`

Build or update kosha’s index of a repository, and return its status.


source

Vault.kosha

def kosha(
    dir:str=None, # repo root; defaults to the cwd repo
    share_encoder:bool=False, # embed code with the vault's encoder instead of kosha's
    **kw
):

The kosha index for the repository dir, kept on the vault so every code method uses the same one.

grep(pattern) runs ripgrep over the files on disk, through rgapi. It finds exact text. It also searches files that kosha never indexed and files that changed since the last index_code. It respects .gitignore.


source

Vault.grep

def grep(
    pattern:str, # a ripgrep regex
    dir:str='.', # tree to search
    limit:int=20, # matching lines returned
    **kw
)->fastcore.foundation.L: # forwarded to rgapi.rg (glob=, ext=, context=, hidden=, ...)

Find exact matches in the files on disk with ripgrep, respecting .gitignore.


source

Vault.where_to_add

def where_to_add(
    description:str, limit:int=5, dir:str=None
)->fastcore.foundation.L:

Rank the places in the indexed repository where a described change belongs.


source

Vault.symbol

def symbol(
    name:str, depth:int=1, dir:str=None
)->fastcore.basics.AttrDict:

Look up a function or class in the call graph: its file, PageRank and number of links, with its callers and callees.


source

Combining the three searches

federate(q) runs several searches at once. Each search is called a leg. The legs are the prose of the vault, each other shelf, the kosha index of the repository (and of installed packages with env=True), and ripgrep. The vault and kosha use different embedding models, and ripgrep uses no model. Their scores cannot be compared. federate merges the legs by rank with reciprocal rank fusion, which needs only the order of each leg. weights= favours one leg over another. Every hit has the same fields: source (the leg), ref, title, where and text. It also has open, which says how to open the hit. A leg that fails is reported in legs and in note. The other legs still answer.


source

Vault.federate

def federate(
    q:str, # the query
    limit:int=12, # fused hits returned
    prose:bool=True, # the vault's own documents, papers, notes
    repo:bool=True, # kosha's repo index
    env:bool=False, # kosha's installed-package index
    grep:bool=True, # ripgrep over the working tree
    kind:str=None, # restrict the prose leg to some KINDS
    shelves:bool=True, # other shelves as their own legs: True for all, a list to pick, None for none
    weights:dict=None, # per-leg RRF weights, e.g. {'prose':1.0,'repo':1.5}
    dir:str=None, # repo for the code and grep legs
    per_leg:int=None, # hits pulled from each leg before fusion
    *, pii:str='off', pii_ner:bool=False, stale:bool=False
)->fastcore.basics.AttrDict:

Search prose, other shelves, indexed code and the files on disk at once, and merge the results by rank.

Code in an answer

When kosha has indexed the repository, .kosha/code.db exists. Then context and ask add code hits after the prose sections (code=4 by default). A code hit has the same fields as a section. The prompt and the citations treat both alike. A code hit has no node_id, because read cannot open it. Its filename is path:line on disk.


source

code_sections

def code_sections(
    v, # the Vault
    q:str, # the question
    n:int=4, # code hits to keep
    dir:str=None, # repo for the kosha and ripgrep legs
    **kw
)->fastcore.foundation.L: # forwarded to federate

Code hits from federate, shaped like vault sections so that ask can number and cite them like any other.


source

kosha_indexed

def kosha_indexed(
    dir:str=None
)->bool:

Whether kosha has already indexed this repository, checked by looking for its file.

Try it

Each leg can be turned off. Each leg fails on its own. This example runs only the prose leg.

v = Vault(':memory:')
v.note('litesearch fuses the FTS and vector legs with reciprocal rank fusion.')
f = v.federate('rank fusion', repo=False, grep=False)
f.hits[0].where, f.legs, f.note
/Users/71293/code/personal/orgs/vishalakshi/.venv/lib/python3.13/site-packages/tqdm/auto.py:21: TqdmWarning: IProgress not found. Please update jupyter and ipywidgets. See https://ipywidgets.readthedocs.io/en/stable/user_install.html
  from .autonotebook import tqdm as notebook_tqdm
('litesearch fuses the FTS and vector legs with reciprocal rank fusion.',
 {'prose': 1},
 'RRF over prose; the legs use different encoders, so ranks are fused, not distances')
test_eq(f.legs['prose'], 1)
test_eq(f.hits[0].source, 'prose')
# every leg off: empty, not an error (shelves=None too, or an existing shelf would answer)
test_eq(v.federate('rank fusion', prose=False, repo=False, grep=False, shelves=None).hits, [])
assert v.grep('reciprocal rank fusion', '.')                                     # ripgrep reads the disk, not the vault
v.grep = lambda *a, **kw: 1/0
f3 = v.federate('rank fusion', repo=False)
assert f3.note.startswith('search incomplete, grep (ZeroDivisionError') and f3.legs['prose'] == 1, f3.note
del v.grep