# Coding Agent Token Economics Standard

> Source: <https://github.com/microsoft/cates>
> Published: 2026-11-29 16:55:43+00:00

**Key takeaway:** cates-analyzer scores coding-agent configs statically from a 100-point baseline with no LLM calls, and its optional --copilot profile adds 15 experimental checks across 11 configuration families without changing the stable scoring model or CI gates.

Score coding-agent configurations for **token efficiency**, **security**, and **CATES conformance** — zero LLM calls required.

This is the reference implementation for the **Coding Agent Token Economics Standard (CATES)**. It is vendor-neutral and analyzes common coding-agent configuration surfaces, including repository and path-specific instructions, prompt libraries, chat modes, MCP configs, setup steps, hooks, and editor settings.

The **initial scan remains a static configuration assessment**, not a bill or
proof of economic performance. For end-to-end costs and accepted-task outcomes,
use the separate, opt-in [experimental economics assessment](#experimental-end-to-end-token-economics).

**A grade is not an assurance certificate.** Scores start at 100 and deduct
detected findings after policy overrides and exclusions; one critical finding
can coexist with an A. Reports highlight unresolved critical findings regardless
of grade and disclose disabled/suppressed findings and discovery limits.
No findings does not establish safety, effective permissions or task correctness.
Compare scores only under the same policy and scan scope.

To pair static results with controlled permission probes and before/after
accepted-task costs, attach [optional runtime evidence](https://github.com/microsoft/cates/blob/main/docs/RUNTIME-EVIDENCE.md):
`cates-analyzer . --runtime-evidence runtime-evidence.json`.
These records are **caller-reported, not independently verified**, and never
change scores, conformance levels or CI gates.

The [Modern Agent Assurance proposal](https://github.com/microsoft/cates/blob/main/docs/MODERN-AGENT-ASSURANCE.md) records
the October 29, 2026 standards review and current primary sources. It adds
manual guidance for skills, effective permissions, MCP authorization, and
outcome validation, not new scored rules or gates. Legacy prompt-secrecy checks
are configuration heuristics, not enforceable security controls.

For deeper **GitHub Copilot hygiene**, run `cates-analyzer . --copilot`.
The [Copilot profile](https://github.com/microsoft/cates/blob/main/docs/COPILOT-HYGIENE.md) adds 15 experimental checks across
11 configuration families, explicit coverage limits, and a manual-verification
checklist. It is available in the CLI, library, API and hosted UI without
changing the stable scoring model or gates.

**OpenSSF Best Practices status: not registered; no badge claimed.**
See the [maintainer setup and assurance runbook](https://github.com/microsoft/cates/blob/main/docs/MAINTAINER-SETUP.md) for
branch-protection activation, release bootstrap, and the managed-fuzzing decision.

The [agentic SDLC guide](https://github.com/microsoft/cates/blob/main/docs/AGENTIC-SDLC.md) connects issue intake, planning,
implementation, review, releases, deployment and maintenance using the existing
toolchain. Start with the **Agent-ready task** template and the **CATES SDLC**
Copilot agent; run `npm run verify` before handoff. Agents assist with delivery;
maintainers retain merge, publication and deployment authority.

**Distribution status:** This repository is release-ready, but no version tag
or GHCR package has been published yet. Use the source-checkout instructions
below until the first GitHub release is available.

Build and run the current source:

```
git clone https://github.com/microsoft/cates.git
cd cates
npm ci
npm run build
node dist/cli/index.js .
```

Requires Node.js **>= 22.12** and npm **>= 10**. After the first release,
the npm and GHCR installation paths documented in the release notes become
the recommended options.

The package installs two commands: **`cates-analyzer`** (reports inefficiencies)
and **`cates-optimize`** (deliberately applies structurally checked edits — see
[Optimizer](#-optimizer--apply-lossless-fixes-cates-optimize)).
The programmatic package API is ESM-only; CommonJS callers must use dynamic
`import()`.

```
# Analyze current directory
cates-analyzer .

# Analyze a specific repo
cates-analyzer /path/to/repo

# JSON output for CI
cates-analyzer . --format json

# SARIF output for code scanning systems
cates-analyzer . --format sarif

# Repository URL, branch folder, file, or pull request
# (auto-detected — also works as `cates-analyzer review <url>`)
cates-analyzer https://github.com/OWNER/REPO
cates-analyzer https://github.com/OWNER/REPO/tree/main/path/to/folder
cates-analyzer https://github.com/OWNER/REPO/pull/123

# Quieter pretty output (drops the banner; keeps all data)
cates-analyzer . --quiet

# Shell completion
cates-analyzer completion bash > /usr/local/etc/bash_completion.d/cates-analyzer
cates-analyzer completion zsh  > "${fpath[1]}/_cates-analyzer"
```

Exit codes:

| Code | Meaning | 
|---|---|
| `0` | Analysis succeeded; all CI gates passed | 
| `1` | CATES gate failed ( `--min-score` ,`--require-level` ,`--fail-on` ,`--max-always-loaded` , or conformance) | 
| `2` | Usage error (invalid flag, missing argument, parse failure) | 

When running from this source checkout before publishing/installing the package, use one of these forms:

```
npm run --silent review -- https://github.com/OWNER/REPO
npm run --silent cates -- review https://github.com/OWNER/REPO
npx tsx src/cli/index.ts review https://github.com/OWNER/REPO
```

Do not run `tsc review ...` or `npm run typecheck -- review ...`; those commands invoke the TypeScript compiler and it will treat `review` and the URL as files to compile.

A small, non-root Alpine image is the easiest way to get a consistent
toolchain across Windows, macOS, and Linux (plus the right `git` and `gh`
versions baked in).

```
# Build locally
docker build -t cates-analyzer .

# Analyze the current directory (bind-mount it as /work)
docker run --rm -v "$PWD:/work" cates-analyzer .

# Review a public repo
docker run --rm cates-analyzer review https://github.com/OWNER/REPO

# Review a private repo (token never written to disk)
docker run --rm -e GH_TOKEN cates-analyzer review https://github.com/OWNER/REPO

# JSON to stdout, piped into your tooling
docker run --rm -v "$PWD:/work" cates-analyzer . --format json > report.json
```

Windows PowerShell users substitute `${PWD}` for `$PWD`.

The image runs as a non-root user, uses a read-only root filesystem, and
ships with `tini` as PID 1 so it behaves cleanly under container orchestrators.
Published `ghcr.io/microsoft/cates` tags become available with the first
GitHub release.

The chart in [`deploy/helm/cates`](https://github.com/microsoft/cates/blob/main/deploy/helm/cates/README.md) deploys
CATES as a `CronJob` (default) or one-shot `Job`. It supports
NetworkPolicies, a persistent reports volume, and a
ConfigMap-mounted `.cates.yml` policy.

```
helm install cates ./deploy/helm/cates \
  -n cates --create-namespace \
  --set githubToken.value=$GH_TOKEN \
  --set-json 'args=["demo","--limit","25","--format","json"]'
```

See [`deploy/helm/cates/README.md`](https://github.com/microsoft/cates/blob/main/deploy/helm/cates/README.md) for
production values, Workload Identity setup, and PVC-backed reports.

Don't want to install the CLI? Use the **CATES Service** — a hosted
companion that lets you score a primitive in two ways:

1. **Paste** an instruction file, prompt, MCP config, agent definition,
or`.cursorrules` directly into the browser.
2. **Scan a GitHub URL** — repo, folder, file, or pull request.

Behind the scenes the service runs the exact same analyzer as the CLI
(`analyze()` / `analyzeInMemory()`), so a score from the service is
identical to a score from `cates-analyzer` on the same bytes. There are
**no LLM calls**, **no telemetry**, and **no content logging** —
submitted text is analyzed in-process and discarded; repos fetched via
"Scan" are cloned shallowly into a temp directory that is removed as soon
as the score is returned.

| Method | Endpoint | Purpose | 
|---|---|---|
| `POST` | `/api/analyze` | In-memory analysis. Body: `{ files: [{path, content}], policy?, tokenizer? }` . | 
| `POST` | `/api/scan` | GitHub-URL analysis. Body: `{ url, policy?, tokenizer? }` . | 
| `POST` | `/api/economics` | Experimental, separate accounting over a normalized usage ledger; no scan or score. | 
| `GET` | `/api/rules` | Stable/cache-output `rules` , separate`copilotChecks` , and service limits. | 
| `GET` | `/api/healthz` | Liveness probe. | 
| `GET` | `/api/readyz` | Readiness probe. | 

All endpoints accept and return JSON. The `AnalysisResult` shape returned
by the analyze and scan endpoints is **the same** type the CLI emits with
`--format json` — every existing report consumer (dashboard, CI gates,
SARIF converter) works unchanged.

`/api/economics` instead returns an experimental `EconomicsReport`. It accepts
caller-supplied records only; it does not collect telemetry, import invoices,
or fetch prices. Economics remains separate from the hosted scan/paste UI;
the UI's Copilot hygiene selector adds static advice, not usage accounting.

| Limit | Value | 
|---|---|
| Max files per request | 50 | 
| Max bytes per file | 100 KB | 
| Max total payload | 1 MB | 
| Per-IP rate limit | 60 requests / minute | 

Limits are exposed live at `GET /api/rules` so UIs and CI integrations can
display them or pre-validate.

Rule/dimension overrides, suppressions, `experimental`, and `copilot` are
accepted in the request's `policy` field. HTTP overrides use the long object
form, not YAML shorthand. Threshold fields are accepted for shared-policy
compatibility, but HTTP endpoints return analysis reports rather than enforcing
CLI exit-code gates; callers can evaluate those reports with `evaluateGates`.

```
{
  "files": [
    { "path": ".github/copilot-instructions.md", "content": "..." }
  ],
  "policy": {
    "copilot": "all",
    "dimensions": { "security": { "enabled": false } },
    "rules": { "TE004": { "severity": "low" } }
  }
}
```

File URLs analyze the requested file; folder URLs preserve repository-relative
classification while restricting traversal. Resource-limited, unreadable and
unrecognized inputs are not evidence of a clean repository. See the
[coverage contract and resource limits](https://github.com/microsoft/cates/blob/main/docs/COPILOT-HYGIENE.md#honest-boundaries-and-resource-limits).

```
# Build and run (Node 22.12+)
npm ci
npm run build:service
npm run service:start         # listens on :8080

# Or in watch mode while developing
npm run service:dev
```

Open `http://localhost:8080`.

The same image powers both the CLI and the service. Override `CMD` to
launch the service:

```
docker build -t cates .
docker run --rm -p 8080:8080 --entrypoint node cates \
  /app/dist-service/service/server.js
```

The hosted UI ships with a **toggle drawer** at the top of the page that
fetches `GET /api/rules` and lets you:

- Disable any individual rule (single-click on the rule pill)
- Disable an entire dimension (click the dimension button — e.g. "security" if you already enforce those checks elsewhere)
- Override severity per rule
- Export the current state as `.cates.yml` for committing to your repo

Every toggle is sent in the `policy` field of the next request, so the
score updates immediately and the result includes `disabledRuleIds` /
`disabledDimensions` for auditability.

| Concern | Mitigation | 
|---|---|
| Pasted content exfiltration | No persistence, no telemetry, no content logging. The access log records `method/path/status/durationMs` only. | 
| Cross-site framing / SEO indexing | Strict CSP, `frame-ancestors 'none'` ,`X-Frame-Options: SAMEORIGIN` ,`X-Robots-Tag: noindex, nofollow` set on every response. | 
| Argv-injection via `/api/scan` URLs | URLs flow through the same `parseGitHubLink` guards used by the CLI; refs starting with`-` , traversal segments, and shell metacharacters all return`HTTP 400` . | 
| DoS via giant payloads | Hard per-file + per-request byte caps + JSON body limit, all enforced *before* the analyzer runs. | 
| DoS via repo cloning | Shallow clones with depth=1, temp dir is removed in a `finally` block even if scoring throws. | 
| Auth / multi-tenant data | None in v1 — the service is stateless and anonymous. OAuth, persisted reports, and org dashboards are on the Phase 3 roadmap; see [`VERSIONING.md`](https://github.com/microsoft/cates/blob/main/VERSIONING.md) and the session plan. | 

| Capability | What you get | 
|---|---|
| **Zero-LLM static analysis** | Deterministic, fast, no API keys, no data exfiltration | 
| **49 stable rules** across 6 scored dimensions, plus 10 experimental rules | Token efficiency, security, specificity, completeness, conflict/reachability, harness quality, cache shaping, and output shaping | 
| **Per-family tokenizers** | Model-family tokenizers or an offline approximation — pick one or compare side-by-side | 
| **Multi-surface discovery** | Repository + path-specific instructions, prompt libraries, chat modes, MCP configs, hooks, setup steps, editor settings | 
| **Configurable** | Toggle any rule or whole dimension on/off, override severities, suppress with reasons + expirations | 
| **Multiple output formats** | Human-readable text, JSON, **SARIF** for code scanning systems | 
| **CI-ready gates** | `--min-score` ,`--require-level` ,`--fail-on` ,`--max-always-loaded` | 
| **Conformance levels** | Score against CATES Level 1, 2, or 3 | 
| **Repository review** | `cates-analyzer review <url>` for repos, branches, folders, files, or PRs | 
| **Hosted service + HTTP API** | Paste / scan / programmatic access via the [CATES Service](#-cates-service-hosted-ui--http-api) — same engine, no install | 
| **Portfolio scanning** | Roll up many repos into one report | 
| **Demo mode** | Scan repositories supplied through a custom manifest | 
| **Safe autofix** | `--fix` /`--fix-dry-run` for mechanical, reviewable changes | 
| **Static economics signals** | Per-finding heuristic impact and legacy savings estimates; not measured spend or proven reductions | 
| **Experimental lifecycle accounting** | Separate usage-ledger assessment: cache/input/output, retries and child calls, explicit rates, non-model costs, and cost per accepted task | 
| **Hardened runtime** | Sandboxed reads, argv-injection guards, size/depth limits, binary detection, no network calls in analyze mode | 
| **Multiple ship targets** | npm CLI, Docker image, Helm chart, and local HTTP service | 

CATES is policy-driven. Drop a `.cates.yml`, `.cates.yaml`, or `.cates.json`
at your repo root (or pass `--policy <path>`) and you can:

- Set CI quality gates (`minScore` ,`requireLevel` ,`failOn` ,`maxAlwaysLoadedTokens` )
- **Toggle any individual rule on/off**
- **Toggle an entire dimension on/off** (e.g. skip all security rules
because your org already uses GitHub Advanced Security)
- **Override the severity** of any rule or dimension
- Suppress specific findings (with required reasons and optional expirations)

Both YAML and JSON are accepted. A minimal annotated example:

```
# .cates.yml — full schema
minScore: 80
requireLevel: 1
failOn: [critical]
maxAlwaysLoadedTokens: 1500

# ─── Whole-dimension toggles ─────────────────────────────────────────
# Disable an entire category of rules in one line. Useful when another
# tool already covers it (e.g., another approved scanner owns these checks).
dimensions:
  security: off              # skip CATES SEC* and security-tagged MCP/STP rules
  # token-efficiency: off
  # specificity: off
  # completeness: off
  # conflict-reachability: off
  # harness-quality: off

# ─── Per-rule toggles & severity overrides ───────────────────────────
# Most specific wins: rules[<id>] > dimensions[<dim>] > built-in defaults.
# Shorthand:  off | on | <severity>   (critical|high|medium|low|info)
# Long form:  { enabled: true|false, severity: <severity> }
rules:
  SEC001: off                # disable a single rule
  TE004: low                 # downgrade Forced Verbosity from high to low
  MCP002: on                 # re-enable one rule even though `security: off`
  CMP002: { severity: high } # long form

# ─── Suppressions (for documented false positives / accepted risk) ───
suppressions:
  - ruleId: SEC004
    file: .github/copilot-instructions.md
    reason: Legacy wording criterion waived; host access controls reviewed separately
    owner: @platform-team
    expires: 2026-12-31
```

The same shape works as JSON:

```
{
  "minScore": 80,
  "dimensions": { "security": "off" },
  "rules": { "SEC001": "off", "TE004": "low" }
}
```

**Tip:** set `dimensions.security: off` when another approved scanner owns
secret scanning and code scanning. CATES will
still score token efficiency, specificity, completeness, conflicts, and
harness quality, and any individual security rule you want to keep
(e.g. `MCP002`, `SEC005`) can be re-enabled with `rules.<ID>: on`.

Disabled rules and dimensions are reported in the JSON output under
`disabledFindings`, `disabledRuleIds`, and `disabledDimensions` so you
can audit exactly what was filtered.

Once you have a report, here's how to drive the score up:

1. **Critical findings first** — almost always`SEC001` (hardcoded secrets)
or`MCP002` (secrets in MCP config). Rotate the credential, then remove
it from history and move it behind an env var / secret manager.
2. **High-severity security & token waste** —`SEC003` (overly permissive
scope),`SEC005` (system-prompt leakage),`TE004` (forced verbosity),`TE006` (cross-file duplication).
3. **Token budget breach** — if`TE001` fires, your always-loaded config
is over the 1,500-token budget. Move conditional or rarely-used
guidance into scoped instruction files or on-demand prompt files.
4. **Specificity & completeness** — replace vague language (`SPC001` ) with
concrete file paths, commands, and decision criteria; add the missing
essential topics flagged by`CMP002` .

```
# Explain any rule, including the CATES section it maps to and how to fix it
cates-analyzer explain SEC003
cates-analyzer explain TE004

# Apply mechanical, reviewable fixes (only rules marked autofix-safe)
cates-analyzer . --fix-dry-run     # preview
cates-analyzer . --fix             # apply

# Re-run with a stricter gate to confirm the fix
cates-analyzer . --min-score 85 --fail-on critical,high
```

- Commit a `.cates.yml` so the policy is reviewed like code.
- If a rule is genuinely not applicable, **disable
it** in`.cates.yml` rather than ignoring it everywhere.
- If a finding is a known false positive, **suppress it** with a reason
and (ideally) an`expires` date — the suppression report tells you
when those expire.
- Wire CATES into CI with `--format sarif` and upload to your code scanning
system, or`--format json` and feed it into your own dashboards.

Every report contains a `recommendations` block, prioritized and
estimated as heuristic configuration-token impacts, not measured savings. Impacts
can overlap and may not reflect actual client loading. Start at priority 1 and work
down — each item lists the affected files, the safety classification,
and whether it's autofixable.

```
# Compare scores across runs by saving JSON reports per commit
cates-analyzer . --format json > reports/$(git rev-parse --short HEAD).json
```

For multi-repo views use `cates-analyzer portfolio <path>` or the demo
manifest (`cates-analyzer demo --limit 25`).

The analyzer **reports** what's inefficient. `cates-optimize` is a **separate,
deliberately-run tool** that **acts on that report**: it rewrites your Copilot
primitives (instructions, prompts, chat modes, agents, skills, rules files) to be
reduce configuration source tokens using structural text checks, then
prints source-token counts and a static re-score. It does **not** establish
unchanged model behavior, task quality, request-token reductions or lower bills.

It is intentionally **not** wired into `cates-analyzer` — you run it on purpose.

`cates-optimize` retains the legacy `lossless` safety label for compatibility.
It removes duplicates, recognized filler and whitespace; even these edits can
change how a model follows instructions. Available transformations:

| Optimizer | Rule | What it removes | 
|---|---|---|
| `dedupe-lines` | TE007 | Later exact duplicates of an instruction line (first copy stays) | 
| `dedupe-blocks` | TE007 | Later byte-identical multi-line blocks within a file | 
| `remove-filler` | TE003 | Standalone lines that only restate model defaults (e.g. "You are a helpful assistant") | 
| `whitespace` | — | Trailing whitespace, blank-line runs (code fences untouched) | 

Before writing any file, the tool compares a **normalized set of non-filler lines
and code-line entries**, then **re-scores with the same CATES engine**.
The signature ignores order and repetition and uses heuristic filler matching;
it does not prove byte-identical code blocks or semantic/behavioral equivalence.
Run representative before/after tasks before adopting edits. Anything that needs human
judgement (restructuring always-loaded context, extracting big code examples,
rewriting forced verbosity or negative-constraint lists, deduping across files,
removing secrets) is **left untouched** and surfaced as "remaining opportunities".

Want the strictest purely-mechanical run? Add `--skip remove-filler` to keep only
whitespace + exact-duplicate removal.

```
cates-optimize .                          # optimize the current repo, write changes
cates-optimize . --dry-run                # preview the gain, write nothing
cates-optimize . --backup                 # keep a <file>.orig next to each change
cates-optimize . --format json            # machine-readable achievement report

# Reuse a report you already produced with the analyzer:
cates-analyzer . --format json > report.json
cates-optimize --report report.json

cates-optimize --list-optimizers          # show available optimizers
cates-optimize . --only dedupe-lines,whitespace
```

The report leads with the headline efficiency gain (token reduction on active and always-loaded config), a before/after table (tokens, CATES score, findings), the per-file changes, the text-check details and limitations, and the remaining manual opportunities.

Beyond configuration size, two possible economic improvement areas are assessed
statically through **experimental, non-normative** rules — **cache-shaping**
(`CS001`–` CS005`: volatile tokens in the always-loaded prefix, dynamic-before-static
ordering, …) and **output-shaping** (`OS001`–` OS005`: missing output contract,
full-file-rewrite mandates, unconditional verbose reasoning, …).

These are **OFF by default, carry zero scoring weight, and are excluded from
conformance and CI gates** — your score and grade are byte-identical whether the
flag is on or off. Run them to *see the wider token impact*:

```
cates-analyzer . --experimental         # full report + a labeled experimental section
cates-analyzer . --experimental-only    # just the cache/output-shaping findings
CATES_EXPERIMENTAL=1 cates-analyzer .    # or via env var
cates-optimize . --experimental          # advisory token impact (never auto-applied)
```

Or opt in via policy:

```
# .cates.yml
experimental: true
rules:
  OS002: off                  # disable a specific experimental rule
  CS001: { severity: low }    # or soften one
```

Findings live in a separate `result.experimental` channel with
`"stability": "experimental"` and are **SemVer-exempt**. See
[`docs/EXPERIMENTAL-CACHE-OUTPUT-DIMENSIONS.md`](https://github.com/microsoft/cates/blob/main/docs/EXPERIMENTAL-CACHE-OUTPUT-DIMENSIONS.md)
and `CATES-v1.0.md` §5.4 / §9.9 / §9.10. These are informative parts of the
working draft, **not normative conformance requirements**. Static signals do
not establish cache hits, universal price ratios, or behavior-preserving savings.

**Annex L** expands CATES beyond configuration hygiene while leaving the
initial scan, its 49 stable rules, six scored dimensions, and CI gates intact.
Invoke the separate accounting mode only when you have usage/outcome records:

```
# Synthetic worked example, not real vendor pricing
node dist/cli/index.js economics examples/economics.json
node dist/cli/index.js economics examples/economics.json --format json
# Installed command: cates-analyzer economics usage.json
```

The experimental assessment accounts for **uncached input, cache reads/writes,
output including reasoning, retries, failed/cancelled work, child-agent calls,
retrieval and compaction calls**, and separately supplied tool, compute, storage,
network, human-review, and adjustment costs. It reports cost/tokens per
**accepted task**, provider/model and purpose attribution, and elapsed latency.

It prevents double counting, retains rate provenance, distinguishes reported
charges from estimates, and keeps missing data **unknown rather than zero**.
There are no hardcoded vendor prices, model calls, telemetry collectors, or
economic gates. Complete coverage is caller-declared, not independently audited;
empirical optimization benefits remain unproven until evaluated.

See the [full economics contract and lifecycle coverage matrix](https://github.com/microsoft/cates/blob/main/docs/TOKEN-ECONOMICS.md)
for every field, accounting equation, provider-normalization boundary, worked
example, limitation, and evidence/graduation requirement. The same assessment
is available as `analyzeEconomics(input)` and `POST /api/economics`; no runtime
economics UI or automatic provider adapters are included.

| Dimension | Weight | What It Checks | 
|---|---|---|
| **Security** | 25% | Secrets, prompt injection vectors, overly permissive grants, system prompt leakage | 
| **Token Efficiency** | 25% | Redundancy, verbose examples, generic filler, forced verbosity, negative constraint spam | 
| **Specificity** | 15% | Vague vs actionable instructions, project-specific context, concrete patterns | 
| **Completeness** | 15% | Coverage of testing, error handling, style, architecture, security, scope, output | 
| **Conflict & Reachability** | 10% | Contradictory instructions and precedence conflicts | 
| **Harness Quality** | 10% | Scope limits, failure handling, output constraints, verification steps | 

This tool is hardened against adversarial configs:

- **Sandboxed reads** —`realpath()` verification prevents symlink escapes
- **Size/depth/count limits** — no DoS via deep trees or huge files
- **Binary detection** — skips non-text files
- **No execution** — never runs or evaluates discovered content
- **Secret redaction** — findings never expose full secrets
- **No network calls** — purely local analysis (zero data exfiltration risk)
- **Strict CLI validation** — invalid formats, gates, severities, and limits fail loudly
- **Auditable suppressions** —`.cates.yml` suppressions require reasons and support expiration dates

This tool practices what it preaches:

- **Zero LLM calls** for core scoring — pure heuristic-based analysis
- **Real tokenizers per model family** :
  - `openai-cl100k` (default) — GPT-3.5, GPT-4, GPT-4 Turbo
  - `openai-o200k` — GPT-4o, o1, o3, o4 series
  - `anthropic-claude` — Claude (BPE; exact for Claude 2, approximation for Claude 3+)
  - `approx` — offline character heuristic
- **Config precedence awareness** — knows which files are always-loaded vs conditional
- **Token reduction projections** with conservative direct-token reduction and projected retry/tool-call reduction percentages

Pick one for scoring with `--tokenizer`, or compare side-by-side with `--compare-tokenizers`:

```
cates-analyzer . --tokenizer anthropic-claude
cates-analyzer . --compare-tokenizers openai-cl100k,openai-o200k,anthropic-claude
cates-analyzer tokenizers                # list supported tokenizers
```

The default tokenizer can also be set via `CATES_TOKENIZER=anthropic-claude`.

| File Pattern | Type | Loading Scope | 
|---|---|---|
| `AGENTS.md` ,`CLAUDE.md` ,`GEMINI.md` ,`QWEN.md` ,`.ai/instructions.md` ,`.github/copilot-instructions.md` | Root instructions | Always-loaded | 
| Nested `AGENTS.md` ,`CLAUDE.md` ,`GEMINI.md` ,`QWEN.md` | Scoped instructions | Conditional | 
| `.github/instructions/*.instructions.md` ,`.ai/instructions/*.instructions.md` | Path-specific instructions ( `applyTo` ) | Conditional (always-loaded when `applyTo` targets every file) | 
| `.github/prompts/*.md` ,`.ai/prompts/*.md` ,`.claude/commands/*.md` ,`.gemini/commands/*.md` | Prompt/command files | On-demand | 
| `.github/chatmodes/*.chatmode.md` ,`.ai/chatmodes/*.chatmode.md` | Custom chat modes | On-demand | 
| `agents/*` ,`.github/agents/*` ,`.ai/agents/*` ,`.claude/agents/*` ,`.gemini/agents/*` | Agent definitions | Conditional | 
| `.cursorrules` ,`.cursor/rules/*.mdc` ,`.windsurfrules` ,`.windsurf/rules/*` ,`.clinerules` ,`.cline/rules/*` ,`.roo/rules/*` ,`.ai/rules/*` | Rule files | Always/conditional | 
| MCP configs ( `mcp.json` ,`.mcp.json` ,`.vscode/mcp.json` ,`.claude/mcp.json` ,`.gemini/mcp.json` ,`.ai/mcp.json` ) | Tool/server configs | Conditional | 
| `.vscode/settings.json` ,`.cursor/settings.json` ,`.claude/settings*.json` ,`.gemini/settings.json` ,`.aider.conf.yml` ,`.aiderignore` | Editor/CLI settings | Conditional | 
| Setup and hook configs ( `.ai/agent-setup.yml` ,`.github/workflows/copilot-setup-steps.yml` ,`.pre-commit-config.yaml` ,`.claude/hooks/*` ,`.ai/hooks/*` ) | Agent environment/harness | Environmental | 

```
Usage:
  cates-analyzer analyze [options] [path]
  cates-analyzer review [options] <source>
  cates-analyzer conformance [options] [path]
  cates-analyzer rules [options]
  cates-analyzer explain <ruleId>
  cates-analyzer portfolio [options] [path]
  cates-analyzer demo [options]
  cates-analyzer tokenizers [options]

Common analyze options:
  -f, --format <format>       pretty, json, sarif
  --policy <path>             .cates.yml/.json policy file
  --min-score <n>             quality gate
  --require-level <n>         require CATES Level 1, 2, or 3
  --fail-on <list>            e.g. critical,high
  --max-always-loaded <n>     token budget gate
  --tokenizer <name>          openai-cl100k (default), openai-o200k, anthropic-claude, approx
  --compare-tokenizers <list> side-by-side counts
  --files <list>              comma-separated relative files to analyze
  --individual                score each --files entry separately
  --fix / --fix-dry-run       safe mechanical fixes
```

`review` accepts local folders and GitHub URLs. For private repositories, authenticate with `gh auth login` and use `review`; CATES uses local GitHub CLI credentials instead of asking for tokens.

`demo` scans repositories supplied with `--repos-file repos.txt`, where each non-comment line is either a repository URL or `<category> <repository URL>`.

You can also run demo mode through the default command with `cates-analyzer --demo`.

Policy suppressions can be used for documented false positives or temporary accepted risk:

```
suppressions:
  - ruleId: SEC004
    file: .github/copilot-instructions.md
    reason: Legacy wording criterion waived; host access controls reviewed separately
    expires: 2026-12-31
src/
├── cli/index.ts              # Commander.js CLI entry point
├── analyzers/
│   ├── index.ts              # Orchestrator (parallel analyzer execution)
│   ├── discovery.ts          # Secure file enumeration + tokenization
│   ├── token-efficiency.ts   # Waste pattern detection
│   ├── security.ts           # Secret/injection/permission analysis
│   ├── specificity.ts        # Vagueness and project-context checks
│   ├── completeness.ts       # Topic coverage analysis
│   └── conflicts.ts          # Contradiction detection + harness quality
├── rules/
│   └── catalog.ts            # Machine-readable CATES rule catalog
├── scoring/
│   ├── calculator.ts         # Weighted multi-dimension scoring
│   ├── recommendations.ts    # Prioritized action generation
│   └── report.ts             # Pretty/JSON/SARIF formatters
├── conformance.ts            # Level/gate evaluation
├── policy.ts                 # .cates.yml loading
├── autofix.ts                # Safe fix/dry-run support
├── portfolio.ts              # Multi-repo scanning
├── utils/
│   └── tokenizer.ts          # cl100k_base tokenizer + context measurement
├── types.ts                  # Zod-validated type definitions
└── index.ts                  # Library entry point
npm ci
npm run typecheck:all   # CLI + service TypeScript validation
npm test                # Vitest suite (284 tests, ~2s)
npm run test:coverage   # Coverage + enforce the floor (stmt 88, branch 82, func 92, line 88)
npm run service:dev     # Run the HTTP service locally with hot reload
npx tsx src/cli/index.ts ./fixtures/bad   # Test against bad config
npx tsx src/cli/index.ts ./fixtures/good  # Test against good config
npm run release:check   # Full release validation + package preview
```

CI runs `npm run test:coverage`, so any PR that drops below the configured
coverage thresholds (set in `vitest.config.ts`) will fail. The floor is
intentionally below the achieved coverage (~93 / 85 / 96 / 94)
so normal refactors don't trigger flakes; raise it when you legitimately
improve coverage, never silently lower it.

The analyzer catalog contains **49 stable rules** grouped by scored dimension
and **10 opt-in experimental rules** for cache and output shaping. The same
data is available programmatically:

```
cates-analyzer rules --format json     # full machine-readable catalog
cates-analyzer explain SEC003          # full detail + remediation for one rule
```

Use the [`Configuring CATES`](#configuring-cates) section to
turn any rule on/off or override its severity in `.cates.yml`.

**Legend:** Severity follows CATES §9. **Autofix ✅** means
`cates-analyzer . --fix` can apply a safe, mechanical change for this
rule; `—` means the fix is manual.

| Rule | Title | Severity | CATES § | Autofix | 
|---|---|---|---|---|
| MCP002 | Secrets in MCP Configuration | Critical | Annex C | — | 
| SEC001 | Hardcoded Secrets | Critical | 9.3 | — | 
| SEC007 | Autonomy / Approval Bypass | Critical | 9.3 | — | 
| AGT001 | Subagent Missing Tool Restriction | High | 9.8 | — | 
| CMD001 | Command Auto-Executes Shell | High | 9.8 | — | 
| EDC003 | Overly Permissive Tool Allowlist | High | Annex F | — | 
| MCP003 | Insecure MCP Endpoint | High | Annex C | — | 
| MCP005 | Shell Operators in MCP Command | High | Annex C | — | 
| SEC002 | Injection Vectors | High | 9.3 | — | 
| SEC003 | Overly Permissive Scope | High | 9.3 | — | 
| SEC005 | System Prompt Leakage Risk | High | 9.3 | — | 
| SEC006 | Unsafe Execution Patterns | High | 9.3 | — | 
| STP001 | Pipe-to-Shell Setup Pattern | High | Annex D | — | 
| MCP006 | Unpinned MCP Server Package | Medium | Annex C | — | 
| SEC004 | Missing Prompt Protection | Medium | 9.3 | ✅ | 
| STP003 | Broad Setup Permissions | Medium | Annex D | — | 
| HK003 | Outdated Hook Version | Low | Annex E | — | 

| Rule | Title | Severity | CATES § | Autofix | 
|---|---|---|---|---|
| TE004 | Forced Verbosity | High | 9.2 | — | 
| TE006 | Cross-File Duplication | High | 9.2 | — | 
| PRM002 | Oversized Prompt File | Medium | Annex B | — | 
| TE001 | Excessive Always-Loaded Token Count | Medium | 9.2 | — | 
| TE002 | Excessive Inline Code Examples | Medium | 9.2 | — | 
| TE005 | Negative Constraint Spam | Medium | 9.2 | — | 
| TE007 | Within-File Duplicate Instructions | Medium | 9.2 | ✅ | 
| TE008 | Unbounded Context Includes | Medium | 9.2 | — | 
| HK002 | Heavy Hook Operation | Low | Annex E | — | 
| STP002 | Missing Dependency Caching | Low | Annex D | — | 
| TE003 | Generic Filler Instructions | Low | 9.2 | — | 

| Rule | Title | Severity | CATES § | Autofix | 
|---|---|---|---|---|
| SPC001 | Vague Language | Medium | 9.4 | — | 
| SPC002 | Missing Project Context | Medium | 9.4 | — | 
| AGT002 | Subagent Missing Description | Low | 9.8 | — | 
| MCP004 | Missing MCP Server Descriptions | Low | Annex C | — | 
| PRM001 | Missing Prompt Purpose Header | Low | Annex B | ✅ | 
| PRM003 | Excessive Hardcoded File Paths | Low | Annex B | — | 
| SPC003 | Missing Architecture Structure | Low | 9.4 | — | 
| SPC004 | Long Abstract Instruction Block | Low | 9.4 | — | 

| Rule | Title | Severity | CATES § | Autofix | 
|---|---|---|---|---|
| CMP001 | No Configuration Content | High | 9.5 | — | 
| CMP002 | Missing Essential Topics | Medium | 9.5 | — | 
| MCP001 | Invalid MCP Config Syntax | Medium | Annex C | — | 
| STP004 | Missing Test Framework Setup | Medium | Annex D | — | 
| CMP003 | Monolithic Configuration File | Low | 9.5 | — | 
| EDC001 | Invalid Editor Settings Syntax | Low | Annex F | — | 
| EDC002 | AI Assistance Disabled Broadly | Low | Annex F | — | 
| PRM004 | No Variables in Large Prompt | Low | Annex B | — | 
| PRM005 | Prompt Library Sprawl | Low | Annex B | — | 
| STP005 | Missing Linter Setup | Low | Annex D | — | 

| Rule | Title | Severity | CATES § | Autofix | 
|---|---|---|---|---|
| CNF001 | Contradictory Instructions | High | 9.6 | — | 
| HK001 | Interactive Hook | Medium | Annex E | — | 

| Rule | Title | Severity | CATES § | Autofix | 
|---|---|---|---|---|
| CNF002 | Missing Harness Element | Medium | 9.6 | — | 

| Prefix | Surface | 
|---|---|
| `SEC` | Core security checks across all configuration | 
| `TE` | Token-efficiency / waste pattern checks | 
| `SPC` | Specificity / actionability checks | 
| `CMP` | Completeness / topic-coverage checks | 
| `CNF` | Conflict & reachability checks | 
| `PRM` | Prompt-file checks (CATES Annex B) | 
| `MCP` | MCP configuration checks (CATES Annex C) | 
| `STP` | Setup-step checks (CATES Annex D) | 
| `HK` | Hook checks (CATES Annex E) | 
| `EDC` | Editor configuration checks (CATES Annex F) | 
| `AGT` | Subagent-definition checks (CATES §9.8) | 
| `CMD` | Slash-command checks (CATES §9.8) | 

This package follows [Semantic Versioning 2.0.0](https://semver.org/spec/v2.0.0.html).
Releases are automated by
[release-please](https://github.com/googleapis/release-please) from
[Conventional Commits](https://www.conventionalcommits.org/) on `main`:

- `feat:` → MINOR bump
- `fix:` /`perf:` → PATCH bump
- `feat!:` or`BREAKING CHANGE:` → MAJOR bump

The full policy (including how the CATES standard document is versioned
separately from the analyzer) is in [`VERSIONING.md`](https://github.com/microsoft/cates/blob/main/VERSIONING.md), and
all releases are recorded in [`CHANGELOG.md`](https://github.com/microsoft/cates/blob/main/CHANGELOG.md).

Copyright (c) Microsoft Corporation.

Licensed under the [MIT License](https://github.com/microsoft/cates/blob/main/LICENSE.TXT).

This project welcomes contributions and suggestions. See [CONTRIBUTING.md](https://github.com/microsoft/cates/blob/main/CONTRIBUTING.md) for details,
including the Microsoft Contributor License Agreement requirement.

This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/).

For information about reporting security vulnerabilities, please see [SECURITY.md](https://github.com/microsoft/cates/blob/main/SECURITY.md).
Do not report security issues through public issue trackers; use the Microsoft Security Response
Center reporting process described there.

See [SUPPORT.md](https://github.com/microsoft/cates/blob/main/SUPPORT.md) for how to file issues and get help.

CATES does not collect telemetry and does not send usage data or analyzed content to Microsoft.
See [PRIVACY](https://github.com/microsoft/cates/blob/main/PRIVACY) for details.

This project may contain trademarks or logos for projects, products, or services. Authorized use of
Microsoft trademarks or logos is subject to and must follow
[Microsoft's Trademark & Brand Guidelines](https://www.microsoft.com/en-us/legal/intellectualproperty/trademarks/usage/general).
Use of Microsoft trademarks or logos in modified versions of this project must not cause confusion
or imply Microsoft sponsorship. Any use of third-party trademarks or logos is subject to those
third-party policies.
