codenib
¶
Public CodeNib API.
Exports are resolved lazily so importing :mod:codenib or starting the CLI
does not initialize optional graph, embedding, and agent runtimes.
Modules:
| Name | Description |
|---|---|
agent |
Agent package consolidating agent utilities and implementations. |
artifacts |
Portable repository-context artifacts. |
cli |
User-facing CodeNib command line interface. |
clients |
Runnable agent policies and external-agent execution adapters. |
code_chunker |
Code chunking module with both file-level and repository-level functionality. |
code_chunking |
Code chunking module for splitting source code files into semantic chunks. |
codegraph_onboarding |
Managed MCP client registration for the CodeGraph product path. |
compat_pickle |
Read pickles written before the package rename. |
compiler |
Compiler infrastructure for CodeNib. |
context_delivery |
Bounded, query-focused delivery of repository evidence. |
dataset |
|
dataset_ids |
Canonical identifiers for externally hosted CodeNib datasets. |
eval |
Evaluation harnesses: agent runners, retrieval metrics, artifact bundles. |
facts |
Provider-neutral, per-file semantic fact contracts. |
git_snapshot |
Git-backed source boundaries for reproducible repository artifacts. |
graph |
Graph-related modules for CodeNib. |
index |
Index-related components: sparse, dense, and regex. |
integrations |
Compatibility providers for external coding-agent runtimes. |
languages |
Central language metadata registry. |
llm |
LLM module for CodeNib. |
log_utils |
|
ls_index |
Language-server indexers and decoders. |
ls_router |
Unified language-server router for indexing and decoding across all languages. |
mcp |
CodeNib MCP server - exposes backbone capabilities over stdio. |
model |
Model pipelines and planners exposed without eager optional imports. |
native_index_authorization |
Out-of-band authorization for native index parsers. |
ops |
Composable retrieval operators: retrieve, expand, filter, rerank, transform. |
paths |
Canonical filesystem locations owned by CodeNib. |
profiler |
|
provider_routes |
Secret-free provider identities and process-local inference routes. |
repository_filters |
Shared repository traversal policy for user-facing index builders. |
repository_source_selection |
Canonical, backend-neutral repository source-selection policy. |
repository_summary |
Extract a concise project purpose from repository README files. |
sandbox |
Provider-neutral isolation for repository execution. |
scip_interface |
Language-specific SCIP indexing and decoding. |
search |
|
serving |
Retrieval-augmented speculative serving for code agents. |
source_fingerprint |
Deterministic content identity for repository files visible to CodeNib. |
storage |
Wiki-only database boundary. |
toolchains |
Managed external language tools for graph and LSP providers. |
types |
|
utils |
|
web |
DeepWiki-style demo backend. |
wiki |
Index-derived wiki generation for the DeepWiki-style demo. |
Classes:
| Name | Description |
|---|---|
PublishedWorkspaceReceiptOwner |
Caller-precreated one-shot owner for a published workspace generation. |
LocalWorkspaceProvider |
Provision strict workspaces below one private Linux authority root. |
KeywordExtractor |
Agent for extracting keywords from problem statements. |
RerankAgent |
Agent for reranking code nodes based on query relevance using LLM APIs. |
CodeChunker |
Unified code chunker that supports both file-level and repository-level processing. |
RepoChunkingConfig |
Configuration for repository chunking. |
CodeGraph |
A class to represent and manipulate a code graph using igraph. |
CodeVectorStore |
Vector store for code embeddings using FAISS and sentence-transformers. |
RegexNodeIndex |
In-memory regex-based index for CodeGraph nodes. |
BM25CodeIndexer |
A class that builds a BM25 index from CodeGraph nodes and provides |
LSIndexer |
Unified indexer that delegates to language-specific implementations. |
CodeSearchEngine |
Integrated search engine that combines SCIP indexing, code graph representation, |
Functions:
| Name | Description |
|---|---|
create_code_vector_store |
Factory function to create a CodeVectorStore. |
PublishedWorkspaceReceiptOwner
¶
Caller-precreated one-shot owner for a published workspace generation.
Methods:
| Name | Description |
|---|---|
consume |
Synchronously borrow one exact authenticated publication reader. |
Attributes:
| Name | Type | Description |
|---|---|---|
destination_binding |
PublishedWorkspaceDestinationBinding
|
Project the exact destination binding from this active generation. |
Source code in codenib/_captured_directory.py
destination_binding
property
¶
Project the exact destination binding from this active generation.
consume
¶
consume(
callback: Callable[
[PublishedWorkspaceReceipt, PublicationDirectoryReader], _WorkspaceResult
],
*,
check_cancelled: Callable[[], None] | None = None
) -> _WorkspaceResult
Synchronously borrow one exact authenticated publication reader.
Source code in codenib/_captured_directory.py
LocalWorkspaceProvider
dataclass
¶
LocalWorkspaceProvider(
allowed_root: Path, provision_timeout_ns: int = _DEFAULT_PROVISION_TIMEOUT_NS
)
Provision strict workspaces below one private Linux authority root.
KeywordExtractor
¶
KeywordExtractor(llm: LiteLLMChat)
Agent for extracting keywords from problem statements.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
llm
|
LiteLLMChat
|
A configured LiteLLMChat instance. |
required |
Methods:
| Name | Description |
|---|---|
extract_keywords |
Extract keywords from a problem statement. |
Source code in codenib/agent/extract_agent.py
extract_keywords
¶
extract_keywords(problem_statement: str) -> KeywordExtraction
Extract keywords from a problem statement.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
problem_statement
|
str
|
The problem statement to extract keywords from |
required |
Returns:
| Name | Type | Description |
|---|---|---|
KeywordExtraction |
KeywordExtraction
|
Structured output with extracted keywords |
Source code in codenib/agent/extract_agent.py
RerankAgent
¶
RerankAgent(
llm: LiteLLMChat, listwise_format: Literal["structured", "rankgpt"] = "structured"
)
Agent for reranking code nodes based on query relevance using LLM APIs.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
llm
|
LiteLLMChat
|
A configured LiteLLMChat instance. |
required |
listwise_format
|
Literal['structured', 'rankgpt']
|
How to ask the LLM to format the ranking.
|
'structured'
|
Methods:
| Name | Description |
|---|---|
rerank_nodes |
Rerank nodes based on their relevance to the query. |
Source code in codenib/agent/rerank_agent.py
rerank_nodes
¶
rerank_nodes(
query: str,
nodes: list[NodeInfo],
top_k: int | None = None,
window_size: int | None = None,
window_step: int | None = None,
include_content: bool = False,
) -> list[QueriedNode]
Rerank nodes based on their relevance to the query.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
query
|
str
|
The query to rank nodes against |
required |
nodes
|
list[NodeInfo]
|
List of nodes with content to rank |
required |
top_k
|
int | None
|
Maximum number of results to return (None for all) |
None
|
window_size
|
int | None
|
Number of nodes per rerank window. None -> all nodes. |
None
|
window_step
|
int | None
|
Step size between sliding windows. Defaults to window_size. |
None
|
include_content
|
bool
|
Whether to include node content in the result objects. |
False
|
Returns:
| Type | Description |
|---|---|
list[QueriedNode]
|
List[QueriedNode]: Ranked nodes with relevance scores (optionally with content) |
Notes
When a sliding window is configured, each window is reranked independently and the averaged scores across all windows determine the final ordering.
Source code in codenib/agent/rerank_agent.py
81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 | |
CodeChunker
¶
CodeChunker(
language: str = "python",
repo_config: RepoChunkingConfig | None = None,
max_lines_per_chunk: int | None = None,
chunk_depth: int = 2,
include_header_epilogue: bool = False,
l2_level_exclusive: bool = True,
skeleton_mode: bool = False,
include_l2_in_file_skeleton: bool = True,
)
Unified code chunker that supports both file-level and repository-level processing. Maintains backward compatibility with the old API while adding repository functionality.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
language
|
str
|
Programming language to parse ('python', 'cpp', 'java', etc.) |
'python'
|
repo_config
|
RepoChunkingConfig | None
|
Configuration for repository-level chunking. Uses defaults if None. |
None
|
max_lines_per_chunk
|
int | None
|
Maximum number of lines per emitted chunk. Default: None (no splitting) |
None
|
chunk_depth
|
int
|
Depth of AST traversal (1=top-level only, 2=include methods) |
2
|
include_header_epilogue
|
bool
|
Whether to include file headers and epilogues. Default: False |
False
|
l2_level_exclusive
|
bool
|
When chunk_depth is 2, whether to omit L1 container nodes (classes/structs/impls) and emit only L2 members. Default: True. |
True
|
skeleton_mode
|
bool
|
Emit signature-only skeletons instead of full bodies when True. |
False
|
include_l2_in_file_skeleton
|
bool
|
When chunk_depth is 0, include member signatures in file-level skeletons. Default: True. |
True
|
Methods:
| Name | Description |
|---|---|
chunk_file |
Chunk a code file into function/class level pieces. |
save_chunks_to_json |
Save chunks to a JSON file. |
print_chunk_summary |
Print a summary of the generated chunks. |
chunk_repository |
Chunk all relevant files in a repository. |
chunk_repository_source |
Chunk one retained repository generation without path-based reads. |
get_repository_stats |
Get statistics about the repository without processing files. |
print_repository_summary |
Print a summary of all chunks from the repository. |
chunk_swebench_instance |
Chunk a SWE-bench instance repository. |
save_swebench_chunks |
Save SWE-bench chunking result to JSON file. |
clear_nodes |
Clear the collected nodes list. |
Source code in codenib/code_chunker.py
chunk_file
¶
Chunk a code file into function/class level pieces.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
file_path
|
str
|
Path to the code file to chunk |
required |
relative_path
|
str | None
|
Relative path for node_id generation. If None, uses file_path. |
None
|
skeleton_mode
|
bool | None
|
Override instance-level skeleton setting. When True, chunk content contains signatures only. |
None
|
Returns:
| Type | Description |
|---|---|
|
List of CodeChunk objects |
Source code in codenib/code_chunker.py
save_chunks_to_json
¶
print_chunk_summary
¶
chunk_repository
¶
Chunk all relevant files in a repository.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
repo_path
|
str
|
Path to the repository root. Languages come from RepoChunkingConfig; when empty they are inferred from file extensions present in the repo. |
required |
strict
|
bool
|
Raise when any discovered source file cannot be chunked instead of returning a partial repository result. |
False
|
Returns:
| Type | Description |
|---|---|
list[CodeChunk]
|
List of CodeChunk objects from all processed files |
Raises:
| Type | Description |
|---|---|
ValueError
|
If repo_path doesn't exist or languages are unsupported |
Source code in codenib/code_chunker.py
252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 | |
chunk_repository_source
¶
chunk_repository_source(
repository_source: RepositorySourceBinding,
*,
check_cancelled: Callable[[], None] | None = None
) -> list[CodeChunk]
Chunk one retained repository generation without path-based reads.
The binding supplies the complete authenticated file inventory and all source bytes. Discovery, filtering, decoding, and parsing therefore operate on that fixed generation even when the repository is also visible through a mutable public pathname.
Source code in codenib/code_chunker.py
331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 | |
get_repository_stats
¶
Get statistics about the repository without processing files.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
repo_path
|
str
|
Path to the repository root. Languages come from RepoChunkingConfig; when empty they are inferred. |
required |
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
Dictionary containing repository statistics |
Source code in codenib/code_chunker.py
print_repository_summary
¶
Print a summary of all chunks from the repository.
Source code in codenib/code_chunker.py
chunk_swebench_instance
¶
chunk_swebench_instance(
instance: dict[str, Any],
cache_dir: str | None = None,
languages: list[str] | None = None,
) -> dict[str, Any]
Chunk a SWE-bench instance repository.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
instance
|
dict[str, Any]
|
SWE-bench instance dictionary containing repo, base_commit, instance_id, etc. |
required |
cache_dir
|
str | None
|
Directory to cache repositories. Defaults to ~/.codenib |
None
|
languages
|
list[str] | None
|
List of languages to process. If None, uses repository's primary language |
None
|
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
Dictionary containing instance info, repo path, and chunks |
Source code in codenib/code_chunker.py
save_swebench_chunks
¶
Save SWE-bench chunking result to JSON file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
swebench_result
|
dict[str, Any]
|
Result from chunk_swebench_instance() |
required |
output_path
|
str
|
Path to save the JSON file |
required |
Source code in codenib/code_chunker.py
RepoChunkingConfig
dataclass
¶
RepoChunkingConfig(
languages: list[str] = list(),
python_extensions: set[str] | None = None,
cpp_extensions: set[str] | None = None,
csharp_extensions: set[str] | None = None,
rust_extensions: set[str] | None = None,
go_extensions: set[str] | None = None,
java_extensions: set[str] | None = None,
ruby_extensions: set[str] | None = None,
php_extensions: set[str] | None = None,
kotlin_extensions: set[str] | None = None,
swift_extensions: set[str] | None = None,
scala_extensions: set[str] | None = None,
lua_extensions: set[str] | None = None,
javascript_extensions: set[str] | None = None,
typescript_extensions: set[str] | None = None,
ignore_dirs: set[str] = None,
include_dirs: set[str] = None,
source_selection: RepositorySourceSelection = RepositorySourceSelection(),
ignore_patterns: set[str] = None,
max_file_size_mb: float = 10.0,
filter_tests: bool = True,
skip_minified: bool = True,
minified_line_threshold: int = 10000,
)
Configuration for repository chunking.
Methods:
| Name | Description |
|---|---|
__post_init__ |
Initialize default values. |
__post_init__
¶
Initialize default values.
Source code in codenib/code_chunker.py
CodeGraph
¶
A class to represent and manipulate a code graph using igraph. start_line uses 0-based index.
Methods:
| Name | Description |
|---|---|
add_file_node |
Add a file node to the graph and set it as the current file and scope. |
add_symbol_node |
Add a symbol node to the graph. |
add_symbol_reference |
Add a reference to a symbol. |
update_current_scope |
Update the current scope to the given symbol with its range. |
exit_scopes_by_line |
Exit scopes that have ended based on current line number. |
add_containment_edge |
Add a containment edge from current scope to a symbol. |
batch_edges |
Defer igraph edge insertion until the block exits, flushing all |
invalidate_caches |
Invalidate derived indexes after direct graph mutation. |
build_range_indexes |
Rebuild per-file line-range indexes from current graph state. |
merge_from |
Merge another |
query_range |
Query the graph by source-file line range (LSP-aligned). |
query_range_by_symbol |
Range-query by symbol identity ( |
layers |
Build a multi-graph layer index over this graph. |
layer |
Return one named graph layer view. |
add_root_node |
Add the root node to the graph |
add_directory_node |
Add a directory node to the graph |
save_graph |
Save the graph to a pickle file for fast serialization. |
load_graph |
Load a graph from a pickle file. |
load_graph_stream |
Load a graph from a caller-authenticated binary stream. |
get_graph |
Get the igraph Graph object. |
unified_index |
Readable |
display_name |
Readable label for a canonical name ( |
resolve_symbol |
Map a readable/bare symbol to (canonical_name | None, candidates). |
get_node_info_by_name |
Get information about a node in the graph. |
get_node_info_by_id |
Get information about a node in the graph. |
get_node_content |
Get the content of a node in the graph. |
get_neighbors |
Get the neighbors of a node in the graph. |
get_successors |
Get the successors of a node_name (outgoing edges). |
get_predecessors |
Get the predecessors of a node_name (incoming edges). |
print_graph_basic_info |
Print basic information about the graph. |
visualize_graph |
Visualize the code graph with different colors for different node and edge types. |
Source code in codenib/graph/code_graph.py
add_file_node
¶
Add a file node to the graph and set it as the current file and scope.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
file_path
|
Path of the file to add |
required |
Source code in codenib/graph/code_graph.py
add_symbol_node
¶
add_symbol_node(
symbol,
line,
scope_start_line=None,
scope_end_line=None,
symbol_type=None,
symbol_kind=None,
)
Add a symbol node to the graph.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
symbol
|
Symbol name |
required | |
line
|
Line number of the symbol |
required | |
scope_start_line
|
Start line of the symbol's scope (optional) |
None
|
|
scope_end_line
|
End line of the symbol's scope (optional) |
None
|
|
symbol_type
|
Type of symbol (NODE_TYPE_CLASS, NODE_TYPE_METHOD, NODE_TYPE_FUNCTION) (optional) |
None
|
Source code in codenib/graph/code_graph.py
add_symbol_reference
¶
add_symbol_reference(
symbol,
module_path=None,
symbol_type=None,
anchor_file: str | None = None,
anchor_line: int | None = None,
symbol_kind=None,
)
Add a reference to a symbol.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
symbol
|
Symbol being referenced |
required | |
module_path
|
Path of the module containing the symbol (optional) |
None
|
|
symbol_type
|
Type of symbol (NODE_TYPE_CLASS, NODE_TYPE_METHOD, NODE_TYPE_FUNCTION) (optional) |
None
|
|
anchor_file
|
str | None
|
File where the reference site is located (optional) |
None
|
anchor_line
|
int | None
|
0-based line of the reference site (optional) |
None
|
Source code in codenib/graph/code_graph.py
update_current_scope
¶
Update the current scope to the given symbol with its range.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
symbol
|
Symbol to set as current scope |
required | |
start_line
|
Start line of the symbol's scope |
None
|
|
end_line
|
End line of the symbol's scope |
None
|
Source code in codenib/graph/code_graph.py
exit_scopes_by_line
¶
Exit scopes that have ended based on current line number. File scope (with None range) is never popped.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
current_line
|
Current line number being processed |
required |
Source code in codenib/graph/code_graph.py
add_containment_edge
¶
Add a containment edge from current scope to a symbol.
CONTAIN edges deliberately carry no anchor — containment is a
structural relation, not a call/reference site. (See anchor invariant
ii on query_range.)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
target_symbol
|
Symbol being contained. |
required |
Source code in codenib/graph/code_graph.py
batch_edges
¶
Defer igraph edge insertion until the block exits, flushing all
buffered edges in a single add_edges call.
igraph rebuilds its internal adjacency index on every add_edges
call, so inserting one edge at a time (as bare _add_edge does) is
O(E^2) in the number of edges — the dominant cost when decoding a large
repo. Wrapping a build loop in this context collapses that to O(E):
with graph.batch_edges():
# ... many add_symbol_reference / _add_edge calls ...
Edge dedup is unaffected (the dedup index is updated as edges are
buffered). Edge ids returned by _add_edge while buffering are
provisional and only become real after flush; no caller relies on them
mid-build. Outside this block _add_edge inserts immediately, so the
incremental patcher and all other callers are unchanged. Nesting is a
no-op (the outermost block owns the flush).
Source code in codenib/graph/code_graph.py
invalidate_caches
¶
build_range_indexes
¶
Rebuild per-file line-range indexes from current graph state.
Call this after the graph is fully constructed by a decoder, and
again after any incremental patcher batch. The two indexes are
pickled with the graph by save_graph, so subsequent load_graph
calls do not need to rebuild.
Cost: O(V + E) — one linear pass over vertices and edges.
Source code in codenib/graph/code_graph.py
merge_from
¶
merge_from(other: CodeGraph) -> None
Merge another CodeGraph into this one.
Vertices are keyed by their canonical name attribute. Existing
vertices receive any attributes from other; missing vertices are
inserted. Edges are copied through _add_edge so structural edge
deduplication and anchored reference multi-edges keep the same
semantics as decoder-built graphs.
Source code in codenib/graph/code_graph.py
query_range
¶
query_range(
file: str,
start_line: int,
end_line: int,
kinds: set | None = None,
depth: int = 1,
*,
layer: str | None = None
) -> RangeQueryResult
Query the graph by source-file line range (LSP-aligned).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
file
|
str
|
source file (graph-relative path). |
required |
start_line
|
int
|
first line of the inclusive 0-based span. |
required |
end_line
|
int
|
last line of the inclusive 0-based span. |
required |
kinds
|
set | None
|
edge kinds to include in |
None
|
depth
|
int
|
reserved for future multi-hop expansion. Only |
1
|
layer
|
str | None
|
optional named graph layer ( |
None
|
Returns: RangeQueryResult with typed NodeRef/EdgeRef records.
Anchor invariants
(i) anchor_file == source.file (anchor lives at the call site, never the target). (ii) anchor_* is meaningful only on EDGE_TYPE_REFERENCE; CONTAIN edges leave both fields None. (iii) outgoing ∩ incoming = ∅ for any single query (call site and target are in distinct scopes by definition).
Source code in codenib/graph/code_graph.py
652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 | |
query_range_by_symbol
¶
query_range_by_symbol(
name: str, kinds: set | None = None, depth: int = 1, *, layer: str | None = None
) -> RangeQueryResult
Range-query by symbol identity (name).
Resolves name -> vid -> (file, start_line, end_line) and forwards
to query_range. name is the globally-unique identity attribute
(semi-raw SCIP symbol), not the unified_name display.
Returns an empty RangeQueryResult if the symbol is unknown or has no associated file/range (e.g. a SCIP reference-only vertex).
Source code in codenib/graph/code_graph.py
layers
¶
layer
¶
add_root_node
¶
add_directory_node
¶
save_graph
¶
Save the graph to a pickle file for fast serialization.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
output_path
|
Path to save the pickle file |
required |
Source code in codenib/graph/code_graph.py
load_graph
classmethod
¶
Load a graph from a pickle file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
input_path
|
Path to the pickle file |
required |
Returns:
| Name | Type | Description |
|---|---|---|
CodeGraph |
Loaded graph instance |
Source code in codenib/graph/code_graph.py
load_graph_stream
classmethod
¶
Load a graph from a caller-authenticated binary stream.
The serialized schema is unchanged. Runtime loaders use this entry point after binding the bytes to the manifest receipt, so they never need to reopen an already-verified pathname before unpickling it.
Source code in codenib/graph/code_graph.py
get_graph
¶
unified_index
¶
Readable unified_name (full + bare) -> [canonical names], cached.
Rebuilds from vertex attributes when the persisted _unified_to_names
is empty (older prebuilt graphs ship it empty even though every vertex
carries a unified_name).
Source code in codenib/graph/code_graph.py
display_name
¶
Readable label for a canonical name (unified_name or itself).
resolve_symbol
¶
Map a readable/bare symbol to (canonical_name | None, candidates).
Tries the canonical name first, then the readable unified_name
(full display, then bare token), then a substring match. None when
ambiguous or missing; candidates are readable display names.
Source code in codenib/graph/code_graph.py
get_node_info_by_name
¶
Get information about a node in the graph.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
node_name
|
Name of the node |
required |
Returns:
| Type | Description |
|---|---|
|
Dictionary with vertex attributes or None if not found |
Source code in codenib/graph/code_graph.py
get_node_info_by_id
¶
Get information about a node in the graph.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
node_id
|
ID of the node |
required |
Returns:
| Type | Description |
|---|---|
|
Dictionary with vertex attributes or None if not found |
Source code in codenib/graph/code_graph.py
get_node_content
¶
Get the content of a node in the graph. Read the file from start_line to end_line. If the node is a file, return the file content.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
node_id
|
ID of the node |
required |
Returns:
| Type | Description |
|---|---|
|
Content of the node or None if not found |
Source code in codenib/graph/code_graph.py
get_neighbors
¶
Get the neighbors of a node in the graph.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
node_name
|
Name of the node |
required |
Returns:
| Type | Description |
|---|---|
|
List of neighbor vertex IDs |
Source code in codenib/graph/code_graph.py
get_successors
¶
Get the successors of a node_name (outgoing edges).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
node_name
|
Name of the node |
required | |
edge_types
|
Optional edge types to retain. Typed traversal returns unique neighbors even when the graph contains multi-edges. |
None
|
Returns:
| Type | Description |
|---|---|
|
List of successor vertex IDs |
Source code in codenib/graph/code_graph.py
get_predecessors
¶
Get the predecessors of a node_name (incoming edges).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
node_name
|
Name of the node |
required | |
edge_types
|
Optional edge types to retain. Typed traversal returns unique neighbors even when the graph contains multi-edges. |
None
|
Returns:
| Type | Description |
|---|---|
|
List of predecessor vertex IDs |
Source code in codenib/graph/code_graph.py
print_graph_basic_info
¶
Print basic information about the graph.
Source code in codenib/graph/code_graph.py
visualize_graph
¶
Visualize the code graph with different colors for different node and edge types.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
output_path
|
Path to save the visualization (optional) |
None
|
|
width
|
Width of the plot in pixels |
800
|
|
height
|
Height of the plot in pixels |
600
|
|
layout
|
Layout algorithm to use ('fruchterman_reingold', 'kk', 'grid', etc.) |
'fruchterman_reingold'
|
Returns:
| Type | Description |
|---|---|
|
A matplotlib figure object if output_path is not provided |
Source code in codenib/graph/code_graph.py
1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 | |
CodeVectorStore
¶
CodeVectorStore(
embedding_model: str = "text-embedding-ada-002",
embedding_provider: str = "openai",
dimension: int = 1536,
index_type: str = "flat",
index_metric: str = "ip",
ivf_nlist: int = 100,
ivf_nprobe: int = 8,
store_path: str | None = None,
profiler: Profiler | None = None,
embedding: Any | None = None,
artifact_metadata: dict[str, Any] | None = None,
**embedding_kwargs
)
Vector store for code embeddings using FAISS and sentence-transformers. Provides semantic search capabilities over code chunks.
Supports hierarchical indexing: - L0: File-level skeletons - L2: Function/method-level chunks for fine-grained retrieval (default)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
embedding_model
|
str
|
Name of the embedding model to use |
'text-embedding-ada-002'
|
embedding_provider
|
str
|
Provider for embeddings ("openai" or "huggingface") |
'openai'
|
dimension
|
int
|
Dimension of the embedding vectors |
1536
|
index_type
|
str
|
FAISS index type — "flat" (exact brute force, default) or "ivf" (IVF inverted-file; approximate, faster at scale). IVF indices are trained lazily on the first batch of vectors. |
'flat'
|
index_metric
|
str
|
Distance metric ("ip" for inner product, "l2" for L2 distance) |
'ip'
|
ivf_nlist
|
int
|
IVF only — number of Voronoi cells (coarse centroids). On
small corpora it is clamped down to the training-set size, since
FAISS k-means needs at least |
100
|
ivf_nprobe
|
int
|
IVF only — cells probed per query; the recall/latency
knob. Clamped to the effective |
8
|
store_path
|
str | None
|
Path to store/load the vector store |
None
|
profiler
|
Profiler | None
|
Optional profiler instance to capture detailed timings |
None
|
embedding
|
Any | None
|
A pre-built embedding wrapper to reuse. When several stores share one model (e.g. one per repo), pass the same instance so the model is loaded onto the GPU only once. |
None
|
artifact_metadata
|
dict[str, Any] | None
|
Optional immutable source/build identity persisted with the top-level configuration. |
None
|
**embedding_kwargs
|
Additional arguments for embedding model |
{}
|
Methods:
| Name | Description |
|---|---|
reuse_query_embedding |
Reuse one query vector within a composed request, then discard it. |
clear_query_cache |
Clear the single-query embedding reused by consecutive search stages. |
swap_index |
Hot-swap the FAISS index without reloading the embedding model. |
close |
Release embeddings and FAISS resources to free memory. |
add_code_chunks |
Add code chunks to the vector store. |
add_nodes_with_content |
Add NodeInfo objects (with content) to the vector store. |
search |
Search for similar code chunks using semantic similarity. |
search_with_content |
Search and return results with content included. |
search_within_ids |
Search only within a restricted set of node IDs. |
hierarchical_search |
Note: This method is implemented by Claude and is just for future reference. |
save |
Save the vector store to disk. |
load |
Load the vector store from disk. |
get_stats |
Get statistics about the vector store. |
get_embeddings_by_content_hash |
Extract raw embedding vectors from the FAISS index, keyed by content hash. |
rebuild_from_embeddings |
Clear level and rebuild its FAISS index from pre-computed embeddings. |
delta_update |
Patch a flat FAISS index in place when the change set is small. |
clear |
Clear data from the vector store. |
Attributes:
| Name | Type | Description |
|---|---|---|
closed |
bool
|
Whether every resource owned by this store has been released. |
Source code in codenib/index/embedding/vector_store.py
1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 | |
reuse_query_embedding
¶
Reuse one query vector within a composed request, then discard it.
Source code in codenib/index/embedding/vector_store.py
clear_query_cache
¶
Clear the single-query embedding reused by consecutive search stages.
swap_index
¶
swap_index(
path: str, *, native_index_authorization: NativeIndexAuthorization | None = None
) -> None
Hot-swap the FAISS index without reloading the embedding model.
The replacement is fully loaded and validated before the current L0/L2 state is released. The embedding model is left intact so the caller can reuse the same model across many instances.
Source code in codenib/index/embedding/vector_store.py
close
¶
Release embeddings and FAISS resources to free memory.
Source code in codenib/index/embedding/vector_store.py
add_code_chunks
¶
Add code chunks to the vector store.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
code_chunks
|
list[dict[str, Any]]
|
List of code chunk dictionaries with content and metadata |
required |
level
|
Level
|
Index level to add chunks to ("l0" for file skeletons, "l2" for functions/methods) |
'l2'
|
Source code in codenib/index/embedding/vector_store.py
1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 | |
add_nodes_with_content
¶
add_nodes_with_content(nodes: list[NodeInfo], level: Level = 'l2') -> None
Add NodeInfo objects (with content) to the vector store.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
nodes
|
list[NodeInfo]
|
List of NodeInfo objects |
required |
level
|
Level
|
Index level to add nodes to ("l0" or "l2") |
'l2'
|
Source code in codenib/index/embedding/vector_store.py
search
¶
search(
query: str,
top_k: int = 10,
score_threshold: float | None = None,
level: Level = "l2",
mask_node_ids: set[str] | None = None,
) -> list[NodeInfo]
Search for similar code chunks using semantic similarity.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
query
|
str
|
Search query text |
required |
top_k
|
int
|
Number of top results to return |
10
|
score_threshold
|
float | None
|
Minimum similarity score threshold |
None
|
level
|
Level
|
Index level to search ("l0" for file skeletons, "l2" for functions/methods) |
'l2'
|
mask_node_ids
|
set[str] | None
|
Optional set of CodeChunk.node_id values to filter results. |
None
|
Returns:
| Type | Description |
|---|---|
list[NodeInfo]
|
List of NodeInfo objects with scores populated |
Source code in codenib/index/embedding/vector_store.py
1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 | |
search_with_content
¶
search_with_content(
query: str,
top_k: int = 10,
score_threshold: float | None = None,
level: Level = "l2",
mask_node_ids: set[str] | None = None,
) -> list[NodeInfo]
Search and return results with content included.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
query
|
str
|
Search query text |
required |
top_k
|
int
|
Number of top results to return |
10
|
score_threshold
|
float | None
|
Minimum similarity score threshold |
None
|
level
|
Level
|
Index level to search ("l0" for file skeletons, "l2" for functions/methods) |
'l2'
|
mask_node_ids
|
set[str] | None
|
Optional set of CodeChunk.node_id values to filter results. |
None
|
Returns:
| Type | Description |
|---|---|
list[NodeInfo]
|
List of NodeInfo objects with content populated |
Source code in codenib/index/embedding/vector_store.py
1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 | |
search_within_ids
¶
search_within_ids(
query: str, mask_node_ids: set[str], top_k: int = 10, level: Level = "l2"
) -> list[NodeInfo]
Search only within a restricted set of node IDs.
Instead of searching the full FAISS index globally and filtering afterwards, this method restricts the search space before computing similarity. It reconstructs stored vectors for matching documents and computes similarity against the query embedding directly.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
query
|
str
|
Search query text. |
required |
mask_node_ids
|
set[str]
|
Set of node_id / node_name values to restrict search to. |
required |
top_k
|
int
|
Number of top results to return. |
10
|
level
|
Level
|
Index level to search. |
'l2'
|
Returns:
| Type | Description |
|---|---|
list[NodeInfo]
|
List of NodeInfo objects sorted by similarity score. |
Source code in codenib/index/embedding/vector_store.py
1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 | |
hierarchical_search
¶
hierarchical_search(
query: str,
l0_top_k: int = 5,
l2_top_k: int = 10,
l0_score_threshold: float | None = None,
l2_score_threshold: float | None = None,
filter_l2_by_l0: bool = True,
) -> dict[str, list[NodeInfo]]
Note: This method is implemented by Claude and is just for future reference. Perform hierarchical search: first L0 (files), then L2 (functions).
This implements a coarse-to-fine retrieval strategy: 1. Search L0 to find relevant files based on their skeletons 2. Search L2 for specific functions/methods 3. Optionally filter L2 results to only include those from L0 files
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
query
|
str
|
Search query text |
required |
l0_top_k
|
int
|
Number of top L0 results (files) |
5
|
l2_top_k
|
int
|
Number of top L2 results (functions/methods) |
10
|
l0_score_threshold
|
float | None
|
Score threshold for L0 results |
None
|
l2_score_threshold
|
float | None
|
Score threshold for L2 results |
None
|
filter_l2_by_l0
|
bool
|
If True, only return L2 results from files found in L0 |
True
|
Returns:
| Type | Description |
|---|---|
dict[str, list[NodeInfo]]
|
Dict with 'l0' and 'l2' keys containing search results |
Source code in codenib/index/embedding/vector_store.py
save
¶
Save the vector store to disk.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | None
|
Path to save the store (uses self.store_path if not provided) |
None
|
Source code in codenib/index/embedding/vector_store.py
1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 | |
load
¶
load(
path: str | None = None,
*,
native_index_authorization: NativeIndexAuthorization | None = None
) -> None
Load the vector store from disk.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | None
|
Path to load the store from (uses self.store_path if not provided) |
None
|
native_index_authorization
|
NativeIndexAuthorization | None
|
Process-local authorization bound to the exact captured tree and semantic view contract. Artifact fields cannot provide this capability. |
None
|
Source code in codenib/index/embedding/vector_store.py
2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 | |
get_stats
¶
Get statistics about the vector store.
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
Dictionary with store statistics |
Source code in codenib/index/embedding/vector_store.py
get_embeddings_by_content_hash
¶
Extract raw embedding vectors from the FAISS index, keyed by content hash.
This is used to seed the EmbeddingsCache after a full build so that
the first incremental update achieves ~100% cache hit rate for unchanged
chunks.
Each document's content is MD5-hashed to produce the key. If the
document metadata already contains a content_hash field it is used
directly; otherwise the hash is computed on the fly.
Returns:
| Type | Description |
|---|---|
dict[str, ndarray]
|
Dict mapping content_hash → np.ndarray (float32 vectors). |
Source code in codenib/index/embedding/vector_store.py
rebuild_from_embeddings
¶
Clear level and rebuild its FAISS index from pre-computed embeddings.
Used by the incremental update path: unchanged chunks contribute their cached vectors, so only genuinely new/modified chunks require model inference. No embedding model calls are made by this method.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
documents
|
list
|
Document-like objects with |
required |
embeddings
|
list[ndarray]
|
Corresponding embedding vectors as |
required |
level
|
Level
|
Which index level to rebuild ( |
'l2'
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If documents and embeddings have different lengths. |
Source code in codenib/index/embedding/vector_store.py
delta_update
¶
delta_update(
all_documents: list,
all_embeddings: list[ndarray],
changed_content_hashes: set[str],
level: Level = "l2",
threshold: float = 0.1,
) -> None
Patch a flat FAISS index in place when the change set is small.
When the fraction of changed chunks is below threshold, this uses
IndexFlat.remove_ids + add to modify only the affected rows,
keeping unchanged vectors and their aligned documents untouched. IVF
indexes are rebuilt because removing their implicit IDs does not
compact the remaining labels to match the document array. If the
change ratio exceeds the threshold (or the index is empty), this also
falls back to :meth:rebuild_from_embeddings.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
all_documents
|
list
|
The complete desired set of documents for level
after the update. Must carry |
required |
all_embeddings
|
list[ndarray]
|
Corresponding embedding vectors, aligned with all_documents. |
required |
changed_content_hashes
|
set[str]
|
Content hashes of chunks that were added, removed, or modified in this update cycle. Used both to decide between delta/rebuild and to identify stale rows. |
required |
level
|
Level
|
Which index level to update. |
'l2'
|
threshold
|
float
|
Maximum change ratio (changed/total) for the delta path; above this a full rebuild is performed. |
0.1
|
Source code in codenib/index/embedding/vector_store.py
2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 | |
clear
¶
Clear data from the vector store.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
level
|
Level | None
|
If specified, only clear that level ("l0" or "l2"). If None, clear both levels. |
None
|
Source code in codenib/index/embedding/vector_store.py
RegexNodeIndex
¶
RegexNodeIndex(code_graph: CodeGraph)
In-memory regex-based index for CodeGraph nodes. Supports regex pattern matching on node content with glob filtering.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
code_graph
|
CodeGraph
|
CodeGraph instance containing nodes to index |
required |
Methods:
| Name | Description |
|---|---|
search |
Search for pattern in node content (grep-like functionality). |
Source code in codenib/index/regex_idx/regex_idx.py
search
¶
search(
pattern: str,
file_glob: str | None = None,
node_type: str | None = None,
case_sensitive: bool = False,
use_regex: bool = True,
top_k: int | None = None,
) -> list[NodeInfo]
Search for pattern in node content (grep-like functionality).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
pattern
|
str
|
Search pattern (regex or plain string) |
required |
file_glob
|
str | None
|
Optional glob to filter by file path (e.g., '.py', '*/calc.py') |
None
|
node_type
|
str | None
|
Optional node type to filter (e.g., 'function', 'class', 'file') |
None
|
case_sensitive
|
bool
|
Whether search is case-sensitive (default: False) |
False
|
use_regex
|
bool
|
Whether to use regex (default: True) or plain string matching |
True
|
top_k
|
int | None
|
Optional result limit. Regex searches stop as soon as it is met. |
None
|
Returns:
| Type | Description |
|---|---|
list[NodeInfo]
|
List of NodeInfo objects matching the pattern |
Examples:
>>> idx.search(r'def\s+\w+', file_glob='*.py') # Find function defs
>>> idx.search('calculator', use_regex=False) # Plain string search
>>> idx.search('class', node_type='file') # Search in file nodes only
Source code in codenib/index/regex_idx/regex_idx.py
116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 | |
BM25CodeIndexer
¶
BM25CodeIndexer(
code_graph=None,
chunks=None,
max_k: int = 15,
language: str = "english",
project_root: str | None = None,
*,
prepare_only: bool = False,
check_cancelled: Callable[[], None] | None = None
)
A class that builds a BM25 index from CodeGraph nodes and provides search functionality with stemming support.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
code_graph
|
CodeGraph instance containing nodes to index. If provided, the index will be built immediately. |
None
|
|
chunks
|
List of CodeChunk objects to index. If provided, the index will be built immediately. |
None
|
|
max_k
|
int
|
Maximum number of results to return in searches |
15
|
language
|
str
|
Language for stopword removal Default is "english" which works well for processing code tokens as it treats special characters as separators |
'english'
|
project_root
|
str | None
|
Repository root used to resolve relative source paths |
None
|
prepare_only
|
bool
|
Prepare canonical persisted documents without building the serving-time in-memory rank index. |
False
|
check_cancelled
|
Callable[[], None] | None
|
Cooperative stop check for prepare-only chunk builds. |
None
|
Methods:
| Name | Description |
|---|---|
build_index_from_graph |
Build a BM25 index from a CodeGraph. |
build_index_from_chunks |
Build a BM25 index from a list of CodeChunk objects. |
bind_repository_source |
Attach a retained source authority chosen by the runtime caller. |
save_index |
Save the index to a directory. |
load_index |
Load the index from a directory. |
load_index_values |
Load already-decoded BM25 values from an authenticated reader. |
Source code in codenib/index/sparse_idx/bm25_index.py
build_index_from_graph
¶
build_index_from_graph(code_graph: CodeGraph) -> BM25Retriever
Build a BM25 index from a CodeGraph.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
code_graph
|
CodeGraph
|
CodeGraph instance containing nodes to index |
required |
Source code in codenib/index/sparse_idx/bm25_index.py
build_index_from_chunks
¶
build_index_from_chunks(
chunks: list[CodeChunk], *, project_root: str | None = None
) -> BM25Retriever
Build a BM25 index from a list of CodeChunk objects.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
chunks
|
list[CodeChunk]
|
List of CodeChunk objects (with node_id, chunk_type, name, file, etc.) |
required |
project_root
|
str | None
|
Repository root used to resolve relative source paths |
None
|
Returns:
| Type | Description |
|---|---|
BM25Retriever
|
BM25Retriever instance |
Source code in codenib/index/sparse_idx/bm25_index.py
bind_repository_source
¶
Attach a retained source authority chosen by the runtime caller.
Source code in codenib/index/sparse_idx/bm25_index.py
save_index
¶
Save the index to a directory.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
directory_path
|
str
|
Path to save the index to |
required |
Source code in codenib/index/sparse_idx/bm25_index.py
load_index
¶
Load the index from a directory.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
directory_path
|
str
|
Path to load the index from |
required |
Source code in codenib/index/sparse_idx/bm25_index.py
load_index_values
¶
load_index_values(
documents_data: Iterable[object],
metadata: Mapping[str, Any] | None,
*,
source_mode: str = SOURCE_MODE_LEGACY_DIRECT
) -> None
Load already-decoded BM25 values from an authenticated reader.
Artifact runtimes use this entry point so persisted bytes can be read through a pinned directory authority instead of being reopened by path.
Source code in codenib/index/sparse_idx/bm25_index.py
1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 | |
LSIndexer
¶
LSIndexer(
project_root: str | Path,
output_dir: str | Path | None = None,
exclude_patterns: list | None = None,
profiler: Profiler | None = None,
language: str | None = None,
decoder_backend: str | None = None,
graph_route: str = ACTIVE_GRAPH_ROUTE,
)
Unified indexer that delegates to language-specific implementations.
Methods:
| Name | Description |
|---|---|
process_query_index |
Build a backend-specific capability-scoped query index. |
process_query_provider |
Build a backend-specific provider with compatible fallbacks. |
graph_patch |
Incrementally update graph using LSP graph-patching. |
Attributes:
| Name | Type | Description |
|---|---|---|
index_quality_report |
Latest backend quality report, when the indexer provides one. |
|
index_generation_report |
Latest backend generation report, when the indexer provides one. |
|
decoded_input_receipt |
Decoded input generation consumed by graph construction, if any. |
|
graph_output_receipt |
Graph generation written by the pipeline invocation, if any. |
|
supports_partial_index |
bool
|
Whether this backend can identify partial output from this run. |
Source code in codenib/ls_router.py
index_quality_report
property
¶
Latest backend quality report, when the indexer provides one.
index_generation_report
property
¶
Latest backend generation report, when the indexer provides one.
decoded_input_receipt
property
¶
Decoded input generation consumed by graph construction, if any.
graph_output_receipt
property
¶
Graph generation written by the pipeline invocation, if any.
supports_partial_index
property
¶
Whether this backend can identify partial output from this run.
process_query_index
¶
Build a backend-specific capability-scoped query index.
Source code in codenib/ls_router.py
process_query_provider
¶
Build a backend-specific provider with compatible fallbacks.
Source code in codenib/ls_router.py
graph_patch
¶
graph_patch(graph: CodeGraph, base_commit: str, target_commit: str = 'HEAD') -> dict
Incrementally update graph using LSP graph-patching.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
graph
|
CodeGraph
|
Existing CodeGraph to update in place. |
required |
base_commit
|
str
|
Git commit hash the graph was built from. |
required |
target_commit
|
str
|
Git commit hash to patch to (default HEAD). |
'HEAD'
|
Returns:
| Type | Description |
|---|---|
dict
|
Statistics dict from the patcher. |
Source code in codenib/ls_router.py
CodeSearchEngine
¶
CodeSearchEngine(
repo_path: str,
llm_model: str = "gpt-4o",
llm_temperature: float = 0.0,
llm_max_tokens: int = 8192,
top_k: int = 10,
language: str = "english",
instance_id: str | None = None,
)
Integrated search engine that combines SCIP indexing, code graph representation, BM25 indexing, and keyword extraction to provide context-aware code search.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
repo_path
|
str
|
Path to the repository to index and search. |
required |
llm_model
|
str
|
Full litellm model identifier for keyword extraction
(e.g., |
'gpt-4o'
|
llm_temperature
|
float
|
Temperature for LLM sampling. |
0.0
|
llm_max_tokens
|
int
|
Maximum tokens for LLM responses. |
8192
|
top_k
|
int
|
Number of top results to return. |
10
|
language
|
str
|
Language for BM25 indexer (default is "english"). |
'english'
|
instance_id
|
str | None
|
Optional instance ID for the dataset. |
None
|
Methods:
| Name | Description |
|---|---|
index_repository |
Index the repository using SCIP and build BM25 index. |
extract_keywords |
Extract keywords from a problem statement. |
search |
Search the repository for code relevant to the problem statement. |
get_code_context |
Get source code context for a search result. |
get_code_context_by_node_name |
Get source code context for a node by its name. |
get_predecessor_nodes |
Get predecessor nodes for a given node name. |
get_rich_result_context |
Enhance a search result with source code context. |
search_with_context |
Search and include source code context in the results. |
Source code in codenib/search.py
index_repository
¶
Index the repository using SCIP and build BM25 index.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
repo_name
|
str | None
|
Optional name for the repository |
None
|
instance_id
|
str | None
|
Optional instance ID for the dataset |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
True if indexing was successful, False otherwise |
Source code in codenib/search.py
extract_keywords
¶
extract_keywords(problem_statement: str) -> KeywordExtraction
Extract keywords from a problem statement.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
problem_statement
|
str
|
The problem statement to analyze |
required |
Returns:
| Type | Description |
|---|---|
KeywordExtraction
|
KeywordExtraction object containing extracted keywords |
Source code in codenib/search.py
search
¶
search(problem_statement: str, use_keyword_extraction: bool = True) -> list[NodeInfo]
Search the repository for code relevant to the problem statement.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
problem_statement
|
str
|
The problem statement or query |
required |
use_keyword_extraction
|
bool
|
Whether to use keyword extraction. |
True
|
Returns:
| Type | Description |
|---|---|
list[NodeInfo]
|
List of search results with scores and locations |
Source code in codenib/search.py
get_code_context
¶
get_code_context(result: Mapping[str, Any] | NodeInfo) -> str | None
Get source code context for a search result.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
result
|
Mapping[str, Any] | NodeInfo
|
A single search result from the search method |
required |
Returns:
| Type | Description |
|---|---|
str | None
|
Source code context as a string, or None if not available |
Source code in codenib/search.py
get_code_context_by_node_name
¶
Get source code context for a node by its name.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
node_name
|
str
|
The name of the graph node |
required |
Returns:
| Type | Description |
|---|---|
str | None
|
Source code context as a string, or None if not available |
Source code in codenib/search.py
get_predecessor_nodes
¶
Get predecessor nodes for a given node name.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
node_name
|
str
|
The name of the graph node |
required |
Returns:
| Type | Description |
|---|---|
list[str]
|
List of predecessor node names |
Source code in codenib/search.py
get_rich_result_context
¶
get_rich_result_context(
result: Mapping[str, Any] | NodeInfo, context_lines: int = 5
) -> dict[str, Any]
Enhance a search result with source code context.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
result
|
Mapping[str, Any] | NodeInfo
|
A single search result from the search method |
required |
context_lines
|
int
|
Number of context lines to include before and after |
5
|
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
Enhanced result with source code context |
Source code in codenib/search.py
search_with_context
¶
search_with_context(
problem_statement: str, context_lines: int = 5, use_keyword_extraction: bool = True
) -> list[dict[str, Any]]
Search and include source code context in the results.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
problem_statement
|
str
|
The problem statement or query |
required |
context_lines
|
int
|
Number of context lines to include |
5
|
use_keyword_extraction
|
bool
|
Whether to use keyword extraction |
True
|
Returns:
| Type | Description |
|---|---|
list[dict[str, Any]]
|
List of search results with code context |
Source code in codenib/search.py
create_code_vector_store
¶
create_code_vector_store(
embedding_model: str = "text-embedding-ada-002",
embedding_provider: str = "openai",
store_path: str | None = None,
**kwargs
) -> CodeVectorStore
Factory function to create a CodeVectorStore.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
embedding_model
|
str
|
Name of the embedding model |
'text-embedding-ada-002'
|
embedding_provider
|
str
|
Provider for embeddings |
'openai'
|
store_path
|
str | None
|
Path to store/load the vector store |
None
|
**kwargs
|
Additional arguments for CodeVectorStore |
{}
|
Returns:
| Type | Description |
|---|---|
CodeVectorStore
|
CodeVectorStore instance |