Skip to content

Architecture & code map

Where things live in the code, and which file to open for a given change. src/ctx/ is a flat package of ~60 modules; this page is the map. If you’re here to make a change, start with the “which file do I touch” table, then read the plane your change lands in.

New to the design ideas themselves? Read How it works and Core concepts first — this page assumes that vocabulary.

Every module belongs to one of six planes. A change belongs in one plane, inherits that plane’s invariants, and ships with a test.

PlaneOwnsYou’d change it to…
Safetyhard, non-adaptive limits: path, process, storage, secrettighten confinement or redaction
Executioncommands, jobs, capture, host integrationadd a capture surface or host adapter
Derivationsymbols, references, facts, queriesadd an indexer or fact producer
Evidenceextraction, coverage, contractsadd a command-family profile
Deliveryplans, budgets, rendering, retrievaladd a deterministic renderer or plan op
Behaviourinterventions, outcomes, reflex, policyadd a measured reflex or scorecard metric
I want to…Start in
add a digest profile (pytest-like) for a new toolsrc/ctx/digest/<family>prof.py + src/ctx/contracts/<family>.toml — see Writing a profile
change how a command is classified/steeredsrc/ctx/hook.py (the PreToolUse guard — stdlib-only hot path)
add or change a CLI verbsrc/ctx/cli.py (its parser block + one row in _COMMANDS) + a handler in src/ctx/commands/ + its one-liner in src/ctx/cliux.py
add a ctx q stagesrc/ctx/query.py
add an evidence-plan operatorsrc/ctx/plan_ops.py (+ plan_ir.py, plan_exec.py)
change how a digest is selected/sizedsrc/ctx/resolver.py (the Delivery Policy Resolver)
change retrieval (get/search/spans)src/ctx/retrieval.py + src/ctx/_retrieval/
change how a repo: line address stays valid across editssrc/ctx/anchors.py
measure whether the host’s own edits are landingsrc/ctx/edit_outcomes.py
change what happens when a node does not finishsrc/ctx/steward.py (classifier + menu) · src/ctx/recovery_policy.py (the choice)
change what harnesses record about a collaboration, or resume onesrc/ctx/taskledger.py · src/ctx/orchestrator.py:run_route
change the artifact storesrc/ctx/store.py
change path confinement or secret redactionsrc/ctx/workspace.py / src/ctx/textutil.py
add a code-navigation verb (callers/refs/def)src/ctx/codeverbs.py / src/ctx/callgraph.py
change host setup / plugin renderingsrc/ctx/installer.py, src/ctx/wrap.py
change the MCP tool surfacesrc/ctx/mcp.py
change the session scorecardsrc/ctx/scorecard.py

No behavioural signal may weaken anything here.

ModuleResponsibility
workspace.pyWorkspace resolution, identity, path confinement; absolute paths never leave here in model-visible form (SPEC §5).
hook.pyThe PreToolUse context guard — runs on the hot path of every intercepted tool call; stdlib-only for latency and reliability (SPEC §10.2, §11).
textutil.pyDeterministic text: token estimation, ANSI/control stripping, secret redaction, bounded emission (SPEC §8, §16).
surface.py, surface_profiles.py, surface_gateway.py, surface_reconcile.pyThe input side: ctx surface capability-context audit, minimal-surface compilation, the progressive-disclosure MCP gateway, and shadow reconciliation.
ModuleResponsibility
execution.pyBirth-time capture runner; output spools to disk and is content-addressed before the model sees it (SPEC §6.2, §7).
store.pyThe content-addressed artifact store and quota enforcement (SPEC §12).
jobs.pyLong-runner backgrounding: ctx run --bg, ctx job(s).
seq.pyctx seq — declared command trees (round economy without losing gates).
pyeval.pyctx py — programmable capture; a Python script runs under the birth gate, only its digest returns.
wrap.pyctx wrap <host> — run an agent under the harness, ephemerally.
installer.pyPlugin rendering, installation, and health checks; ctx doctor, ctx antigravity install (SPEC §4, §18).
proxy.pyThe Tier-0 observer proxy: byte-exact relay for API traffic that measures wire ground truth.
rescue.pyLossless mid-session rescue: epoch-latched transcript elision (Tier-1).
mcp.pyThe bounded MCP retrieval server — one tool schema with an op discriminator.
cli.py, __main__.pyCLI entry, the front door, argument parsing, and the _COMMANDS dispatch table (the hook subcommand is dispatched before argparse, for latency).
commands/One module per verb family holding the command bodies. The table maps a command to a module name, so an invocation imports only the family it needs — and every dependency stays inside the function that uses it, for the same reason.
config.pyRepository policy: committed ctx.toml plus hard defaults (SPEC §13). See Configuration.
statusline.pyHost-neutral status-line rendering.
ModuleResponsibility
facts.pyThe typed fact store and Angle-lite joins, in per-workspace SQLite.
skeleton.pyThe tree-sitter skeleton tier: imports, types, signatures with line ranges.
callgraph.pyThe deterministic call graph behind ctx callers/callees/impact.
codeverbs.pySymbol-addressed verbs ctx def/refs/diag (jedi backend, AST fallback).
query.pyctx q — the composition algebra: a total pipeline, ≤ 8 stages, no loops.
filesets.pyThe file-set algebra (corpus source, repo.files op); fd engine with a Python fallback.
repomap.pyThe ranked repository map (damped-PageRank over the reference graph).
astgrep.py, semgrep_engine.pyStructural- and semantic-search engine tiers behind logical plan ops.
scip_ingest.py, _vendor/scip_pb2.pyOpportunistic SCIP cross-reference ingestion; degrades to none if absent.

This is the plane most contributions touch. The flow is extractor → EvidenceGraph + coverage → Evidence Contract → (resolver) → renderer.

ModuleResponsibility
evidence.pyThe typed evidence layer: EvidenceGraph / EvidenceItem / CoverageReceipt — the seam between extraction and everything downstream (EDC §5).
contracts.pyEvidence Contracts: per-outcome REQUIRED / PREFERRED / RETRIEVABLE fact classes, validated over typed facts at the selection seam (EDC §5.3).
contracts/*.tomlThe committed contracts: pytest.toml, lint.toml, investigate.toml, generic.toml.
digest/base.pyShared profile machinery: the Profile base class, DigestContext, StreamView.
digest/__init__.pyThe profile registry (_PROFILES) and detect_profile / render_run_digest.
digest/pytestprof.pyThe pytest profile (pass path pytest/v1; census failures pytest/v2) — the reference EDC instance.
digest/lintprof.py, logprof.py, jsonprof.py, tableprof.py, searchprof.py, moreprofs.pyProfiles for diagnostics, logs, JSON/JSONL, tables, search results, and go/cargo/jest/git-diff families.
digest/text.pyThe generic text profile — the universal deterministic fallback (text/v1).
rundiff.pyctx diff run:A run:B — structural run-to-run regression digest.

Delivery — selecting and rendering views

Section titled “Delivery — selecting and rendering views”
ModuleResponsibility
resolver.pyThe Delivery Policy Resolver — the single choke point where every ladder composes into a DeliveryPlan (EDC §5.4).
digest/evidence_render.pyThe plan-obeying pure renderer for census-grade profiles: (graph, contract, plan) → bytes.
plan_ir.py, plan_ops.py, plan_exec.pyThe compiled evidence-plan IR (a total, bounded DAG), its logical operators, and the executor + investigate/v1 digest.
ask.pyctx ask — intents as typed plan presets (the seven intents).
edit_outcomes.pyWhat happened to the host’s own Edit/Write: a closed-vocabulary classifier over the tool result and a privacy-safe rate ledger. Observation only.
anchors.pyContent anchors and line tags: the verify → relocate → refuse ladder that keeps a repo: line address meaningful after an edit. Pure and total (ANCHORS.md).
retrieval.py, _retrieval/Bounded ctx search / get / stats / spans: deterministic, budget-capped, provenance-bearing (SPEC §6.3–6.5).
refs.pyThe reference/handle grammar (run:…#stdout, spans) (SPEC §6.1).
substitute.pyThe collapse substitution layer (the replacement surface).
prefixassets.pyThe prefix-stability contract: every byte injected into the prompt prefix is locked behind a manifest.
pricing.py, data/model-prices.jsonHost-neutral model pricing.
debt.pyctx debt — declared omission for engineering scope.
ModuleResponsibility
reflex.pyThe reflex arc: deterministic behavioural detectors, an append-only outcome ledger, and the densify-on-starvation latch.
policy.pyLearned policy epochs: run telemetry compiled into committed policy.
engagement.pyGraduated engagement: scaling the harness footprint to measured task scale.
evidence_outcomes.py, plan_value.pyDeterministic evidence→follow-up association and per-operator follow-up statistics.
scorecard.pyThe session scorecard: cache / cost / effort economics from wire.jsonl.
replay.pyThe session-history replay learning loop (ctx replay --regret/--outcomes).
checkpoint.pyEpoch checkpoints: freeze task state — goal, decisions, evidence handles (SPEC §14).
taskledger.pyThe task ledger: six closed-vocabulary row types, append/load/fold, the inbox. The bus harnesses collaborate over (TASK-LEDGER.md).
steward.pyTyped failure classification and the action menu for the recovery policy; every decision is a ledger row before it is acted on.
recovery_policy.pyThe promoted AlphaEvolve choose_recovery seam: retry / escalate / re-plan / honest stop, by failure kind and remaining budget.

native/ holds an optional Rust implementation of the PreToolUse hook (~3 ms vs ~29 ms for Python), parity-tested against hook.py. It’s an accelerator, not a requirement — the Python hook ships the same decision on every code path.


For the invariants every change is reviewed against, and how to run the tests, see CONTRIBUTING.md. For the normative contracts, see spec/.