Metadata-Version: 2.4
Name: repo-context-optimizer
Version: 0.2.0
Summary: Deterministic repo context for coding agents: contract Trees, contract diffs, and a map checker. Installed with pip; works on Python, JavaScript, TypeScript, Go, Java, C#, Kotlin, PHP, Ruby, Swift, CSS, SQL, shell, PowerShell, and Rust (partial).
License-Expression: MIT
Project-URL: Homepage, https://github.com/si4ai/repo-context-optimizer
Keywords: python,javascript,typescript,go,java,csharp,kotlin,php,ruby,swift,css,sql,shell,powershell,rust
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.12
Classifier: Operating System :: OS Independent
Classifier: Development Status :: 2 - Pre-Alpha
Requires-Python: >=3.12
Description-Content-Type: text/markdown
License-File: LICENSE
Provides-Extra: tokens
Requires-Dist: tiktoken; extra == "tokens"
Dynamic: license-file

# repo-context-optimizer

`rco` gives a coding agent a map of a repo as one JSON object: the signatures of each file, how modules fit together, and the parts of a file that changed. No model, no keys, and no network except tiktoken's one-time encoding download when the tokens extra is installed. Install with `pip install repo-context-optimizer`.

## Languages

Works on Python, JS/TS, Go, Java, C#, Kotlin, PHP, Ruby, Swift, CSS, SQL, shell, PowerShell, Docker (Dockerfiles and Compose files), and Rust (partial). You install it with pip, but it reads any repo.

| Language | What rco extracts | Measured savings | Test environment digest (0.2.0) |
|---|---|---|---|
| Python | Trees, Forest edges, diff, test selection | django 57.3%, transformers 86.3% at `8730f35` | `python` (or `python3`) and in-tree venvs (`.venv`, `.tox`, `.nox`): version, flags, the declared dependency closure, `.pth` and editable sources; `PYTHONHASHSEED`, `PYTHONOPTIMIZE`, `PYTHONPATH`, `PYTEST_ADDOPTS` |
| JavaScript and TypeScript | Trees, Forest edges, diff, test selection | vite 77.4% at `8730f35` | `node --version`, `NODE_OPTIONS`, `NODE_ENV`, `NODE_PATH`, the `bun` or `deno` version when the tree has their files; lock: `package-lock.json`, `npm-shrinkwrap.json`, `pnpm-lock.yaml`, `yarn.lock`, `bun.lock`, `bun.lockb`, `deno.lock`, else the packages in `node_modules` |
| Go | Trees, Forest edges, diff, test selection | cli/cli 83.4% at `8730f35` | `go version`, `go env` (GOOS, GOARCH, CGO_ENABLED, the `CGO_*FLAGS`, GOFLAGS, GOEXPERIMENT, CC and more), `GODEBUG`, `GOWORK`; lock: `go.sum`, else `go list -m all` |
| Java | Trees, Forest edges, diff, test selection | guava 82.6% at `7cbc034` | `java -version`, JAVA_HOME's JDK, Gradle and Maven property variables; lock: `gradle.lockfile` in every Gradle project; Maven: `mvn dependency:list`; Gradle without locks: not detected (runs) |
| C# | Trees, Forest edges, diff, test selection | Newtonsoft.Json 78.5%, serilog 60.6% at `7cbc034` | `dotnet --version`, `dotnet --list-runtimes`, roll-forward, host environment and globalization variables; lock: `packages.lock.json` in every project, else `dotnet restore` and `dotnet list package` |
| Kotlin | Trees, Forest edges, diff, test selection | okhttp 70.7% (Java and Kotlin together, not split) at `7cbc034` | as Java |
| PHP | Trees, Forest edges, diff, test selection | laravel/framework 62.4% at `7cbc034` | `php -v`, `php -m`, every effective ini setting, `PHP_INI_SCAN_DIR`, `PHPRC`, `XDEBUG_MODE`, `XDEBUG_CONFIG`; lock: `composer.lock`, else `composer show --no-interaction` |
| Ruby | Trees, Forest edges, diff, test selection | rubocop 38.7% at `11afa3c` | `ruby -v`, `RUBYOPT`, `RUBYLIB`, `GEM_HOME`, `GEM_PATH`, `BUNDLE_WITHOUT`, `BUNDLE_WITH`, `BUNDLE_PATH`, `BUNDLE_GEMFILE`, Bundler's `.bundle/config`; lock: `Gemfile.lock`, else `gem list` and `bundle list` (so `vendor/bundle` counts) |
| Swift | Trees, Forest edges, diff, test selection | Alamofire 56.6% at `14467c9` | `swift --version`; lock: `Package.resolved`, else the pins `swift package resolve` writes |
| CSS | Trees (selectors, at-rules); `@import` / `url()` edges; diff | pdf.js CSS-only 40.1% at `39d574ca`; the-mill Wall 0% | nothing: its tests run under another language |
| Docker (Dockerfiles, Compose files) | Trees (stages, base images, COPY/ADD, RUN, ARG/ENV, ENTRYPOINT/CMD; Compose services, build, image, depends_on); Forest edges (COPY/ADD sources, Compose build to its Dockerfile, `env_file`, `include`); diff; test selection: every test when CI, the top-level Makefile or a test file uses containers, else the tests that read the file | awesome-compose Docker only 18.0% (median of arms; per-commit median 0.0%, 65 of 121 ties) at `8730f35` plus `0b2fd01` | `probe:docker`: in a container, each `FROM` and Compose image by digest (`@sha256:` pinned, else `crane`, `skopeo` or `docker buildx imagetools`); none resolves: not detected (runs). Outside a container: a fixed value |
| SQL | Trees (schema tables and columns); no Forest edges; diff | not measured | nothing: its tests run under another language |
| shell | Trees, Forest edges, diff | nvm 0% at `8730f35` | nothing: no shell test file pattern |
| PowerShell | Trees, Forest edges, diff | not measured | nothing: no shell test file pattern |
| Rust (partial) | Trees, Forest edges (77 of 105 files on ripgrep `3e85c6c`, card 1424 run); diff, test selection | ripgrep 10.8% at `8730f35` | `rustc -vV`, the rustc and rustdoc flag variables, the target, `RUSTC` and its wrappers, `RUSTUP_TOOLCHAIN`, `CARGO_TARGET_*`, `CARGO_PROFILE_*`, cargo config files outside the tree; lock: `Cargo.lock`, else `cargo metadata` |

Sources: [support matrix](docs/support-matrix.md). Every run also keys on os, arch, libc, the OS version, the container image (`none` outside one; inside one rco needs `RCO_CONTAINER_IMAGE` or podman's image id, else every test runs) and the CI matrix leg; [test environments](docs/guide/test-environments.md) has the full table, and a probe that fails means the tests run.

Two things set rco apart from grep, ctags and other search tools:

- **Token density: the agent reads only the fields it needs.** rco answers with a JSON object, so an agent takes `parts`, a signature or a line range and skips the rest. The map may hold more than a task needs, which is safer than holding too little and scanning again. grep and similar tools print lines, and an agent reads that output top to bottom, then often searches again.
- **The measure is tokens to finish a task, not the size of one command's output.** A short grep output that leads to rereading files and more searches can cost more in the end. rco is judged by the tokens an agent spends to complete a task with it and without it: [the proof](#the-proof-tokens-to-finish-a-task).

### If you are an agent

## rco: look up the map before the code
- Run `rco map --preload` once per checkout.
- Before you read code, run `rco map --for FILE...` for the files you will touch. It prints JSON.
- Do not read a source file top to bottom: `parts` has each `--for` file's nodes and what `changed` against `base`. Open the file only to edit at the part you looked up.
- The map is JSON, not text to grep: look things up with `rco map --get NAME`, `--search REGEX` or `--list [KIND|PATH]` (each returns a list). Open a raw file only when the map does not answer.
- If `built.behind` is not 0, run `rco map --preload` and map again; read any file in `built.differs` directly. If `built.source` is `worktree`, the map already has those uncommitted edits.
- To test a change, run `pytest $(rco tests BASE HEAD --list)` instead of the full suite.
- After a compaction, rerun `rco map --for FILE...` instead of rereading the files.

## The proof: tokens to finish a task

An agent that has to change a file usually greps for names, then reads whole files to see the signatures around them; most of those tokens go to finding its way, not editing. So rco is measured by the tokens an agent spends to complete a task with rco and without it (grep, ctags and reading files), counting rereads and repeated searches, and whether the answer is right.

Five tasks on rco's own tree at release/0.1.9 `c58e3710f9a3`, tiktoken `cl100k_base`. This is a **modeled agent, not a live agent run**: rco is charged only for the JSON fields the task uses plus any follow-up file slices; grep or git for its full stdout plus re-scans and follow-up slices. Which fields a task needs is a judgement recorded per task. Every step, the method and its limits: [docs/baseline/rel019-c58e371-task-cost.md](docs/baseline/rel019-c58e371-task-cost.md).

| task | tokens rco | tokens grep / git | right? |
|---|---|---|---|
| T1 find `build_map` and open it to change its signature | 444 | 447 | both; reading the function body (383) is most of each |
| T2 which tests to run for a commit | 2,781 | 14 | both include the failing test file; rco is a safe superset (172 test IDs in 47 files), grep names 2 files |
| T3 can a PR merge onto release (#193; #143) | 16; 56 | 25; 72 | both; rco reads only `onto.clean` and `onto.conflicts` |
| T4 contract changes of a commit | 509 | 122 but wrong (misses two added fields); 961 to complete | rco on the first read |
| T5 merge order of two open PRs | 142 | 182 | both |

rco cost less on T3, T5 and T4 (against a complete grep answer), about the same on T1, and far more on T2. What rco prints is often much more than what the task uses (T5: 142 used of 4,448 printed): the map offers more, and the agent reads the fields it needs. `rco baseline --grep` cannot measure task cost today: it estimates, per commit, the outlined parts of the files that commit changed against `ctags -x` plus a grep of those files (tiktoken `o200k_base`), with no import neighbors, callers, field-selective reads, follow-up reads or multi-step tasks.

Earlier estimates, from the replay definition at rco `8730f35` (changed files plus their one-hop imports, budget 12000, tiktoken `o200k_base`): what an agent would read per commit with and without rco, not a run of an agent on a task. They have not been remeasured with `rco baseline`. Source: [the `8730f35` comparison](docs/baseline/main-8730f35-compare.md).

- **Saved 45% to 65% of tokens on our own repos** since 1 Nov 2026 (win/tie/loss): md2xarticle `e0eee6f` 45.2% (18 commits, 13/5/0), this repo 62.5% (149, 121/20/8), the-mill `f6daf98` 64.8% (298, 205/88/5). **rco lost on 13 commits**, all after the same-folder import change, where the map followed those imports and cost more than reading the files.
- **grep and ctags saved more on the same commits.** Where rco sent a map, % saved for rco / aider's map at rco's size / ctags / grep of changed names: this repo (129 commits) 63.7 / 63.7 / 67.8 / 71.0, the-mill (210) 71.1 / 71.2 / 71.5 / 73.5. ctags and grep there borrowed rco's import graph and changed-name list, so a compact outline, not rco alone, is what saves the tokens.
- **Not measured: a live agent's tokens to finish a task, and whether it does the task better.** The task table above is a model of an agent.

What each command prints next to the grep, git or ctags sequence it replaces, with right-or-wrong checks and timings, is an appendix: [output size per command, not task cost](docs/baseline/rel019-c58e371-task-cost.md#appendix-output-size-not-task-cost). Grep often prints less per command; that is not what a task costs.

## 30-second start

```
pip install "repo-context-optimizer[tokens]"   # tiktoken adds real token counts
cd your-repo
rco baseline                    # does it help on your repo? estimates your last 10 code commits
rco baseline --grep             # the same commits, estimated for grep plus ctags
rco map --for src/cli.py        # what an agent looks up before editing src/cli.py
rco init --agents               # point AGENTS.md and similar files at `rco map`
```

**CI runs only the tests that matter, and never reruns tests that already passed on the same code.** `rco tests` picks the tests a change can reach; with `--passed` it picks nothing when the tree under test already passed, and only the tests for what changed since when it did not. It keys on the git tree, so squash, rebase and merge commits, a merge queue, and the push after a merge all get it. On this repo, PR #190's merge-queue run ran 934 tests in 4m45s after its pull request had passed them; its base had moved 6 files since, and with the pull request's record `rco tests --passed` selects 48 test files (197 test IDs) for that run. `rco init --ci-tests` writes the workflow. Setting rco up for a team repo: [adopting rco](docs/guide/adopting-rco.md), then [GitHub setup](docs/github-setup.md).

## Commands

Nine commands, no setup: the map is built from git and cached in `.rco/` as it is read. Every command prints JSON by default and also takes `--repo PATH` (default `.`), `--format json|markdown` (markdown renders the same object) and `--out FILE`.

```mermaid
flowchart LR
    rco((rco)) --> map["map<br/>--for --list --search --get<br/>--preload --clear --name"] & tree["tree<br/>--for"] & forest["forest"]
    rco --> diff["diff<br/>--staged --worktree"] & tests["tests<br/>--staged --worktree<br/>--ignore --list<br/>--passed --record"] & mc["merge-check<br/>--onto --base --head<br/>--order"]
    rco --> baseline["baseline<br/>--last --since --grep<br/>--pr --max-files"] & verify["verify<br/>--schema --openapi<br/>--help-text"] & init["init<br/>--agents --hooks --remove-hooks<br/>--metrics --ci-tests<br/>--no-config --no-ci"]
```

| Command and flag | what it does | what it is for |
|---|---|---|
| `rco map` | the repo map at a commit (default `HEAD`) as JSON: the Forest plus every Tree; fills the cache as it reads | an agent's first look at a repo |
| `--for FILE...` | only the modules that own those files and their neighbors, the signatures of the files they import, and each file's `parts` and what `changed` | before editing: what to know about those files without reading them |
| `--list [KIND\|PATH]` / `--search REGEX` / `--get NAME` | nodes from the map as a JSON list, filtered by kind or path, by name pattern, or by exact name | looking a name up instead of grepping |
| `--preload [--name NAME]` | builds and stores the map for a commit ahead of time and moves a named pointer (default `main`) | warming the cache in CI or after a merge |
| `--clear [--name NAME]` | empties this repo's cache (Trees, prose, pointers); never touches git or sources | starting the cache over |
| `rco tree` | the Trees (signatures) of a commit | reading a module's contract |
| `--for PATH...` | only the modules that own those paths | narrowing to one area |
| `rco forest` | how the modules fit together at a commit | seeing the shape of a repo |
| `rco diff` | added, removed and changed signatures, flags, columns and routes between two commits, with callers | reviewing what a change does to its contract |
| `--staged` / `--worktree` | diffs the index or the working tree against `HEAD` | checking edits before you commit |
| `rco tests` | the tests that can see the changes between two commits, through imports and file names | running only the tests a change can affect |
| `--staged` / `--worktree` | uses the index or working tree as the head | picking tests before you commit |
| `--ignore GLOB` | drops changed paths no test reads (repeatable) | keeping data-only changes from running everything |
| `--list` | the pytest node IDs a change reaches (or whole test files), one per line | feeding `pytest` in CI |
| `--record` / `--passed RECORD` | `--record` names `HEAD`'s tree, parents and environment digest; `--passed` (repeatable) takes records of trees that passed in this environment: none when `HEAD`'s tree is one, else the diff from the nearest, else `BASE` | never rerunning tests on code that already passed |
| `rco merge-check` | per `BRANCH` given: text conflicts onto `--onto` (default branch), and whether it uses what this PR (`--base`..`--head`) changed; exit 1 only on a text conflict | knowing before a merge which branches break |
| `--order` | for two or more branches: what each changes that another uses, and a safe merge order | planning the order of several merges |
| `rco baseline` | per-commit token estimate of the outlined changed parts over the last 10 code commits | finding out whether rco helps on your repo |
| `--last N` / `--since DATE` | which commits to estimate | A longer window, or a roll-up since a date |
| `--grep` | the same commits estimated for one fixed ctags plus grep run | comparing rco with grep on your own history |
| `--pr N` | the commits of pull request N | measuring one pull request in CI |
| `--max-files N` | skips commits that change more code files (default 50) | keeping bulk changes out of the estimate |
| `rco verify` | compares the map with real outputs you captured; exit 1 on a mismatch | proving the map matches the running system |
| `--schema` / `--openapi` / `--help-text CMD=FILE` | A SQL schema dump, an OpenAPI document, or a saved `--help` (repeatable) | checking tables, routes or CLI flags |
| `rco init` | writes `rco.toml` and a CI report job, keeping any file that exists | one-step setup |
| `--agents` | writes the agent block above into `AGENTS.md` and similar files | pointing agents at the map |
| `--hooks` / `--remove-hooks` | adds or removes a post-merge hook that preloads the map | keeping the cache warm locally |
| `--metrics` | adds a CI step that runs `baseline --pr` and uploads the report | tracking savings per pull request |
| `--ci-tests` | writes `.github/workflows/rco-tests.yml`: pytest on what `rco tests` selects, records each green tree, reads earlier records back | CI that runs only the tests that matter, once per tree |
| `--no-config` / `--no-ci` | skips `rco.toml` or the workflow | setting up only part |

```mermaid
flowchart LR
    G["git commit"] -->|"map reads a commit not stored yet: lazy fill"| S[("store in .rco/<br/>Trees keyed by content hash<br/>commits indexed by sha, named pointers")]
    G -->|"map --preload: fill ahead, move a pointer"| S
    C["map --clear"] -->|"empties Trees, prose, pointers; never git"| S
```

The cache: `map` fills it lazily, `--preload` fills it ahead, `--clear` empties it, and entries are keyed by content, so a rerun writes nothing new. Exit codes, JSON fields and examples are in [docs/commands.md](docs/commands.md).

## Languages, repo types and upcoming work

| Status ([per language](#languages)) | Languages and repo types | Token savings (the [support matrix](docs/support-matrix.md) gives each sha and source) |
|---|---|---|
| ✅ shipped in 0.1.9 | Python, SQL, JavaScript and TypeScript, Go, shell, PowerShell | Python 57.3% to 86.3%; TS/JS 77.4%; Go 83.4%; shell 0%; SQL and PowerShell not measured |
| ✅ shipped in 0.1.9, new | Java, C#, Kotlin, PHP, Ruby, CSS, Swift | Java 82.6%; C# 78.5% and 60.6%; PHP 62.4%; Ruby 38.7%; CSS-only 40.1%; Swift 56.6% (each at the sha in the matrix) |
| 🟡 partial | Rust: 37 of 105 files resolved an import on the 0.1.8 run | ripgrep 10.8% at `8730f35` |
| ✅ shipped in 0.2.0 | Docker: Dockerfiles and Compose files, with their base images in the environment digest. Environment-aware pass record (card 1422): `rco tests --passed` skips or narrows a run only with a record from the same environment (runtime, OS, CPU arch, libc, resolved dependencies, CI matrix leg), so a pass on Python 3.11 does not skip the same tree on 3.13 | Docker: awesome-compose Docker only 18.0% (median of arms; per-commit median 0.0%); the pass record is not measured |
| 🗓️ upcoming, after 0.2.0 | Languages: C and C++; COBOL is pending a measurement or a user request | not measured |
| 🗓️ upcoming, no date | A concept classifier for prose (`map --search` matches only node and module names today, so a prose phrase finds nothing); richer map nodes (signatures, imports, callers) and other optimizations in progress | not measured |
| ⚪ fallback | Any other language: the file shows by path | not measured |
| ✅ repo types | Single package, monorepo, polyglot, submodules (skipped with a note), LFS (opaque), empty repo | not measured by type |

## How rco is built

```mermaid
flowchart TB
    A["9 commands<br/>commands/: one Spec each"] --> B["Map layer<br/>core/: build, forest, diff, refs"]
    B --> S["Cache<br/>store/: SQLite, filled on read"]
    B --> C["File graph<br/>imports, edges"]
    C --> D["Language registry"]
    D --> E["lang/&lt;language&gt;/ on a shared engine"]
    E --> F["Shared base<br/>gitread, canon, model, output"]
```

Deterministic, one design for every language, checked in CI and with SPIN, and measured with losses counted: [docs/architecture.md](docs/architecture.md) has why, the layers and the module behind each command. Design, roadmap and process: [docs/design/](docs/design/).

## Documentation and license

[Commands](docs/commands.md), [support matrix](docs/support-matrix.md), [architecture](docs/architecture.md), [adopting rco](docs/guide/adopting-rco.md), [GitHub setup](docs/github-setup.md), [cloud agents](docs/guide/cloud-agents.md), [changelog](CHANGELOG.md). MIT; see [LICENSE](LICENSE).
