Skip to main content

trace2rules

Mine coding-agent sessions into evidence-backed AGENTS.md rules.

trace2rules is a local-first CLI. It ingests agent trajectories, detects recurring friction (setup failures, repeated exceptions, oversized output, rediscovery hotspots), and proposes a small number of repository-specific rules with the evidence attached.

Status: beta. The output is a proposal, not an automatically applied AGENTS.md.

Example finding

On the demo corpus, PDM, a Python package manager, showed its most expensive repeated friction as a setup loop: import pdm failed until pip install -e . was run. It appeared in 56 sessions and accounted for ~82,966 setup tokens.

synthesize turns that into:

trace2rules ingest --format swe-rebench --repos pdm-project__pdm --limit 200
trace2rules synthesize --repo pdm-project/pdm --out -

The default path is LLM-backed. Add --offline to force deterministic rules.

Example output (abridged; model output varies):

# AGENTS.md

Generated by trace2rules from 200 sessions in pdm-project/pdm.

## convention
- **Rule:** Run `pip install -e .` once at the start of a session before importing `pdm` or invoking the `pdm` CLI. Skipping editable installation causes `ImportError` and `which pdm` failures that trigger repeated setup retries.
  **Evidence:** 56 sessions with ImportError recovery (82,966 tokens) and 28+14+12 exact setup sequences (~73,149 setup_tax tokens).

## test_command
- **Rule:** Run scoped tests directly with `python -m pytest tests/ -x -q -k "<expr>"` instead of running `python -m pytest --version` and separate `python -c "import pdm"` probes first.
  **Evidence:** 12 exact test-setup sessions (26,806 total tokens, 14,565 setup_tax tokens) and 199 sessions running run_tests.

## convention
- **Rule:** Read the exact exception signature on any `exit:1` or `ImportError` failure; if the same signature repeats after an edit, fix the product code or test scope instead of editing or re-running the harness.
  **Evidence:** 3 sessions with paired_instances=2 and delta_rework=+2.13 (26,079 tokens), plus 68 exit:1 recovery sessions (117,440 tokens).

## context_hygiene
- **Rule:** Truncate verbose `execute_bash` output with `-q` or `| head`/`| tail`, and skip redundant `view /workspace` and `pwd` checks before reading `README.md` or `tests/`.
  **Evidence:** 181 sessions averaging 1,804 tokens per bash call (373,521 tokens) and 143 workspace-exploration cluster sessions (782,785 tokens).

Rules are capped at 5 rules, 60 lines, and 2,500 characters per repo.

Synthesis

Synthesis is LLM-first. trace2rules synthesize sends redacted gated findings for each repo to an OpenAI-compatible chat model and asks for structured rules. Common API keys, bearer tokens, URL credentials, query tokens, password assignments, and private keys are redacted before external calls; redaction is best-effort, not a guarantee.

Provider selection:

  1. TRACE2RULES_LLM_API_KEY — API key for a custom OpenAI-compatible endpoint.
  2. GEMINI_API_KEY or GOOGLE_API_KEY — Gemini OpenAI-compatible endpoint.
  3. OPENAI_API_KEY — OpenAI.

If no key is configured, or the call fails, synthesis falls back to deterministic rules and continues. --offline forces the deterministic path without a network call.

TRACE2RULES_BASE_URL makes any OpenAI-compatible endpoint usable, including a LiteLLM proxy.

Supported inputs

Format What it reads Notes
swe-rebench nebius/SWE-rebench-openhands-trajectories parquet Opt-in; streamed from Hugging Face
agent-trajectory Local Claude Code, Codex, Pi, OMP, OpenCode SQLite/JSON Default; Node.js 20+ required for non-OpenCode sources

SWE-chat is not a primary input. It is used below as an optional example corpus.

Datasets are not included in this repository.

Install

Use the published package:

uv tool install trace2rules
# or
pip install trace2rules

For development from a clone:

uv sync

agent-trajectory calls its bundled JS bridge through the system Node runtime for Claude Code, Codex, Pi, and OMP. Install Node.js 20 or newer; OpenCode SQLite ingestion is pure Python.

Quick start: your own sessions

Analyze the sessions already on your machine.

uv tool install trace2rules
trace2rules ingest --source ~ --limit 50
trace2rules mine
trace2rules synthesize

Or hand the workflow to your coding agent:

Read the trace2rules README, install it with uv tool install trace2rules if it is missing, then ingest my local agent sessions. Use trace2rules report to surface recurring friction with evidence and synthesize repo-specific AGENTS.md rules from that JSON.

--source is repeatable. --source ~ scans all standard local stores: ~/.claude/projects, ~/.codex/sessions, ~/.pi/agent/sessions, and ~/.omp/agent/sessions. The example imports 50 sessions per source; use --limit 0 for all.

LLM synthesis is the default. Add --offline if you do not have an API key.

ingest writes to data/trace2rules.duckdb by default. mine, exact, and synthesize read from it.

Public dataset: SWE-rebench

To reproduce the PDM example above without local sessions, ingest the default SWE-rebench OpenHands parquet from Hugging Face. django__django is an instance_id prefix, not a GitHub slug.

uv run trace2rules ingest --format swe-rebench --repos django__django --limit 50
uv run trace2rules mine
uv run trace2rules synthesize

Optional example corpus: SWE-chat

SWE-chat is an optional example corpus, not a core input format. It is useful for reproducing the PDM finding above.

Request access on the dataset page, then download the two tables:

uvx --from huggingface_hub hf download SALT-NLP/SWE-chat \
  --repo-type dataset \
  --include "sessions.parquet" \
  --include "conversations.parquet" \
  --local-dir data/swe-chat

uv run trace2rules ingest \
  --format swe-chat \
  --source data/swe-chat \
  --limit 0

uv run trace2rules mine
uv run trace2rules synthesize

--limit 0 imports the full corpus. The default limit is 200 sessions. For swe-rebench, --limit 0 also means all matching sessions.

Local agent sessions

uv run trace2rules ingest \
  --format agent-trajectory \
  --source ~ \
  --limit 0

With --source ~, it scans the standard stores:

  • ~/.claude/projects
  • ~/.codex/sessions
  • ~/.pi/agent/sessions
  • ~/.omp/agent/sessions
  • ~/.local/share/opencode

OpenCode is read directly from its SQLite database; JSON exports are still accepted:

uv run trace2rules ingest --format agent-trajectory --source ~/.local/share/opencode

Use --repo owner/name to override the repository label for local sessions.

Commands

Command Purpose
ingest Load sessions and tool events into DuckDB
mine Show friction clusters, hotspots, recovery loops, and context blasts
report Emit all findings and patterns as evidence-rich JSON for an agent
doctor Check install, Node, credentials, source stores, and database schema
label Optional: classify targets with a decision model (intent, object_type, confidence)
patterns Mine structural multi-step friction; labels refine when available
exact Show exact recurring sequences with evidence
synthesize Write per-repo .proposed.md files

Useful options:

trace2rules ingest                         # ~, all detected local stores
trace2rules ingest --label                 # auto-detect clef/Gemini/OpenAI
trace2rules ingest --format swe-rebench    # opt into the public dataset
trace2rules ingest --source PATH --limit 200
trace2rules synthesize
trace2rules synthesize --offline
trace2rules synthesize --max-rules 10
trace2rules synthesize --out-dir ./proposals
trace2rules synthesize --repo owner/name --out AGENTS.proposed.md
trace2rules synthesize --repo owner/name --out -

--label auto-detects an authenticated wrangler first, then GEMINI_API_KEY/GOOGLE_API_KEY, then OPENAI_API_KEY. It is opt-in because a full local run can have thousands of unique targets.

Agentic workflow

The built-in synthesizer is optional. An agent can consume the evidence directly:

trace2rules ingest
trace2rules report > /tmp/trace2rules-report.json

report emits JSON with repo/session/instance counts, findings, labels, exact sequences, and label-driven patterns. Each finding carries sessions, tokens, evidence, and detector-specific fields such as lift, rework, setup_tax, cost, and paired_instances.

The calling agent can then write AGENTS.md rules from that evidence without invoking trace2rules synthesize or configuring an LLM key.

--out - writes the markdown to stdout and sends progress/findings to stderr.

Synthesis is LLM-first. --offline skips the LLM and uses deterministic rules.

Decision labels

trace2rules label classifies each distinct normalized target with a decision model:

  • intent: explore, read, search, edit, run_tests, run_script, install, env_check, git, other
  • object_type: file, directory, test_scope, package, module, config, unknown

It stores the chosen labels and confidence in target_labels. synthesize annotates matching findings, sends the label summary to the LLM prompt, and drops low-confidence or other labels from deterministic rules. patterns mines structural object-level sequences without labels and uses labels only to name events when confidence is high.

Supported models:

--model Provider Credential
clef-flash (default) Cloudflare Workers AI wrangler login
clef Cloudflare Workers AI wrangler login
jev Cloudflare Workers AI (typesafe/jev) wrangler login
gemini-decision-1 Gemini Decisions API GEMINI_API_KEY / GOOGLE_API_KEY
gpt-6-luna (alias luna) OpenAI Decisions API OPENAI_API_KEY

TRACE2RULES_DECISION_MODEL sets the default; --model overrides it.

# default: clef-flash
trace2rules label
trace2rules label --model jev
trace2rules label --model gemini-decision-1
trace2rules label --model gpt-6-luna
trace2rules patterns --min-confidence 0.4

Cloudflare models authenticate through wrangler auth token --json and wrangler whoami --json; the first account is used. Gemini and OpenAI use their standard keys. Labeling defaults to 270 requests/minute with 6 workers and retries 429/5xx responses.

label sends the tool name, action type, redacted normalized target, and a redacted raw command example to the selected provider. The local DuckDB and report output remain unredacted. Do not run external labeling or synthesis on private sessions without reviewing the redaction and provider policy.

Configuration

Variable Purpose
GEMINI_API_KEY Gemini synthesis provider
GOOGLE_API_KEY Alternate Gemini key
OPENAI_API_KEY OpenAI synthesis provider
TRACE2RULES_LLM_API_KEY API key for a custom OpenAI-compatible endpoint
TRACE2RULES_BASE_URL OpenAI-compatible base URL (including LiteLLM)
TRACE2RULES_MODEL Synthesis model, e.g. gemini-4-hydrogen
TRACE2RULES_DECISION_MODEL Labeling backend: clef-flash (default), clef, jev, gemini-decision-1, gpt-6-luna
HF_TOKEN Used by hf download for gated datasets; not read by trace2rules

TRACE2RULES_BASE_URL also works with an OpenAI-compatible LiteLLM proxy.

How it works

  1. Ingest normalizes tool calls into DuckDB (sessions, tool_events).
  2. Detectors find high-coverage setup failures, repeated exception signatures, read-only hotspots, and large output calls.
  3. Exact n-gram mining groups recurring 3–5-step tool sequences with lift and paired-rework evidence. Windows never cross a compaction boundary; nested sequences are deduplicated before selection.
  4. Decision labels (optional) classify normalized targets with clef/Jev/Gemini Decisions/Luna; synthesize uses them for category and filtering, and patterns uses them for intent-aware sequence mining.
  5. Synthesis is LLM-first. It selects gated findings and asks the configured model for structured rules; --offline forces deterministic rules.

Generated verifier scripts and low-support task-specific sequences are filtered before synthesis.

Data and privacy

  • Session data stays in your local DuckDB database.
  • --offline performs no LLM calls.
  • LLM synthesis sends mined findings, not the full raw session database. Findings can still contain commands, paths, and repository names; review before using an external provider.
  • label sends a normalized target plus a raw example to Cloudflare Workers AI; do not use it on sensitive private sessions without review.
  • data/ and generated AGENTS.*.proposed.md files are gitignored.

Known limits

  • Detectors are heuristics. Review every proposed rule.
  • Local-session formats change frequently. agent-trajectory is the compatibility layer; pin its version.
  • Decision-model labels are probabilistic; inspect low-confidence labels before relying on them.

Development

uv sync
uv run pytest
uv build

License

MIT. See LICENSE.

Metadata

Release files for trace2rules 0.1.2

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for trace2rules 0.1.2
File Size Uploaded Provenance Actions
trace2rules-0.1.2.tar.gz 45.6 kB With provenance Details for trace2rules-0.1.2.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for trace2rules 0.1.2
File Interpreter ABI Platform Actions
trace2rules-0.1.2-py3-none-any.whl Python 3 none any Details for trace2rules-0.1.2-py3-none-any.whl

Total release size: 97.8 kB

Release files / trace2rules-0.1.2.tar.gz

Download URL trace2rules-0.1.2.tar.gz
Size 45.6 kB
Tags Source
SHA-256 checksum
How to use checksums
f50559b1d899a87a83c69d6fdff203153c890c819939b202eb29365a2dc0aa00
BLAKE2b-256 checksum
How to use checksums
9b464abe9c84cf6cf0c64ab26caacb7e0700f347f950160a488a094e1b642c9f
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 16, 2026.

Transparency log

Release files / trace2rules-0.1.2-py3-none-any.whl

Download URL trace2rules-0.1.2-py3-none-any.whl
Size 52.2 kB
Tags Python 3
SHA-256 checksum
How to use checksums
abf6bfc3e11342385e1853669af1b104d2778221a204613895f652c9ace11fed
BLAKE2b-256 checksum
How to use checksums
60267858b6f7903988497ef27621ee7148ecc93b1c7be297c002403ebd2fe89e
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 16, 2026.

Transparency log

Security for trace2rules 0.1.2

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for trace2rules-0.1.2.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 16, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page