Skip to content

Codebase Internals

Toprak Ahmet Aydoğmuş edited this page Nov 30, 2026 · 1 revision

T-Zero Algorithm Codebase Internals

A source-grounded guide to the real execution paths, data boundaries, and major subsystems in the repository.

This page explains how the tracked implementation is divided and how its main entry points connect. It is not a security certification, performance guarantee, or substitute for reading the linked implementation. Function names, tool schemas, and runtime behavior can change; compare this guide with the source revision you have installed.

Project name and package names

The project is T-Zero Algorithm. Its Python distribution is named tzero-mcp; its import package is tzero; and the MCP server is exposed through a tzero-mcp executable. These are related names, not interchangeable package identifiers.

The package metadata currently declares version 12.3.4, Python >=3.11, and license AGPL-3.0-only. The registry manifest and distribution files should be checked for the version actually installed by a client.

Sources: pyproject.toml, server.json.

Repository layers

Layer Main tracked location Responsibility visible in source
Python package tzero/ CLI, MCP server, context reduction, scanners, analysis tools, configuration, and feature modules.
Python subpackages tzero/tzero_fixer/, tzero/tzero_jarvis/, tzero/anti_rea/ Fixer/orchestration components, Jarvis components, and Anti-REA protection components.
Rust core crates/tzero_core/ Tree-sitter pruning, context and graph analysis, token utilities, and Python/C-facing exports.
Rust Jarvis core crates/tzero_jarvis_core/ A separate Rust library and binary containing the modules listed in its crate source.
VS Code extension extensions/vscode/ Registers editor commands and views, invokes the installed CLI, and formats returned metrics.
npm installer installers/npm/ npm distribution and bundled Python-side launcher/package files. Treat the shipped copy and the source package as separate artifacts unless parity is verified for the release.
Tests tests/ Unit, integration, packaging, security-oriented, and end-to-end checks. A test name is not proof that every claimed property is complete.
Hosted demo huggingface-space/, openapi.yaml A public hosted application and its HTTP API description; separate from the local MCP server.

The Wiki's generated source-reference pages provide symbol-level indexes for the primary Python package, Rust crates, and selected test declarations.

Launch map

The installed executable-to-function mapping comes from [project.scripts] in pyproject.toml.

Executable Entry point What the entry point selects
tzero tzero.tzero_v3:main CLI command routing, with operations delegated to feature modules.
tzero-gui tzero.tzero_v3:launch_gui The Python desktop UI entry point.
tzero-tui tzero.tzero_tui:main Terminal UI entry point.
tzero-mcp tzero.tzero_mcp:main MCP server startup and its supported command-line modes.
pc-fixer-mcp pc_fixer_mcp:main Separate PC-Fixer MCP entry point.
tzero-add-mcp / tzero-addmcp addmcp:main Editor/client MCP setup utility.
tzero-guard tzero.tzero_guard:main Guard-related command entry point.
tzero-sync tzero.tzero_sync:main Workspace rule synchronization entry point.
tzero-cost tzero.tzero_cost:main Token-cost command entry point.
tzero-drift tzero.tzero_drift:main Instruction/configuration drift command entry point.
tzero-fixer / tzero-explain / tzero-armor / tzero-radar tzero.tzero_v3:main Shared CLI router; the executable name alone does not identify a unique implementation path.

tzero/__init__.py declares lazy exports through __getattr__. It also attempts terminal initialization at import time and suppresses exceptions from that optional initialization. Importing the package therefore is not strictly a no-side-effect operation.

The repository-root tzero_mcp.py is a compatibility wrapper. The substantive server implementation is tzero/tzero_mcp.py.

Sources: pyproject.toml, tzero/__init__.py, tests/test_packaging_sync.py.

Main CLI routing

The tzero console entry point calls main() in tzero/tzero_v3.py. That function handles selected positional commands early, then defines the main argparse interface and dispatches operations. Examples of early routes in the source include editor initialization, local CI, share/sponsor/promo helpers, rule export, ROI display, and Anti-REA-related commands. The later parser covers scanning, context, review, audit, search, cost, sync, hooks, and other features.

The CLI is a router as well as a large implementation module. Many operations delegate to dedicated modules, but the routing branches and feature implementations do not all share one uniform execution model. Inspect the specific argument branch before assuming its filesystem, network, or process effects.

Source: tzero/tzero_v3.py.

Context-reduction path

The following describes the implementation path in tzero/tzero_v3.py; alternate tools and the Rust implementation can behave differently.

1. Select the reducer by file type

TokenReducer.reduce(code, file_path, mode) first returns the input unchanged for mode none. Otherwise, it dispatches by filename extension. The Python path uses Python's built-in ast module. Several other language paths call PolyglotSignatureExtractor methods. SQL, YAML, Terraform/HCL, Dockerfile, and diff/patch handling can be routed through separate reducers by reduce_content.

Unknown extensions fall through to a non-empty-line trim that keeps at most 60 lines. The exact support list and fallback behavior are in the source, not inferred from the README's broader language list.

2. Python AST reduction

When Python parses successfully, the reducer retains source lines associated with:

  • function, async-function, and class declarations;
  • decorators preceding those declarations;
  • imports and import-from statements;
  • direct class assignments and annotated assignments;
  • top-level uppercase names and __all__;
  • a limited beginning portion of a docstring for balanced, adaptive, or contract modes.

It omits most function bodies. The implementation uses AST line ranges and preserves selected source lines; it does not reconstruct a complete semantically equivalent program. If parsing fails or the mode is not one of the AST modes, the fallback is lexical and keeps a smaller set of declarations. Do not treat the output as executable replacement code.

3. Workspace scan

CodebaseScanner.scan_directory(root_dir) reads the active profile for permitted extensions, ignored directory names, thread-pool size, and reduction mode. It walks the directory tree, skips configured directories and names beginning with .venv- or venv-, and records relative paths and sizes.

The scanner first attempts batch reduction through tzero_turbo. If that path raises, it falls back to a thread pool and reads up to 15,000 characters per file in that fallback path. This limit is not a universal maximum for every scan route. Files that cannot be read in the fallback path are logged and omitted from the snippet map.

Source: CodebaseScanner.

4. Build offline context text

generate_offline_context(project_dir, selected_files, file_snippets, cache_aligned) builds Markdown text from the chosen file snippets. It counts lines, collects dependency names using Python AST or language-specific regular expressions, also reads dependencies from a root package.json when present, and formats a sorted file listing and module sections.

This function itself constructs output locally; other callers may separately invoke a configured provider. Its docstring's absolute security and reduction claims are not treated here as measured guarantees.

Source: generate_offline_context.

5. Token and savings numbers are not all the same metric

The repository contains multiple measurement paths:

  1. count_tokens_precise delegates to the BPE counting helper in tzero_polyglot; the source documents a character-based fallback if a tokenizer cannot be used.
  2. TokenReducer.reduce_content computes its returned reduction percentage from character lengths (len), not from the tokenizer's token count.
  3. Scanner and report commands may calculate their own aggregate counters.

Consequently, a character-reduction percentage, a BPE token estimate, and a model-cost estimate must not be presented as if they were the same measurement. Benchmark pages should state which one was used.

Sources: TokenReducer, count_tokens_precise, tzero_polyglot.py.

Local MCP server path

Startup

tzero-mcp enters main() in tzero/tzero_mcp.py. The source recognizes help/version handling, an interactive terminal path, diagnostics and dashboard options, installation options, an optional HTTP mode, and the normal MCP stdio path.

In stdio mode, stdout is the protocol stream. Before starting the server, the code redirects root StreamHandler instances that point to stdout over to stderr to reduce the chance of ordinary logs corrupting MCP JSON-RPC messages.

The server constructor checks which arguments the installed MCP SDK constructor accepts, then selects MCPServer or FastMCP based on available imports. This is a compatibility branch, not evidence that every SDK release has been tested.

Tool modes

The current source has two decorator groups:

  • @_canon_tool registers the canonical handlers when the default canonical mode is active.
  • @_maybe_tool registers the alternate/legacy handlers when the mode is all, legacy, or 47.

An AST count of the checked-in implementation found 14 named canonical registrations and 51 named alternate registrations. A nearby source comment still says 47 for the alternate suite. This is a concrete documentation/source discrepancy: the connected server's tools/list result is the runtime authority for a particular installed version.

See MCP-Tool-Reference for the source-derived names, handlers, signatures, and line links. Do not treat a README count or marketing label as proof of the active runtime list.

HTTP is not the same thing as OpenAPI

The local MCP server can enter an HTTP transport path if invoked with --http; it may use uvicorn or an internal fallback. The repository's openapi.yaml describes the separately hosted Gradio application. It is not the OpenAPI contract for local MCP stdio, nor does the local MCP tool catalog become equivalent to those hosted endpoints.

Sources: tzero/tzero_mcp.py, MCP main, openapi.yaml, MCP-and-OpenAPI.

Rust core

crates/tzero_core builds both cdylib and rlib library forms and declares a binary target. Its root lib.rs exposes modules for AST pruning, BM25 search, boundaries, complexity, context trees, contracts, duplication, entropy, fuzzy matching, hallucination checks, MCP stdio, PageRank, Python bindings, reachability, symbol graphs, token cost, and tokenization.

The exported Rust SupportedLanguage enum includes Python, TypeScript, JavaScript, Rust, Go, and Unknown. The Rust pruning path uses tree-sitter for the recognized languages and a lexical fallback for unknown or failed parser paths. The actual Python TokenReducer has its own dispatch and heuristic paths; do not assume the language handling is identical across Python and Rust.

The core also provides Python bindings through PyO3 and C-ABI exports in lib.rs. The unsafe C-ABI functions specify pointer/length preconditions in their safety comments; callers must meet those contracts. A compiled native extension is a build artifact and may not be present in every installation.

Sources: tzero_core/Cargo.toml, tzero_core/src/lib.rs, ast_pruner.rs.

Jarvis orchestration and system repair

The Python Jarvis orchestrator composes workspace orchestration, semantic compression, a zero-key router, command-risk assessment, execution policy, secret redaction, audit logging, and a self-healing engine. Its execute_terminal method starts a shell process. The source checks the execution policy when TZERO_ENFORCE_AGENT_POLICY=1 or when the policy disallows agent shell; otherwise, the command path is not a universal user-approval gate.

The Fixer orchestrator groups diagnostic and repair components. Its source includes timestamped backups under .tzero/fixer_backups/ and a manifest used by rollback. A backup/rollback mechanism is not a guarantee that every external side effect is reversible. Review the target workspace and the selected repair plan before running a modifying operation.

Sources: JarvisOrchestrator, FixerOrchestrator.

VS Code extension path

The extension activates in VS Code, registers commands and a sidebar view, and invokes the configured CLI executable. Workspace metrics are refreshed by running a scan command and parsing JSON output. Active-editor symbol counts are computed by a lightweight declaration-pattern helper in core.js; this helper is not the Python or Rust AST parser.

The package manifest sets tzero.executablePath to tzero by default and tzero.autoInitOnOpen to false. Some registered commands can invoke operations that write configuration, files, or hooks. A command contribution is not a claim that the operation is read-only.

Sources: extension.js, core.js, package.json.

Tests and what passing means

The Python test tree includes focused test modules and end-to-end tiers. tests/test_packaging_sync.py checks package selection, executable declarations, and version consistency across several manifests. That file does not establish that every duplicated npm source file is byte-identical to tzero/.

A passing unit or integration test only establishes the assertions that test executed in its environment. It does not certify every operating system, editor, remote provider, parser grammar, native build, network path, or security property.

See Tests-Source-Reference for the test declarations and source links. For an actual verification run, use the commands in the repository's current CI workflow and report the exact command and outcome.

Operational cautions

  • Check the installed version and active MCP tools/list; source and published package versions can differ.
  • Use a disposable fixture repository before invoking repair, migration, armor, hook, or setup commands.
  • Review generated and modified files before accepting them.
  • Treat provider calls and hosted demos as network boundaries; never submit private code without authorization.
  • Do not describe a secret scanner, token estimator, static audit, or parser as a 100% guarantee.
  • Treat source comments, release copy, tool descriptions, and test names as claims to verify against executable code and tests.

Reference pages

Clone this wiki locally