К основному содержанию
плагин CX Codex

usage-engineer — плагин для Claude Code и Codex: аудит токенов

Плагин usage-engineer для Claude Code и Codex считает расход токенов в сессиях, сжимает длинные логи и проверяет актуальность карты проекта. Он также выявляет повторные сбои команд.

MIT ★ 1 596 обновлён 2026-10-29

Установить в Claude Code · Через маркетплейс плагинов Все способы и платформы ↓
/plugin marketplace add hashgraph-online/awesome-codex-plugins
/plugin install usage-engineer@awesome-codex-plugins
Открыть на GitHub

Что делает usage-engineer

ue — локальный CLI из одного файла Python. Зависимостей нет, в сеть он не ходит. Задача простая: показать, сколько работы агент выбрасывает зря — гигантские логи в контексте, повторные запуски той же падающей команды, карты проекта, которые разошлись с деревом файлов.

audit собирает расход из локальных Codex rollout JSONL, транскриптов Claude и базы OpenCode, с --by-day даёт таблицу по дням. summarize-log --file build.log оставляет в логе каждую строку с ошибкой и контекст, а байт-в-байт оригинал кладёт рядом и печатает путь. map build и map check версионируют снимок проекта: check выходит с кодом 1 и перечисляет изменившиеся файлы. Всё, что пишет на диск, включается флагом — apply-profile --target codex делает бэкап и запись SHA-256, а rollback откажется затирать правки, сделанные после apply (код 3).

Аудит не открывает auth.json, куки и текст переписки, домашний каталог подменяет на %HOME%. Живой бенчмарк без --max-calls и --confirm не стартует: потолок там по числу вызовов, токены и деньги он не ограничивает. В опубликованном первом прогоне подготовленный пакет контекста на трёх кейсах, где оба варианта прошли, съел на 30% больше токенов. ue этого и не скрывает.

Какие задачи решает

  • сжать лог сборки до ошибок и контекста, сохранив оригинал
  • найти, в какие дни расход токенов в Codex вырос
  • поймать устаревшую карту проекта перед возобновлением работы
  • вычистить дублирующиеся правила из AGENTS.md
  • сравнить два прогона бенчмарка и увидеть регрессии качества

Примеры запросов агенту

  • Прогони ue audit --by-day и скажи, в какие дни расход токенов вырос.
  • Сожми build.log командой ue summarize-log --file build.log, оригинал не трогай.
  • Проверь карту проекта через ue map check, и если она устарела — пересобери.

Как установить usage-engineer

Через маркетплейс плагинов

/plugin marketplace add hashgraph-online/awesome-codex-plugins
/plugin install usage-engineer@awesome-codex-plugins

По шагам, с командами для каждой платформы: Плагины Claude Code: маркетплейсы, установка и как собрать свой

Вопросы об usage-engineer

Как установить usage-engineer в Claude Code?

Через маркетплейс: сначала /plugin marketplace add hashgraph-online/awesome-codex-plugins, затем /plugin install usage-engineer@awesome-codex-plugins.

Что делает usage-engineer?

Считает расход токенов по локальным сессиям Claude, Claude и OpenCode, сжимает длинные логи до строк с ошибками, следит за актуальностью карты проекта и ищет дубли правил в AGENTS.md.

Что нужно, чтобы запустить ue?

Python 3.9+, внешних зависимостей нет. Ставится через pipx или запускается из чекаута как python ue.py <command>.

Исходный текст

usage-engineer · MIT
# usage-engineer (`ue`)

[![CI](https://github.com/noamshorts22-prog/usage-engineer/actions/workflows/ci.yml/badge.svg)](https://github.com/noamshorts22-prog/usage-engineer/actions/workflows/ci.yml)
![Python](https://img.shields.io/badge/python-3.9%2B-blue)
![Dependencies](https://img.shields.io/badge/dependencies-0-brightgreen)
![License](https://img.shields.io/badge/license-MIT-green)

**Stop paying for wasted agent work.** `ue` is a local CLI that measures and cuts the work coding
agents throw away: 5,000-line logs pasted into context, the same failing command retried, stale
project maps, duplicated instructions. It works with **Codex CLI**, **Claude Code** and **OpenCode**.

- Zero dependencies, one Python file, no network calls, ever.
- Never reads `auth.json`, cookies, tokens or chat text.
- Never changes your model or reasoning settings. Everything that writes is opt-in and reversible.

## Install

```
pipx install git+https://github.com/noamshorts22-prog/usage-engineer
ue doctor
```

Or run from a checkout with `python ue.py <command>` (Windows: `ue.cmd <command>`).

### As an agent skill

`ue` also ships as an [Agent Skill](https://agentskills.io) that tells the agent when to use it:
long logs go to a file and get compacted, identical failures are not retried, and maps are checked
before work resumes. The skill bundles `ue.py`, so nothing else needs installing.

| Agent | Install |
|---|---|
| Codex CLI | `codex plugin marketplace add noamshorts22-prog/usage-engineer` then `codex plugin add usage-engineer@usage-engineer` |
| Claude Code | `claude plugin marketplace add noamshorts22-prog/usage-engineer` then `claude plugin install usage-engineer@usage-engineer` |
| Any agent (Cursor, Gemini CLI, OpenCode, ...) | `npx skills add noamshorts22-prog/usage-engineer` |

The skill itself is [skills/usage-engineer/SKILL.md](https://github.com/noamshorts22-prog/usage-engineer/blob/main/skills/usage-engineer/SKILL.md).

## Two minutes to your first numbers

```
ue audit                      # where did my Codex/Claude Code/OpenCode usage go? (read-only, redacted)
ue audit --by-day             # token totals per day, to line up with your quota meter
ue summarize-log --file build.log   # keep every error, drop the noise, store the full copy
ue map build --project .      # snapshot the project; `map check` tells you when it is stale
```

## Commands

| command | what it does | writes |
|---|---|---|
| `audit` | usage baseline from local Codex rollout JSONL, Claude Code transcripts (`~/.claude/projects`) and the OpenCode SQLite DB, with waste signals; `--by-day` adds a per-day table; redacted | optional JSON via `--json-out` |
| `summarize-log --file X` | compact view that keeps every failure/error line plus context; stores the byte-exact original and prints its path | `--out` dir |
| `prepare-context --project DIR` | small task pack: request, constraints, git commit/diff id, path hashes, verification commands | `--out` md + json |
| `map build` / `map check` | versioned project map; `check` exits 1 and lists files when anything changed | map json |
| `instructions scan/duplicates/verify` | AGENTS.md inventory, paragraph-level duplicate mapping, mandatory-rule verification | optional json |
| `compare --a R1 --b R2` | per-task paired comparison of two bench runs; refuses non-comparable records; flags quality regressions | stdout |
| `apply-profile --target codex` | opt-in Codex profile `$CODEX_HOME/usage-efficient.config.toml`, used via `codex --profile usage-efficient` | profile + backup + registry |
| `apply-profile --target opencode-project --project DIR` | project `opencode.json` that references the ue instructions (aborts if one exists) | project file |
| `rollback --target codex` | restores the original state; aborts if the file changed after apply | - |
| `bench list/plan` | the 4 frozen paired benchmark cases and the exact commands (no model calls) | stdout |
| `bench run --runner codex --max-calls N --confirm` | opt-in live A/B run with a hard invocation cap and no automatic retries | state dir |
| `doctor` | environment check: versions, config paths, profiles | stdout |
| `selftest` | 39 deterministic tests, no model calls | - |

## Measure before you believe

Efficiency claims about agents are cheap. `ue bench` makes them testable: each of the four frozen
cases (off-by-one bugfix, cross-file rename, regression test, RTL layout fix) runs in a fresh
isolated copy, the agent never sees the solution or the acceptance script, and `ue compare` refuses
to compare runs that used different models, reasoning levels or case versions.

```
ue bench plan
ue bench run-all --runner codex --max-calls 8 --confirm
ue compare --a <baseline-run.json> --b <profile-run.json>
```

### First live result (2026-10-21, n=1 per cell, codex-cli 0.163.0, default model)

A = baseline, B = `context-pack` (a prepared project map handed to the agent up front).

| Case | A total tokens | B total tokens | A pass | B pass |
|---|---:|---:|:-:|:-:|
| bugfix-offbyone | 325,468 | 364,474 | yes | yes |
| crossfile-rename | 286,107 | 281,159 | yes | yes |
| regression-test | 294,160 | 266,461 | yes | no* |
| rtl-cart | 296,432 | 535,727 | yes | yes |

On the three cases both variants passed, B used **30% more** tokens (+273,353), mostly cached
input. So on these small fixtures the context pack does not pay for itself, and `ue` does not claim
it does. One sample per cell is noise-level; treat this as a demonstration of the method, not a verdict.

\* B's failure was environmental: the file the agent wrote under the Codex Windows sandbox was
not readable by the acceptance script (`PermissionError`), so it says nothing about B's quality.

## Safety properties

- Audit output never includes transcript text and redacts your home directory as `%HOME%`.
- Unknown metrics are reported as `UNKNOWN` / `null`, never as `0`.
- `apply-profile` backs up any existing file and records its SHA-256; `rollback` refuses to
  overwrite later edits (exit code 3).
- `apply-profile --target opencode-global` is refused by design.
- Benchmarks refuse to run without `--max-calls` and `--confirm`. `ue` caps the number of
  invocations; it cannot cap tokens or money.

State lives in `~/.usage-engineer` (override with `UE_STATE_DIR`).

## Known limitations

- Model-level efficiency is barely measured: one live run per cell so far (see above). Live runs
  cost quota, so results from your machine are very welcome.
- On Windows, files the agent creates inside the Codex sandbox can be unreadable to the
  acceptance script, which then reports a false failure.
- Token figures derived from character counts are estimates (4 characters per token).
- The OpenCode audit covers `session` table totals, not per-message parsing.
- Claude Code reports uncached input separately from cache reads and writes, so its `input`
  column is not comparable to Codex's, where cached input is a subset of input. Claude Code
  totals are tokens, not your plan's usage-limit units.

## Roadmap

- Claude Code support in `bench`; Gemini CLI and Aider support in `audit` and `bench`
- A GitHub Action that posts `ue audit` waste signals on agent-authored PRs
- More benchmark cases, contributed by the community

Contributions welcome: see [CONTRIBUTING.md](https://github.com/noamshorts22-prog/usage-engineer/blob/main/CONTRIBUTING.md).

## License

MIT

© noamshorts22-prog · MIT · hashgraph-online/awesome-codex-plugins

Похожие плагины

Все плагины по теме «Настройка агента: память, контекст, субагенты» →
01-usage AI-Driven Dev Скилл 01-usage отвечает, сколько токенов ушло за период или на одну задачу — по дням, моделям, агентам или тикетам, из локального отчёта aidd telemetry. CX Codex +1 ★ 571звёзд репо claude-usage-analyst daymade Скилл claude-usage-analyst объясняет, куда ушли токены и деньги в Claude: собирает данные ccusage, показывает модель, кэш и пятичасовые блоки. CX Codex +1 471установок usage-trends hoangsonww Скилл usage-trends анализирует тренды сессий, расход токенов и популярность инструментов в Claude Code через API мониторинга. Помогает находить сбои и оценивать эффективность кэша за 365 дней. CX Codex +1 ★ 1 198звёзд репо huawei-cloud-maas-tokens-usage huaweicloud Скилл huawei-cloud-maas-tokens-usage для Claude Code и Codex собирает сводную статистику токенов и ошибок в Huawei Cloud MaaS. Запрашивает данные о расходе токенов и количестве вызовов за выбранный период. CX Codex +1 207установок LatentGate KathanModh259 MCP-сервер LatentGate сжимает логи и структуры JSON перед отправкой в контекст модели. Работает локально без ключей API, сокращая расход токенов. CX Codex +1 ★ 25звёзд репо opencli-usage jackwener Скилл opencli-usage для Claude Code учит агента искать команды OpenCLI, читать схемы и разбирать ответы. Помогает работать с сайтами и Chrome через адаптеры. CX Codex +1 21 600установок

Из того же набора391

Весь набор →
waggle Плагин waggle для Claude Code и Codex хранит решения, ограничения проекта и причины в локальном графе, чтобы агент мог использовать их в следующих сессиях. CX Codex ★ 1 596звёзд репо vibestretch Плагин vibestretch напоминает размяться или отдохнуть от экрана, пока агент выполняет долгую задачу. Сигнал зависит от времени ожидания, а не от расписания. CX Codex ★ 1 596звёзд репо vibe-portrait Плагин vibe-portrait читает историю ваших диалогов с ИИ и собирает HTML-портрет: MBTI, радар способностей, рейтинг разработчика и persona-скилл, который думает в вашей манере. CX Codex ★ 1 596звёзд репо velith Плагин velith проводит книгу через шесть фаз от пустой страницы до EPUB и PDF: 12 агентов, зафиксированный голос и проверка готовности перед публикацией. CX Codex ★ 1 596звёзд репо unity-agent-workflows Плагин unity-agent-workflows задаёт порядок работы ИИ-агента с проектами Unity 2D: сначала подтвердить, какие объекты управляют результатом в игре, затем менять файлы и проверять результат. CX Codex ★ 1 596звёзд репо unforgit Плагин unforgit даёт агенту память о проекте: решения, конвенции, подводные камни и плейбуки хранятся в репозитории и не теряются между сессиями. CX Codex ★ 1 596звёзд репо tree-ring-memory Плагин учит агента вспоминать, записывать, проверять и забывать проектный контекст через локальный Tree Ring Memory CLI. CX Codex ★ 1 596звёзд репо tool-advisor Плагин tool-advisor сканирует MCP-серверы, скиллы, плагины и CLI-утилиты в вашем окружении и предлагает до трёх путей решения задачи с готовыми командами. CX Codex ★ 1 596звёзд репо

Спонсоры проекта

Компании, которые помогают держать аналитику открытой