Metadata-Version: 2.4
Name: trace2rules
Version: 0.1.1
Summary: Mine coding-agent trajectories into evidence-backed AGENTS.md rules
Keywords: agents,coding-agents,agents.md,trajectories,duckdb
Author: Rakha Kanz Kautsar
Author-email: Rakha Kanz Kautsar <rkkautsar@gmail.com>
License-Expression: MIT
License-File: LICENSE
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Software Development :: Quality Assurance
Requires-Dist: duckdb>=2.0.0
Requires-Dist: openai>=3.51.0
Requires-Dist: pydantic>=2.14.3
Requires-Dist: python-dotenv>=1.2.4
Requires-Dist: rich>=15.0.0
Requires-Dist: scikit-learn>=1.9.1
Requires-Dist: typer>=0.29.1
Requires-Dist: agent-trajectory>=0.4.4
Requires-Python: >=3.12
Project-URL: Homepage, https://github.com/rkkautsar/trace2rules
Project-URL: Repository, https://github.com/rkkautsar/trace2rules
Project-URL: Issues, https://github.com/rkkautsar/trace2rules/issues
Description-Content-Type: text/markdown

# 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](https://github.com/pdm-project/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:

```bash
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):

```markdown
# 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:

```bash
uv tool install trace2rules
# or
pip install trace2rules
```

For development from a clone:

```bash
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.

```bash
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.

```bash
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](https://huggingface.co/datasets/SALT-NLP/SWE-chat), then download the two tables:

```bash
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

```bash
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:

```bash
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:

```bash
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:

```bash
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.

```bash
# 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

```bash
uv sync
uv run pytest
uv build
```

## License

MIT. See `LICENSE`.
