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 the gated findings for each repo to an OpenAI-compatible chat model and asks for structured rules.
Provider selection:
TRACE2RULES_LLM_API_KEY— API key for a custom OpenAI-compatible endpoint.GEMINI_API_KEYorGOOGLE_API_KEY— Gemini OpenAI-compatible endpoint.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. This example uses OMP; point --source at Claude Code, Codex, or Pi instead if that is what you use.
uv tool install trace2rules
trace2rules ingest --source ~ --limit 50
trace2rules mine
trace2rules synthesize
--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 |
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 --repo owner/name --out AGENTS.proposed.md
trace2rules synthesize --repo owner/name --out -
trace2rules synthesize --out-dir ./proposals
--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, otherobject_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, normalized target, and a raw command example to the selected provider. Do not run it on private sessions without review.
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
- Ingest normalizes tool calls into DuckDB (
sessions,tool_events). - Detectors find high-coverage setup failures, repeated exception signatures, read-only hotspots, and large output calls.
- 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.
- Decision labels (optional) classify normalized targets with clef/Jev/Gemini Decisions/Luna;
synthesizeuses them for category and filtering, andpatternsuses them for intent-aware sequence mining. - Synthesis is LLM-first. It selects gated findings and asks the configured model for structured rules;
--offlineforces 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.
--offlineperforms 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.
labelsends a normalized target plus a raw example to Cloudflare Workers AI; do not use it on sensitive private sessions without review.data/and generatedAGENTS.*.proposed.mdfiles are gitignored.
Known limits
- Detectors are heuristics. Review every proposed rule.
- Local-session formats change frequently.
agent-trajectoryis 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.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| trace2rules-0.1.0.tar.gz | 41.6 kB | With provenance | Details for trace2rules-0.1.0.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| trace2rules-0.1.0-py3-none-any.whl | Python 3 | none | any | Details for trace2rules-0.1.0-py3-none-any.whl |
Total release size: 89.7 kB
Release files / trace2rules-0.1.0.tar.gz
| Download URL | trace2rules-0.1.0.tar.gz |
|---|---|
| Size | 41.6 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
ef4eaac1645bc5df8268cdb05398b898f47aa94115fca476b7b9ef903021166c
|
|
BLAKE2b-256 checksum How to use checksums |
eef744a5a7de3bb6cd6eda508e9acc7394842e0fbd8b668b20dafc3c9e0e9d96
|
| 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 logRelease files / trace2rules-0.1.0-py3-none-any.whl
| Download URL | trace2rules-0.1.0-py3-none-any.whl |
|---|---|
| Size | 48.0 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
1e4e7ac0920183008d75ad2f6354e20406ba4d131ea9a94e17e828edabdf2fc8
|
|
BLAKE2b-256 checksum How to use checksums |
74060a3cf846bd80a07c3fe44703a3390b7890f7f65c9fe206f5b8ed661e70bd
|
| 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 logSecurity for trace2rules 0.1.0
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.
Attestation for trace2rules-0.1.0.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 logA 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.