Code Indexing
SmartMemory can parse and index code repositories, turning source code into searchable knowledge graph nodes. Classes, functions, routes, tests, and their relationships become first-class entities that you can query alongside other memories.
How it works
ingest_code() performs a multi-pass analysis of your repository:
- File collection: walks the directory tree, collecting files by language.
- AST parsing: extracts code entities and relationships from each file.
- Cross-file resolution: builds a symbol table to resolve import bindings across modules.
- Graph writing: creates nodes and edges in the knowledge graph.
- Embedding generation: generates vector embeddings for each entity.
- Pattern seeding: promotes class and function names into the EntityRuler pattern set.
Basic usage
Index a repository with the CLI:
sm code index . --repo my-projectThen recall indexed code from Python with search_code():
from smartmemory.pipeline.config import PipelineConfig
from smartmemory.tools.factory import lite_context
lite = dict(pipeline_profile=PipelineConfig.lite(llm_enabled=False))
with lite_context(**lite) as memory:
hits = memory.search_code(
"clean up vendor billing records",
repo="my-project",
)
for hit in hits:
print(
hit["name"],
hit["entity_type"],
f'{hit["file_path"]}:{hit["line_number"]}',
hit.get("docstring", ""),
hit["score"],
)search_code() returns a list of dictionaries with name, entity_type, file_path, line_number, docstring, and score. There is no sm code search command. Use the Python API for recall after indexing.
CLI parameters
| Parameter | Description |
|---|---|
PATH | Directory to index. Use . for the current repo. |
--repo | Short repository identifier such as "my-service". |
--language | Repeatable language selector. Supports python and typescript. Defaults to Python. |
--exclude | Repeatable directory name to skip. |
--commit-hash | Override the Git commit SHA. Pass an empty string to suppress auto-detection. |
Entity types
The parser extracts five entity types from source code:
| Entity type | Description | Example |
|---|---|---|
module | A source file | smartmemory/code/parser.py |
class | Class definition | class CodeParser |
function | Function or method definition | def parse_file(...) |
route | FastAPI or Express route handler | @router.get("/health") |
test | Test function | def test_index_python_repo() |
Each entity gets a deterministic ID in the format code::{repo}::{file_path}::{name}, making re-indexing idempotent.
Node properties
Every code entity node carries these properties:
| Property | Type | Always present | Description |
|---|---|---|---|
item_id | str | yes | Deterministic node ID |
name | str | yes | Entity name |
entity_type | str | yes | One of module, class, function, route, test |
file_path | str | yes | Relative path from the repository root |
line_number | int | yes | Line number where the entity is defined |
repo | str | yes | Repository identifier |
memory_type | str | yes | Always "code" |
docstring | str | if present | First 500 characters of the entity's docstring |
decorators | str | if present | Comma-separated decorator names |
bases | str | if present | Comma-separated base class names |
http_method | str | routes only | HTTP method such as GET or POST |
http_path | str | routes only | Route path such as /health |
commit_hash | str | if provided | Git commit SHA at index time |
indexed_at | str | yes | ISO timestamp of when the entity was indexed |
Relationship edges
The indexer creates five types of edges between code entity nodes:
| Edge type | Meaning | Example |
|---|---|---|
DEFINES | A module defines a class or function | parser.py defines CodeParser |
IMPORTS | A file imports a symbol from another module | indexer.py imports CodeEntity |
CALLS | A function calls another function | index() calls parse_file() |
INHERITS | A class extends another class | SqliteStore inherits BaseStore |
TESTS | A test function tests a specific entity | test_parse_file() tests parse_file() |
Cross-file CALLS and IMPORTS edges are resolved through a two-pass symbol table that maps local import names to their target entity IDs.
Incremental updates
For adding or updating individual code entities without re-indexing an entire repository, use ingest_structured() with the code_entity schema:
from smartmemory.pipeline.config import PipelineConfig
from smartmemory.tools.factory import lite_context
lite = dict(pipeline_profile=PipelineConfig.lite(llm_enabled=False))
with lite_context(**lite) as memory:
item_id = memory.ingest_structured(
{
"name": "AuthMiddleware",
"entity_type": "class",
"file_path": "middleware/auth.py",
"line_number": 42,
"repo": "my-service",
"docstring": "JWT authentication middleware for FastAPI.",
"bases": ["BaseHTTPMiddleware"],
},
schema="code_entity",
)
print(item_id)The code_entity schema requires name, entity_type, file_path, line_number, and repo. The entity_type must be one of module, class, function, route, or test.
Languages supported
| Language | Status | File extensions | Notes |
|---|---|---|---|
| Python | Full support | .py | AST-based parsing. Extracts classes, functions, FastAPI routes, pytest tests, imports, calls, and inheritance. |
| TypeScript | Experimental | .ts, .tsx, .js, .jsx | Basic entity extraction. Pass --language typescript to the CLI. |
IndexResult
The ingest_code() method returns the real IndexResult dataclass from smartmemory.code.models:
from dataclasses import fields
from smartmemory.code.models import IndexResult
print([field.name for field in fields(IndexResult)])Check result.errors after indexing to see any files that failed to parse. Failed files are skipped without aborting the run.
Pattern seeding
After indexing, seed_patterns_from_code() runs automatically. It extracts {name: entity_type} pairs from the indexed entities and merges them into the workspace's EntityRuler pattern set.
This means that after you index a codebase, future ingest() calls over natural-language text can recognize references to your code symbols. For example, if you index a project containing class SmartGraph, then ingesting the text "The SmartGraph module handles all graph queries" can identify SmartGraph as a named entity of type class.