SmartMemory
Guides

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:

  1. File collection: walks the directory tree, collecting files by language.
  2. AST parsing: extracts code entities and relationships from each file.
  3. Cross-file resolution: builds a symbol table to resolve import bindings across modules.
  4. Graph writing: creates nodes and edges in the knowledge graph.
  5. Embedding generation: generates vector embeddings for each entity.
  6. 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-project

Then 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

ParameterDescription
PATHDirectory to index. Use . for the current repo.
--repoShort repository identifier such as "my-service".
--languageRepeatable language selector. Supports python and typescript. Defaults to Python.
--excludeRepeatable directory name to skip.
--commit-hashOverride the Git commit SHA. Pass an empty string to suppress auto-detection.

Entity types

The parser extracts five entity types from source code:

Entity typeDescriptionExample
moduleA source filesmartmemory/code/parser.py
classClass definitionclass CodeParser
functionFunction or method definitiondef parse_file(...)
routeFastAPI or Express route handler@router.get("/health")
testTest functiondef 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:

PropertyTypeAlways presentDescription
item_idstryesDeterministic node ID
namestryesEntity name
entity_typestryesOne of module, class, function, route, test
file_pathstryesRelative path from the repository root
line_numberintyesLine number where the entity is defined
repostryesRepository identifier
memory_typestryesAlways "code"
docstringstrif presentFirst 500 characters of the entity's docstring
decoratorsstrif presentComma-separated decorator names
basesstrif presentComma-separated base class names
http_methodstrroutes onlyHTTP method such as GET or POST
http_pathstrroutes onlyRoute path such as /health
commit_hashstrif providedGit commit SHA at index time
indexed_atstryesISO timestamp of when the entity was indexed

Relationship edges

The indexer creates five types of edges between code entity nodes:

Edge typeMeaningExample
DEFINESA module defines a class or functionparser.py defines CodeParser
IMPORTSA file imports a symbol from another moduleindexer.py imports CodeEntity
CALLSA function calls another functionindex() calls parse_file()
INHERITSA class extends another classSqliteStore inherits BaseStore
TESTSA test function tests a specific entitytest_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

LanguageStatusFile extensionsNotes
PythonFull support.pyAST-based parsing. Extracts classes, functions, FastAPI routes, pytest tests, imports, calls, and inheritance.
TypeScriptExperimental.ts, .tsx, .js, .jsxBasic 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.

On this page