Metadata-Version: 2.5
Name: agent-efficiency
Version: 2.0.0
Summary: Zero-dependency local context index, log compression, session memory, context doctor, and lean MCP server for AI coding agents.
Project-URL: Homepage, https://github.com/Jeager070/agent-efficiency-skills
Project-URL: Repository, https://github.com/Jeager070/agent-efficiency-skills
Project-URL: Issues, https://github.com/Jeager070/agent-efficiency-skills/issues
Author: Jeager070
License: MIT
License-File: LICENSE
Keywords: ai,claude-code,codex,coding-agent,cursor,fts5,gemini,mcp,skills,tokens
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Software Development :: Quality Assurance
Requires-Python: >=3.9
Provides-Extra: all
Requires-Dist: litellm>=1.40.0; extra == 'all'
Requires-Dist: tree-sitter-language-pack>=0.7.0; extra == 'all'
Requires-Dist: watchdog>=4.0.0; extra == 'all'
Provides-Extra: ast
Requires-Dist: tree-sitter-language-pack>=0.7.0; extra == 'ast'
Provides-Extra: llm
Requires-Dist: litellm>=1.40.0; extra == 'llm'
Provides-Extra: watch
Requires-Dist: watchdog>=4.0.0; extra == 'watch'
Description-Content-Type: text/markdown

# Agent Efficiency Skills (`ae`)

**Stop paying your AI coding agent to re-read the same files and paste 3,000-line test logs into every turn.**

[![CI](https://github.com/Jeager070/agent-efficiency-skills/actions/workflows/ci.yml/badge.svg)](https://github.com/Jeager070/agent-efficiency-skills/actions/workflows/ci.yml)
[![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](LICENSE)
![Python 3.9+](https://img.shields.io/badge/python-3.9%2B-blue)
![Dependencies: none](https://img.shields.io/badge/core%20deps-stdlib%20only-brightgreen)

Cut noisy test-log & session-resume overhead by **up to 94–97%**, trim code-reading tokens by **20–80%** even against disciplined `rg` + range-read agents, and audit your real IDE token waste & always-on context bloat in 3 seconds.

Works with **Claude Code**, **Cursor**, **Codex**, **Gemini CLI**, **Antigravity**, **OpenCode**, **Windsurf**, **Copilot**, and custom LLM pipelines. Runs 100% locally on **Python 3.9+ standard library + SQLite FTS5** (zero required packages, ~16–21 MB peak RAM, no background daemon).

![Before and after comparison of pytest output vs ae run](docs/assets/before-after-run.svg)

---

## 10-Second Try-It-Now (Zero Repo Changes, Read-Only)

See what your coding agents actually burned last week — and how many always-on tokens your rules, skills, and MCP servers tax every single turn:

```bash
# Run directly from PyPI via uvx (zero install, strictly read-only):
uvx agent-efficiency audit
uvx agent-efficiency doctor

# Or install/run directly from GitHub main:
# uvx --from git+https://github.com/Jeager070/agent-efficiency-skills.git ae audit
```

![ae audit visual session receipt and ae doctor context bloat analyzer](docs/assets/audit-doctor-card.svg)

---

## 1-Command Setup (`ae init`)

### Option A — Install via `pipx` / `pip` + `ae init` (Recommended)
```bash
pipx install agent-efficiency
# Optional native tree-sitter AST upgrade for JS/TS/Go/Rust/Java:
# pipx install "agent-efficiency[ast]"
# Or install directly from GitHub main:
# pipx install git+https://github.com/Jeager070/agent-efficiency-skills.git

# Auto-detects Claude Code, Cursor, Codex, Gemini, OpenCode, Windsurf & Copilot:
ae init                         # Skills (--profile ide) + ae CLI + rules + repo index
ae init --enforce               # Recommended v2.0: MCP (core) + ae_gate.py PreToolUse + hard rules
ae init --hooks                 # + Non-destructive hooks (PreToolUse in safe hint-only mode)
ae init --hooks --auto-wrap     # + Explicit opt-in: auto-wrap simple pipe-free test/build cmds
ae init --mcp                   # + Built-in lean MCP (`ae mcp --profile core`: 8 tools, <850 tok)
```

### Option B — From a Local Clone (No `pipx`/`uvx` Needed)
```bash
git clone https://github.com/Jeager070/agent-efficiency-skills.git
cd agent-efficiency-skills

python3 scripts/ae_init.py . --hooks
# Or target a single runtime explicitly:
python3 scripts/install.py --runtime claude --profile ide --install-cli --install-rules --force
python3 scripts/install.py --runtime cursor --profile ide --install-cli --install-rules --force
```

### Option C — Claude Code Plugin Marketplace
This repository ships `.claude-plugin/plugin.json` and `.claude-plugin/marketplace.json`:
```text
/plugin marketplace add Jeager070/agent-efficiency-skills
/plugin install agent-efficiency
```

---

## Why It Actually Gets Used (Not Forgotten Like Normal Skills)

1. **Real `SessionStart` trigger (Claude Code & Gemini CLI) + Hookless-IDE setup:**
   - **Hook-capable clients (`ae init --hooks`):** `SessionStart` runs `agent_state.py session-start --auto-index` automatically at turn 0, injecting `PROJECT_MAP.md`, recent git activity, and active checkpoints/handoffs directly into the starting context so the agent skips `ls`/`find` without relying on prompt memory.
   - **Hookless IDEs (Antigravity, Cursor, Codex, Windsurf, Copilot):** `ae init` installs the short workflow block ([rules/AGENT_RULES.md](rules/AGENT_RULES.md)) into `GEMINI.md` / `.cursor/rules/agent-efficiency.mdc` (`alwaysApply: true`) / `AGENTS.md` / `copilot-instructions.md` — kick off a fresh window with `ae resume` (or bind it as your first prompt/workflow).
2. **Safe-by-default `PreToolUse` / `BeforeTool` hook** ([scripts/pretool_hook.py](scripts/pretool_hook.py)):
   - **Default (`--mode hint`):** Never rewrites commands silently. Adds a concise non-blocking tip on noisy test/build runs and nudges when the agent is about to re-read an unchanged >150-line file in full.
   - **Explicit opt-in (`ae init --auto-wrap` / `--mode rewrite`):** Transparently wraps *only* simple, pipe-free, non-interactive test/build commands (`pytest`, `npm test`, `cargo test`, `go test`, `vitest`, `tsc`, etc.) through `ae run`. Commands with pipes (`|`), redirects (`>`), chains (`&&`/`;`), subshells, complex env prefixes, or interactive/watch flags (`-i`, `--pdb`, `--watch`, `-w`) are **never** touched.
3. **Lean 7-tool MCP Core Profile (`--profile core`):** Full 39-tool MCP servers cost **~3,274 schema tokens every turn**. `ae init --mcp` and `setup_hooks.py mcp-config` default to `--profile core` (**7 tools, ~622–637 tokens — −81% schema tax**).
4. **Live Savings Counter, Actionable Doctor & Clean Rollback:** Every `ae run`, `ae slice`, and `ae outline` logs gross local I/O savings (`ae savings --statusline`); `ae doctor` lists the **Top 10 heaviest skills with exact paths** and archives unused bloat safely (`ae doctor --prune --apply`); `ae install-status` and `ae uninstall` inspect and cleanly remove every installed component.
   ```text
   ae: -142.3k tok (-86%, ~$0.43 saved / 7d)
   ```

---

## Core IDE Skills vs. Optional Pipeline Skill

| Bundle | Skills | Always-On Load | Who Needs It |
|---|---|---:|---|
| **`--profile ide` (default)** | `local-context-index` + `adaptive-orchestration-handoff` | **~119 tok** | Everyday coding in Claude Code, Cursor, Codex, Gemini CLI, Antigravity, OpenCode, Windsurf, Copilot |
| **`--profile full`** | Adds `prompt-cache-manager` | **~170 tok** | Custom Anthropic / OpenAI / Gemini / Bedrock API pipeline builders |

- **`local-context-index`**: Incremental SQLite FTS5 index (schema v5, CamelCase/snake_case/kebab-case splitting), static symbol **call graph**, monorepo alias resolution (`tsconfig.json`, `package.json` workspaces, `go.mod`), multi-target live `slice` (`a.py:foo b.py:10-40`), `diff-pack`, `trace-pack`, `tests-for`, and `run` (80–95% log compression + auto-sliced failing stacktraces).
- **`adaptive-orchestration-handoff`**: Zero-friction `checkpoint` (`CHECKPOINT.md`), 1-call `session-start`/`brief` with live SHA drift detection, ADRs (`DECISIONS.md`), anti-duplication dead-end memory, read-only IDE `audit` (Claude Code, Antigravity, Codex, Gemini, Cursor, OpenCode, Cline), and `doctor` (always-on context bloat, MCP schema tax, cache-busters & secret leaks). Optional subagent/pipeline routing in `route_task.py`.
- **`prompt-cache-manager`** *(optional)*: L0/L1 prefix linting, provider cache payload builders (Anthropic, OpenAI Chat & Responses API, Gemini, Bedrock), and verified telemetry tracking.

---

## Reproducible Benchmarks & End-to-End LLM A/B Eval

### 1. Deterministic Token & Signal-Preservation Benchmarks (Zero API Cost)

Run on **any** local or open-source repository (non-destructive copy in a temp dir) — measures token reduction against both naive reads **and** a disciplined `rg` + 90-line range-read baseline, and verifies **deterministic diagnostic & fixture-warning preservation** (target symbol definitions, `AssertionError`, fixture warning 35+ lines above the traceback, and exact `>>>` crash line preserved):

> **Scope note:** These zero-API-cost benchmarks measure *token reduction and deterministic signal preservation*, not LLM solve rate. To measure end-to-end Pass@1 solve rate, turn count, and net cached API cost with real models, run the A/B harness below.

```bash
python3 benchmarks/benchmark_efficiency.py --repo . --format md
# Benchmark multiple OSS repos side by side (e.g. local clones of Flask & a TS app):
python3 benchmarks/benchmark_efficiency.py --repo /path/to/flask --repo /path/to/ts-app --format md
```

### 2. End-to-End LLM A/B Evaluation (`benchmarks/eval_llm_ab.py`)

Evaluates 6 realistic multi-file bugfix tasks across **Python & TypeScript** — including deliberate **tunnel-vision stress cases** (fixture warning 35+ lines before traceback, module-level constant side effects, enclosing class `__init__` regressions, TypeScript interface/DI defaults) — comparing a `baseline` arm (`grep` + `read_file` + raw tests) against an `ae` arm (`ae search`/`slice --with-header`/`run --verbose` + full-read escape hatch) on **Pass@1 solve rate, turns, context escalations, cache hit rate, and USD cost**:

```bash
# Offline deterministic harness check (0 API cost — verifies all 6 bugs fail & patches pass):
python3 benchmarks/eval_llm_ab.py --mode mock --format md

# Live end-to-end A/B evaluation against real LLMs (requires ANTHROPIC_API_KEY, GEMINI_API_KEY, OPENAI_API_KEY, or litellm):
python3 benchmarks/eval_llm_ab.py --mode live --model claude-sonnet-4-20250514 --format md
python3 benchmarks/eval_llm_ab.py --mode live --model gemini-2.5-flash --format md
python3 benchmarks/eval_llm_ab.py --mode live --model gpt-4o --format md
```

> **Live API benchmark policy:** No live API numbers are hardcoded here until executed against live provider keys; run `--mode live` locally to record verified model-specific Pass@1, turn, cache-hit, and USD results.

### Measured on `agent-efficiency-skills` (78 files, 617 symbols, Apple Silicon, Python 3.9 stdlib)

| Task | Naive Baseline | Disciplined (`rg` + 90L) | With `ae` | Reduction | Fidelity |
|---|---:|---:|---:|---:|:---:|
| Read 3 symbols across 3 files (`ae slice`) | 27,410 tok | 2,897 tok | **562 tok** | **-97.9%** vs naive · **-80.6%** vs `rg` | PASS |
| Debug 181-test failure + failing file (`ae run` + `trace-pack`) | 11,110 tok | — | **271 tok** | **-97.6%** *(stops noise repeating every turn)* | PASS |
| Index speed (78 files) | — | — | **960 ms** cold · **34 ms** inc · **4.9 ms** search | — | — |

### Synthetic 35-File Multi-Language Suite & 1,000-File Scaling (`python3 benchmarks/benchmark_efficiency.py`)

| Scenario | Naive Baseline | Disciplined Baseline | AgentEfficiency | Reduction |
|---|---:|---:|---:|---|
| Exploration (`map`+`search`+`outline`+`slice` / warm `search`+`slice`) | 16,354 tok | 2,456 tok | **2,156 tok** cold / **559 tok** warm | **-86.8%** vs naive · **-77.2%** vs `rg` |
| Session resume (`checkpoint` + `brief`) | 1,636 tok | — | **96 tok** | **-94.1%** |
| Persistent state (decision + dead-end memory) | 6,104 tok | — | **285 tok** | **-95.3%** |
| Subagent handoff (`brief` + `slice`) | 16,354 tok | — | **463 tok** | **-97.2%** |
| *Custom pipelines:* Adaptive routing (5 steps) | \$0.5625 | — | **\$0.1575** | **-72.0%** |
| *Custom pipelines:* Prompt caching (10 turns, Anthropic) | 19,490 billable tok | — | **8,900 tok** | **-54.3%** |

**Scaling (1,000 files / 10,000 symbols, Apple Silicon):** cold index **1.05 s**, incremental edit **166 ms**, FTS5 search **3.3 ms**, call-graph **3.0 ms**, SQLite DB **6.2 MB**.

> **Honest scope:** Against an already disciplined agent using `rg` + tight line-range reads, typical everyday code-reading savings are **20–50%** on medium/large repos (and higher on multi-file symbol lookups). The largest universal savings come from `ae run`, `ae tests-for`, `ae doctor` (cutting always-on MCP/rules tax), and `ae checkpoint`/`brief` across compactions. On tiny `<15`-file single-file edits, read directly.

---

## Daily CLI Reference (`ae`)

`<repo>` defaults to the current working directory (override with `ae -C /other/repo ...`):

```bash
# Onboarding, Waste Audit, Diagnostics & Clean Rollback
ae init [--hooks] [--auto-wrap] [--mcp]         # Auto-detect IDEs & install skills/CLI/rules/hooks
ae install-status [--format card|json]          # Inspect active skills, rules, hooks, MCP & repo state (also `ae status --setup`)
ae uninstall [--dry-run] [--purge-repo-state]   # Non-destructively remove AE rules blocks, hooks, skills & CLI
ae audit [--limit 6 --format card|compact|json] # Visual IDE transcript waste, USD cost & weighted trends
ae doctor [--prune [--apply]] [--format card]   # Always-on bloat, top-10 skill offenders, cache-busters & safe archive
ae savings [--days 7] [--statusline]            # Gross I/O token & USD savings receipt / statusline string

# Minimal Code Context, Logs & Affected Tests
ae index                                        # Incremental FTS5 + call-graph index (.git/info/exclude)
ae search "token refresh"                       # Finds refreshAccessToken via identifier splitting
ae outline src/auth.py                          # Imports + symbol signatures & line ranges
ae slice a.py:foo b.py:Service.bar --with-header --max-tokens 1200
ae deps src/auth.py --depth 2                   # Import blast radius (tsconfig / workspaces / go.mod)
ae callgraph verify_token --depth 2 [--lsp]     # Symbol callers/callees (syntax name-matched, or type-checked via `--lsp`)
ae tests-for                                    # Minimal affected test files + suggested runner cmd
ae run [--verbose] -- pytest -q                 # Compress logs, keep fixture warnings & auto-slice crashes
ae trace-pack --file err.log                    # Raw stacktrace -> exact in-repo failing slices
ae diff-pack --base HEAD --budget-tokens 2500   # Budgeted diff + touched symbols + callers

# Session Memory & Handoff
ae resume                                       # 1-call new-window resume (auto-index + PROJECT_MAP + git + brief)
ae checkpoint --note "Ready for review"         # Zero-friction checkpoint (CHECKPOINT.md)
ae brief                                        # 1-call state/checkpoint brief with live SHA drift check
ae handoff --summary "..." --next "..."         # Zero-reexploration HANDOFF.md
```

### Optional Hooks & Lean MCP Setup
```bash
# Auto-reindex on git commit/checkout/merge (worktree-aware; preserves existing hooks):
python3 scripts/setup_hooks.py git /path/to/repo

# Merge Claude Code or Gemini CLI hooks (safe hint-only PreToolUse by default; pass --auto-wrap to opt in):
python3 scripts/setup_hooks.py runtime /path/to/repo --client claude --write
python3 scripts/setup_hooks.py runtime /path/to/repo --client claude --auto-wrap --write

# Print lean 7-tool MCP config (~622 schema tok vs ~3,274 for --profile full):
python3 scripts/setup_hooks.py mcp-config --client claude --profile core
python3 mcp/server.py --profile core --list-tools
```

---

## Guardrails, Prompt-Cache Hygiene & Runtime Support Tiers

- **Anti-Tunnel-Vision Safeguards:**
  - `ae run` preserves fixture/setup warnings above errors, emits an explicit omission notice if warnings exceed budget, archives the complete redacted `full_log`, and supports `--verbose` for wider pre-error context.
  - `ae slice --with-header` prepends compact file imports, module-level constants, and the enclosing class header within the token budget; `ae trace-pack` uses an asymmetric pre-crash window (`-6/+3`) on long functions.
  - [rules/AGENT_RULES.md](rules/AGENT_RULES.md) enforces an explicit escalation rule: if root cause is unclear or a fix fails once, widen context (`--with-header`, `--verbose`, `full_log`, or full file read) instead of burning extra turns.
- **Prompt-Cache Golden Rule:** Never `@import` mutable `.agent-state/*` files (`CHECKPOINT.md`, `HANDOFF.md`, `CURRENT_STATE.md`) into always-on `CLAUDE.md` / `AGENTS.md` / `.cursor/rules/`. `ae doctor` and `ae cache lint` flag dynamic state includes automatically, and `ae brief` omits ticking TTL countdowns so repeated briefs stay byte-stable. (`ae savings` tracks gross local I/O reduction; verify net provider cache hit rate via `ae audit`.)
- **Core vs. Runtime Support Tiers (Maintenance Boundary):**
  - **Core engine (runtime-agnostic):** `ae index`, `search`, `outline`, `slice`, `deps`, `callgraph`, `tests-for`, `run`, `trace-pack`, `diff-pack`, `doctor`, `checkpoint`, `brief` depend only on local files + Git and never break from IDE format changes.
  - **Tier 1 (CI fixture-verified adapters):** Transcript parsers & hooks for **Claude Code**, **Gemini CLI / Antigravity**, and **Codex**.
  - **Tier 2 (Best-effort / community adapters):** **Cursor**, **OpenCode**, **Windsurf**, **Copilot**, **Cline** (path mappings + best-effort `ae audit` parsers). If any client changes its log schema, `ae audit` surfaces an explicit **Schema-Drift Warning** instead of silently reporting zero usage.

## Parser Fidelity, Trust & Safety Guarantees

- **Python (`.py`, `.pyi`):** Full stdlib `ast` parsing (`analysis_confidence: "ast"`, `resolution_mode: "ast-syntax-name-matched"`) including decorators, base classes, module-level wiring, and DI/callback arguments (`Depends(verify_token)`).
- **JS/TS/TSX/Go/Rust/Java/Kotlin/Swift/C/C++/Ruby:** Zero-dependency default uses comment/string-aware brace matching + dynamic `import()` + JSX + `@Decorator` heuristics (`analysis_confidence: "heuristic"`). Install optional `pip install "agent-efficiency[ast]"` (`tree-sitter-language-pack`) for native `tree-sitter` syntax ASTs, and pass `ae callgraph --lsp` when a local LSP server (`typescript-language-server`, `pyright-langserver`, `rust-analyzer`, `gopls`) is installed for type-checked references (`resolution_mode: "type-checked-lsp"`).
- **Zero code execution during indexing & local privacy:** Strictly static parsing with `PRAGMA trusted_schema=OFF`; zero telemetry or outbound network calls (`ae audit` reads local transcripts strictly read-only). See [SECURITY.md](SECURITY.md) and [CHANGELOG.md](CHANGELOG.md).
- **Smart secret exclusion & code-safe redaction:** skips `.env*` (except `.example`/`.sample`/`.template`), private keys, `*.tfvars.json`, `*.tfstate*`, secret config files, binaries, nested `.gitignore` (`!` negation supported), and symlinks pointing to secrets — redacting hardcoded literals without corrupting code.
- **Prompt-injection isolation & atomic locking:** repository snippets are framed inside `<untrusted_repo_data>`; cross-platform locks use `fcntl.flock` (POSIX) + `msvcrt.locking` (Windows) + `os.replace()`.

## Verification

```bash
python3 scripts/sync_shared.py --check
python3 scripts/validate_skills.py
python3 -m unittest discover -s tests -v
python3 mcp/server.py --profile core --list-tools
python3 benchmarks/benchmark_efficiency.py --repo . --format md
```

## License

[MIT](LICENSE) © 2026 Jeager070
