Skip to content

Python API

Public imports

The package root exports the following names. The tables describe their intended entry points; the sections below render their exact signatures.

Group Root exports
Corpus Symbol, SymbolDict, discover_package_roots, extract_package, extract_monorepo, load_scope
Embedding Backend, code_tokens, embed, neighbors
Structural comparison flatten_body, statement_set, normalize_dump, jaccard_similarity
Tool EchoCodeTool

EchoCheckTool is registered as echo_check and importable from axm_echo.tools, but is not re-exported by axm_echo. The other modules' public helpers are implementation-level surfaces, not root exports. The root does not export __version__.

Corpus and scope contracts

extract_package(Path(...)) returns a list of dictionaries, not Symbol instances. Symbol is the dataclass used to construct those records; as_dict() creates the dictionary view.

SymbolDict records carry qualname, name, package, workspace, kind, signature, doc_first_line, doc_full, body_norm, embed_text, has_doc, path and line. The extractor uses the signature for body_norm; it does not capture bodies. Documented embed_text combines signature and full docstring; undocumented text combines the signature and its fallback.

Discovery uses scope configuration. Functions/classes are selected according to axm-ast's module-public convention, not membership in the package-root __all__. Module records do not include every method as a separate corpus entry.

Embedding contracts

Backend accepts "tfidf" or "st". Library embed() defaults to TF-IDF, unlike the tools. code_tokens() lowercases identifiers, splits camelCase/snake_case and adds frequency-based control-flow hints.

Matrices are dense floating-point arrays with one row per input text. Unknown backends raise ValueError; backend/library failures can propagate. Use nonempty text inputs and guard an empty extracted corpus before indexing matrix[0]. For TF-IDF, embed query and corpus together.

neighbors() normalizes internally, returns row indices and cosine scores sorted descending, and retains scores equal to the threshold. It does not remove the query row. k <= 0 returns an empty list; dimensions must agree. Zero vectors do not have a meaningful self-similarity of 1.0. See the worked tutorial.

Structural contracts

See structural comparison for the meaning and limits of the normalized statement sets.

Root API

axm_echo

axm-echo.

Similarity & echo detection over code corpora (numpy/scikit-learn).

Backend = Literal['tfidf', 'st']

SymbolDict = dict[str, str | int | bool]

Symbol dataclass

A single public symbol projected into the corpus.

embed_text property

Unified embed text: docstring if present, else code/signature.

has_doc property

Whether the symbol carries a non-empty docstring.

as_dict()

Flat dict view (qualname, package, signature, embed_text, ...).

code_tokens(src)

Tokenize code text for the TF-IDF backend.

Lowercases identifiers, splits camelCase and snake_case into sub-tokens, and appends structural keyword hints weighted by frequency so control-flow shape contributes to the vector.

discover_package_roots()

Discover every package directory across the configured scope.

Walks each workspace root from :func:axm_echo.scope.load_scope, covering both the <ws>/packages/<pkg> convention and the flat other/<pkg> layout. The set of roots is data-driven (no frozen package list), so newly added packages are picked up automatically (AC4).

Returns:

Type Description
list[Path]

Sorted, de-duplicated package directories.

embed(texts, *, backend='tfidf')

Embed texts into a dense matrix via the chosen backend.

Parameters:

Name Type Description Default
texts Sequence[str]

Texts to embed (one row per text).

required
backend Backend

"tfidf" (code, scikit-learn) or "st" (MiniLM neural). The st backend is the tools' default (this lib-layer function defaults to tfidf for a torch-free call); it lazily imports torch for first-call latency, tfidf never loads it.

'tfidf'

Returns:

Type Description
NDArray[float64]

A (len(texts), dim) float matrix. Rows are not guaranteed

NDArray[float64]

normalized; neighbors normalizes internally.

Raises:

Type Description
ValueError

If backend is not a registered backend.

extract_monorepo()

Extract public symbols across every discovered package (corpus).

Returns:

Type Description
list[SymbolDict]

The concatenated symbol corpus for the configured scope.

extract_package(pkg_root)

Extract every public function/class of a package via axm-ast.

"Public" follows the axm-ast convention: a symbol exported in the module's __all__ when present, else any module-level name without a leading underscore. Test files and empty __init__ files are skipped; unparseable files are silently ignored.

Parameters:

Name Type Description Default
pkg_root Path

Package directory (containing src/<pkg>/ or a flat source tree).

required

Returns:

Type Description
list[SymbolDict]

One Symbol per public function/class, each carrying

list[SymbolDict]

qualname, signature, doc_first_line, doc_full,

list[SymbolDict]

body_norm (the signature, used as the fallback embed text for

list[SymbolDict]

undocumented symbols -- bodies are not extracted) and the derived

list[SymbolDict]

embed_text.

flatten_body(body)

Flatten compound statements (with/if/for/while/try) into their inner body.

jaccard_similarity(a, b)

Jaccard similarity between two sets (1.0 when both are empty).

load_scope()

Return the workspace roots to scan, with graceful degradation.

Resolves workspace_roots from the shared ~/.axm/config.toml [echo] section through :func:axm_config.get. On any failure (absent section, missing/empty/ill-typed value, or an axm-config error) returns [Path.cwd().resolve()] so the caller still has the current workspace to scan -- never an exception.

Returns:

Type Description
list[Path]

Resolved, de-duplicated workspace root paths. Always non-empty.

neighbors(query, matrix, *, k=10, threshold=None)

Cosine top-k nearest rows to query (exact brute-force matmul).

Parameters:

Name Type Description Default
query NDArray[float64]

A single query vector of shape (dim,).

required
matrix NDArray[float64]

Corpus matrix of shape (n, dim).

required
k int

Maximum number of neighbors to return.

10
threshold float | None

If set, drop neighbors with cosine below this value.

None

Returns:

Type Description
list[tuple[int, float]]

A list of (row_index, cosine_score) pairs sorted by score

list[tuple[int, float]]

descending, length <= k. k <= 0 yields an empty list. The

list[tuple[int, float]]

query is not excluded from the corpus; if query is a row of

list[tuple[int, float]]

matrix it appears at score 1.0.

normalize_dump(stmt)

Normalized single-statement dump (constants + name ids replaced).

statement_set(node)

Normalized stmt shapes (constants + name ids replaced) as a set.

Tools

Both registered tools and their exact execute signatures are included here. Their payloads are specified in result contracts.

EchoCodeTool

Bases: AXMTool

Detect cross-package code echoes (intent-equivalent duplicates).

Registered as echo_code via the axm.tools entry point.

execute(*, backend='st', threshold=PAIR_THRESHOLD, top_n=_DEFAULT_TOP_N, max_cluster_size=MAX_CLUSTER_SIZE, **kwargs)

Cluster cross-package echoes over the configured corpus.

Parameters:

Name Type Description Default
backend Backend

Embedding backend -- "st" (neural MiniLM, the in-process default) or "tfidf" (pure CPU, no torch).

'st'
threshold float

Minimum cosine for a candidate pair.

PAIR_THRESHOLD
top_n int

Show at most this many of the nearest non-acknowledged clusters; the total count stays visible in the metadata.

_DEFAULT_TOP_N
max_cluster_size int

Reject components larger than this as union-find over-merges (structural conformity, not a duplicate echo).

MAX_CLUSTER_SIZE

Returns:

Type Description
ToolResult

ToolResult with the bounded clusters (each carrying a

ToolResult

cluster_hash), parallel_api and boilerplate (demoted

ToolResult

pairs), the live/shown/actionable counts, and stale_acknowledged.

EchoCheckTool

Bases: AXMTool

Retrieve the public symbols closest to a free-form intention.

Registered as echo_check via the axm.tools entry point. It embeds the intention, retrieves the top-k nearest documented symbols across the whole monorepo corpus (AC2), and tags each with a location verdict (AC3). Retrieval is decoupled from the use/extend/nothing decision (AC4): the tool returns ranked candidates + docstrings and leaves the call to the agent.

execute(*, intention='', backend='st', k=_CHECK_TOP_K, threshold=_CHECK_THRESHOLD, **kwargs)

Retrieve the top-k symbols closest to intention over the corpus.

Parameters:

Name Type Description Default
intention str

Free-form description of the behaviour to implement.

''
backend Backend

Embedding backend -- "st" (neural MiniLM, the in-process default) or "tfidf" (pure CPU, no torch).

'st'
k int

Maximum number of candidates to return.

_CHECK_TOP_K
threshold float

Minimum cosine for a candidate to be retrieved. Below it the candidate is dropped, so a novel intention returns an empty list rather than a spurious match (AC4).

_CHECK_THRESHOLD

Returns:

Type Description
ToolResult

ToolResult with intention, corpus_size and candidates

ToolResult

(ranked top-k, each carrying its docstrings and a location verdict).