Skip to content

Architecture

Pavel Erokhin edited this page Nov 21, 2026 · 5 revisions

Русская версия

This page is for contributors: how ctxray's code is laid out, how a command reaches its logic, and how a harness gets launched and measured. Contributing covers the setup and the rules you follow when you change it.

The workspace

ctxray is one Bun workspace with two packages:

Package What it is
packages/ctxray The CLI, published to npm as @mairwunnx/ctxray. TypeScript in strict mode, run by Bun, compiled into one executable per platform for releases
packages/claude-plugin The plugin for Claude Code: skills, hooks, and the MCP server config (Claude Code Plugin). It holds no code, only files that call ctxray

The root holds scripts/ (build, release, and maintenance scripts), packaging/ (the GitHub Action, the GitLab template, the Dockerfiles, the install scripts, the npm launcher), and the Feature-Action-Architecture submodule. The CLI's own dependencies stay few: Elysia for the local servers, Ink and React for the live terminal view, zod for the contracts, typed-inject for dependency injection, and the tokenizers.

Feature-Action Architecture

The code in packages/ctxray/src follows Feature-Action Architecture (FAA) strictly. FAA has four layers, and each one imports only from the layers below it:

Four layers, top to bottom: app, features, entities, shared. Each imports only from the layers below it. A feature never imports another feature, and an entity never imports another entity.

app/

main.ts is the entry point. It handles two hidden subcommands first, __mcp-shim, because harnesses call ctxray through it, and __spectate-hook, a no-op left for hooks 0.1.0 installed, then hands everything else to runCli in cli.ts. Next to them: commands.ts (the command list), container.ts (the DI container), settings.ts (language, CI mode, and the renderer), help.ts, options.ts (the global flags), and self.ts, which knows how ctxray runs itself. user-modules.ts registers a Bun.plugin before any user file loads, so import … from "@mairwunnx/ctxray" in a config or test file always gets the running binary's own API from public-api.ts, whatever node_modules holds.

features/

Slice Command
inspect ctxray inspect
test-run ctxray test and ctxray baseline
diff ctxray diff
show-report ctxray show-report
harness-install ctxray harness add, install, list, pack, remove, upgrade
cache ctxray cache dir, ls, prune, clear
session the hidden ctxray __session behind the plugin's /ctxray
mcp-serve ctxray mcp
doctor ctxray doctor
gen-prompts ctxray gen-prompts
calibrate ctxray calibrate
init ctxray init
show-config ctxray config

A slice holds <verb>.action.ts with the logic, api/command.ts with the command's spec and a thin handler, lib/ for helpers only this slice needs, and index.ts, its public boundary.

entities/

Slice What it holds
harness The adapter contract, the profiles, one folder per harness (claude-code, codex, gemini-cli, opencode, cursor), the capture pipeline in capture/, and the L1–L3 checks in layers/
harness-cache Recipes for installing harnesses, the registry client, .npmrc parsing, the cache folders, installs, and harness pack archives
lockfile Reading and writing ctxray.lock, and the problems a lockfile has against the config
loadout Comparing two loadouts, for diff, --base, and harness upgrade
proxy The local model proxy, the wire protocols, the mock conversation, forwarding to a real upstream, cassettes, traces, the egress guard, prices, and exact token counts
report The HTML, JUnit, Allure, and Markdown reports, and the HTML report's page script
user-config Loading, merging, and finishing the config, and the network settings derived from it

shared/

Slice What it holds
contract The versioned schemas every layer reads: config, loadout, report, trace, lockfile, session, inspection, tests. Also the exit codes and the published JSON Schemas
cli Flag parsing, CommandSpec, and Handler
i18n The message catalogs, locale resolution, plurals, and number formats
render The Ink live view and the plain renderer, and the choice between them
redact Secret and personal-data redaction, with the gitleaks rules
tokens The o200k and Gemma tokenizers and the Anthropic calibration
infra Environment, CI detection, platform keys, HTTP through the user's proxy, file locks, parallel helpers
markdown, glob, codeowners Frontmatter and @ imports, glob matching, CODEOWNERS
stats The Wilson interval for activation tests
mcp-shim The stdio shim ctxray puts in front of a harness's MCP servers

Imports and aliases

Imports go only downward: app → features → entities → shared. A feature never imports another feature, and an entity never imports another entity. Another slice comes in through its index.ts, by an alias from the imports map in packages/ctxray/package.json:

import { type Config, resolveNetwork } from "#entities/user-config/index.ts";
import { ExitCode } from "#shared/contract/index.ts";

Imports keep the .ts extension. Inside a slice, use ./ or one ../, never ../../: Biome rejects it. Scripts at the root reach the CLI's code through #ctxray/*. There are no global barrel files.

Dependency injection

ctxray uses typed-inject in a functional style. A factory is a function that takes its dependencies as positional parameters and declares their tokens in .inject, in the same order:

export const createDiffAction =
  (config: Config, cwd: string) =>
  async ({ base, harnesses }: DiffRequest): Promise<DiffResult> => { … };
createDiffAction.inject = ["config", "cwd"] as const;

typed-inject passes arguments by position, so a (deps: Deps) => … shape fails the type check and crashes at runtime. No service classes with state where a function will do, and no global singletons.

app/container.ts builds two levels:

  • The root container, createContainer(env, cwd), lives for the whole process. It provides env, cwd, version, self, the config loader, and the init action, which runs before any config exists.
  • The per-run child injector, createRunInjector(container, settings, t, renderer, config), holds what the flags and the config decided: the settings, the translator, the renderer, the loaded config, and every other action factory. State that lives for one run sits in a closure inside it, and the injector is disposed when the command ends.

How a command is wired

A command is three pieces: a CommandSpec, a handler factory, and an entry in COMMANDS.

// features/diff/api/command.ts
export const diffSpec: CommandSpec = {
  name: "diff",
  summary: "command.diff",
  options: {
    base: { type: "string", summary: "option.base", value: "ref" },
    harness: { type: "string", summary: "option.harness", value: "ids" },
    json: { type: "boolean", summary: "option.json" },
    config: CONFIG_OPTION,
  },
  usesConfig: true,
};

export const createDiffCommand =
  (diff: DiffAction, t: Translate, renderer: Renderer): Handler =>
  async (values) => { … return ExitCode.ok; };
createDiffCommand.inject = ["diffAction", "t", "renderer"] as const;

The spec names the command, its options, and their help texts as catalog keys. usesConfig makes the CLI load the config first, and subcommands with defaultSubcommand serve commands like harness and cache. The handler parses its flags, calls the action, hands the result to the renderer, and returns an exit code.

app/commands.ts lists every command:

{ spec: diffSpec, handler: (injector) => injector.injectFunction(createDiffCommand) },

and createRunInjector provides the action under the token the handler asks for: .provideFactory("diffAction", createDiffAction).

runCli does the rest. It parses the global flags with the command's own, resolves the language and CI mode, loads the config when the spec asks for it, opens the renderer, builds the run injector, and calls the handler. A thrown error becomes exit code 5 with a link to the issue tracker.

The harness adapter contract

Each harness declares what it is and plugs into up to three tables in entities/harness, plus an install recipe:

Piece Where What it says
HarnessProfile profiles.ts The id, the title, the modes (static, capture, observe), experimental modes, and capabilities
StaticAdapter adapters.ts, STATIC_ADAPTERS discover(project) finds every file the harness could load and returns an Inventory. resolve(inventory, scope) predicts what loads for a working folder and a set of files. That's L1–L3
CaptureAdapter adapters.ts, CAPTURE_ADAPTERS binary, defaultModel, version(), launch() (the command line, environment, and config files for one session), call() (how a test's intent becomes the harness's own tool call), and segment() (cutting a captured request into pieces). That's L4 and up
Recipe entities/harness-cache/recipes.ts, RECIPES The npm package, the default dist-tag, the per-platform build, and where the executable sits inside it. For a harness that isn't on npm, where to find its latest version and checksum

A test that requires a capability the profile lacks is skipped as unsupported instead of failing. checkSupport in profile.ts decides it.

The capture pipeline

From L4 up, a test launches the harness and reads what it sent. The pipeline lives in entities/harness/capture and features/test-run/lib/capture.ts:

ctxray copies the project, marks each file with a canary, and gives each session its own folder. The harness runs in a sandbox: its model requests go to ctxray’s proxy, MCP servers sit behind ctxray’s shim, and every other connection hits the egress guard. The redacted trace is cut into segments, which become the Loadout your test checks.

  1. Copy. createCopy makes one committed copy of the project for the run: a shared git clone plus your uncommitted changes, or a file-by-file copy outside git. It appends a canary ⟦ctx:<path>⟧ to each file a harness could load, so a captured request shows which file reached the model.
  2. Isolate. isolate clones the copy for each session, copy-on-write where the file system allows, and gives the session its own home, tmp, bin, and logs. startSession sets HOME, TMPDIR, and the XDG_* folders, points the proxy variables at the egress guard, and on macOS wraps the command in sandbox-exec.
  3. Proxy. One local proxy serves the whole run, and each session gets its own prefix, <url>/s/<id>, as the model's base URL. The proxy recognises the wire protocol (Anthropic Messages, OpenAI Responses, Chat Completions, Gemini), records every exchange into a redacted trace, and answers from the mock model, a cassette, or a real upstream. MCP servers run behind ctxray's shim, which logs the tool schemas they announce.
  4. Segments. The adapter's segment() cuts a request into segments: system, rules, skills, mcp, commands, tools, and messages. Each one carries its evidence, a marker, a fingerprint, or a canary. buildLoadout ties them to the project's files and counts their tokens, which gives the Loadout a test checks.

Harnesses describes the same steps from the user's side.

The release build

scripts/lib/compile.ts compiles the executable with Bun.build:

  • compile with autoloadDotenv: false and autoloadBunfig: false, so a user's .env or bunfig.toml never changes how ctxray runs
  • bytecode: true and format: "esm" for a faster start, minify: true, and sourcemap: "linked"
  • define sets process.env.NODE_ENV to "production" and embeds the HTML report's page script as CTXRAY_REPORT_CLIENT
  • a plugin replaces react-devtools-core, which Ink imports, with a stub

bun run build compiles for this machine into dist/ctxray. scripts/release.ts builds every platform into dist/release:

Folder What it holds
assets/ The GitHub release: one archive per platform, SHA256SUMS, install.sh, install.ps1, the JSON Schemas, ctxray.gitlab-ci.yml, harnesses.Dockerfile, ctxray-claude-plugin.zip, and the SBOM when one is passed
bin/ The executables, one folder per platform
docker/ The images' build context with the Linux executables
npm/ The npm packages and, in npm/packs, their tarballs
packaging/ What goes to the Homebrew tap, the Scoop bucket, and the action's repository

The platforms are Linux x64 and arm64 on glibc and on musl, a glibc x64 build for processors without AVX2, macOS arm64 and x64, and Windows x64 and arm64. bun scripts/release.ts --only linux-x64,darwin-arm64 builds a few of them for a quick look.

Clone this wiki locally