pi-autoresearch README

The project's README from github.com/davebcn87/pi-autoresearch. As one markdown file: README.md.

result

pi-autoresearch

Autonomous experiment loop for pi

Website · Documentation · Install · Usage · How it works

Try an idea, measure it, keep what works, discard what doesn't, repeat forever.

An extension for pi — an AI coding agent that runs in your terminal. pi-autoresearch gives pi the tools and workflow to run autonomous optimization loops: try an idea, benchmark it, keep improvements, revert regressions, repeat.

Inspired by karpathy/autoresearch. Works for any optimization target: test speed, bundle size, LLM training, build times, Lighthouse scores.


pi-autoresearch

Quick start

pi install npm:pi-autoresearch
pi

Or load the package for one session only with pi -e npm:pi-autoresearch.

Then start the loop inside pi:

/autoresearch optimize unit test runtime, monitor correctness

What's included

Extension Tools + live widget + /autoresearch dashboard
Skill Gathers what to optimize, writes session files, starts the loop

Extension tools

Tool Description
init_experiment One-time session config — name, metric, unit, direction
run_experiment Runs any command, times wall-clock duration, captures output
log_experiment Records result, auto-commits, updates widget and dashboard

/autoresearch command

Subcommand Description
/autoresearch Show help without activating autoresearch mode.
/autoresearch <text> Enter autoresearch mode. If .auto/prompt.md exists, resumes the loop with <text> as context. Otherwise, sets up a new session.
/autoresearch off Leave autoresearch mode. Stops auto-resume and clears runtime state but keeps .auto/log.jsonl intact.
/autoresearch clear Delete .auto/log.jsonl, reset all state, and turn autoresearch mode off. Use this for a clean start.
/autoresearch export Open a live dashboard in your browser. Auto-updates as experiments run.
/autoresearch dashboard Open the fullscreen scrollable dashboard overlay in the terminal. Navigate with ↑/↓/j/k, PageUp/PageDown/u/d, g/G for top/bottom, Escape or q to close.

Examples:

/autoresearch optimize unit test runtime, monitor correctness
/autoresearch model training, run 5 minutes of train.py and note the loss ratio as optimization target
/autoresearch export
/autoresearch dashboard
/autoresearch off
/autoresearch clear

Keyboard shortcuts (opt-in)

No shortcuts are bound by default — pi's built-in keymap grows with every release, so any default chord eventually collides with it (this happened with ctrl+shift+f vs. pi's transcript search). Every action is available as a /autoresearch subcommand instead.

To opt in, add chords to <agent-dir>/extensions/pi-autoresearch.json (<agent-dir> is usually ~/.pi/agent, or PI_CODING_AGENT_DIR when set). Omitted or null keys stay unbound:

{
  "shortcuts": {
    "fullscreenDashboard": "ctrl+shift+y",
    "export": "alt+shift+e",
    "off": null
  }
}

Each key binds its /autoresearch subcommand: fullscreenDashboard → dashboard, export → export, off → off.

Pick a chord that's free in pi's built-in keybindings and your <agent-dir>/keybindings.json — extension shortcuts win conflicts, so a clashing chord hijacks the built-in action.

Picking a free chord (guidance for agents)

Don't guess a chord — check it against the installed pi's built-in keymap first:

PI_ROOT=$(ls -d ~/.pi/pkg/pi-* 2>/dev/null | sort -V | tail -1)
[ -n "$PI_ROOT" ] || PI_ROOT="$(npm root -g)/@earendil-works/pi-coding-agent"
node --input-type=module -e '
const { KEYBINDINGS } = await import(process.argv[1] + "/dist/core/keybindings.js");
const taken = new Set(Object.values(KEYBINDINGS).flatMap(({ defaultKeys }) => defaultKeys).map((key) => key.toLowerCase()));
console.log(taken.has(process.argv[2].toLowerCase()) ? "TAKEN" : "FREE");
' "$PI_ROOT" ctrl+shift+y

Chords in <agent-dir>/keybindings.json values are also taken. Write a verified-free chord into <agent-dir>/extensions/pi-autoresearch.json, then /reload pi and confirm no Extension shortcut conflict warning appears.

ctrl+shift+y, ctrl+shift+u, alt+shift+f, and ctrl+alt+d are free as of pi 0.84.x. Always re-verify — pi's keymap grows over time, which is why this extension binds nothing by default.

UI

Skills

autoresearch-create asks a few questions (or infers from context) about your goal, command, metric, and files in scope — then writes two files and starts the loop immediately:

autoresearch-finalize turns a noisy autoresearch branch into clean, independent branches — one per logical change, each starting from the merge-base. Groups must not share files, so each branch can be reviewed and merged independently.

autoresearch-hooks (optional) helps author .auto/hooks/before.sh and .auto/hooks/after.sh for a session. It ships with ten reference scripts in skills/autoresearch-hooks/examples/ (external search, learnings journal, native notifications, anti-thrash, idea rotation, and more) — the skill handles the contract, you pick the inspiration. The core autoresearch loop has no hook awareness.

All session files live in a single .auto/ subfolder at the working-directory root — one folder to preserve across reverts, gitignore, and clean up. (Legacy flat autoresearch.* files are still read for in-flight sessions.)

File Purpose
.auto/prompt.md Session document — objective, metrics, files in scope, what's been tried. A fresh agent can resume from this alone.
.auto/measure.sh Benchmark script — pre-checks, runs the workload, outputs METRIC name=number lines.
.auto/log.jsonl Append-only log of every run (written by the tools).
.auto/checks.sh (optional) Backpressure checks — tests, types, lint. Runs after each passing benchmark. Failures block keep.
.auto/hooks/ (optional) Executable scripts (before.sh, after.sh) that fire around iterations. Stdout is delivered to the agent as a steer message.

Install

pi install npm:pi-autoresearch
Manual install
cp -r extensions/pi-autoresearch ~/.pi/agent/extensions/
cp -r skills/autoresearch-create ~/.pi/agent/skills/

Then /reload in pi.


Usage

1. Start autoresearch

/autoresearch optimize unit test runtime, monitor correctness

This activates autoresearch mode and makes the experiment tools available. If .auto/prompt.md does not exist, it also loads the autoresearch-create skill. Calling /skill:autoresearch-create directly does not activate the mode, so the tools remain unavailable in a fresh session.

The agent asks about your goal, command, metric, and files in scope — or infers them from context. It then creates a branch, writes .auto/prompt.md and .auto/measure.sh, runs the baseline, and starts looping immediately.

2. The loop

The agent runs autonomously: edit → commit → run_experiment → log_experiment → keep or revert → repeat. It never stops unless interrupted.

Every result is appended to .auto/log.jsonl in your project — one line per run. This means:

3. Finalize into reviewable branches

/skill:autoresearch-finalize

The agent reads .auto/log.jsonl, groups kept experiments into logical changesets, proposes the grouping for your approval, then creates independent branches from the merge-base. Each commit includes metric improvements in the message. Groups must not share files, so branches can be reviewed and merged independently.

4. Monitor progress


Example domains

Domain Metric Command
Test speed seconds ↓ pnpm test
Bundle size KB ↓ pnpm build && du -sb dist
LLM training val_bpb ↓ uv run train.py
Build speed seconds ↓ pnpm build
Lighthouse perf score ↑ lighthouse http://localhost:3000 --output=json

How it works

The extension is domain-agnostic infrastructure. The skill encodes domain knowledge. This separation means one extension serves unlimited domains.

┌──────────────────────┐     ┌──────────────────────────┐
│  Extension (global)  │     │  Skill (per-domain)       │
│                      │     │                           │
│  run_experiment      │◄────│  command: pnpm test       │
│  log_experiment      │     │  metric: seconds (lower)  │
│  widget + dashboard  │     │  scope: vitest configs    │
│                      │     │  ideas: pool, parallel…   │
└──────────────────────┘     └──────────────────────────┘

Two files keep the session alive across restarts and context resets:

.auto/log.jsonl   — append-only log of every run (metric, status, commit, description)
.auto/prompt.md   — living document: objective, what's been tried, dead ends, key wins

A fresh agent with no memory can read these two files and continue exactly where the previous session left off.


Configuration (optional)

Create .auto/config.json in your pi session directory to customize behavior:

{
  "workingDir": "/path/to/project",
  "maxIterations": 50
}
Field Type Description
workingDir string Override the directory for all autoresearch operations — file I/O, command execution, and git. Supports absolute or relative paths (resolved against the pi session cwd). The config file itself always stays under the session cwd. Fails if the directory doesn't exist.
maxIterations number Maximum experiments before auto-stopping. The agent is told to stop and won't run more experiments until a new segment is initialized.

Long-running loops and context

The loop is designed to run unattended across context limits. When pi's auto-compaction summarizes the older portion of the conversation, autoresearch detects the resulting idle and re-prompts the agent to re-read .auto/prompt.md, the tail of .auto/log.jsonl, .auto/ideas.md, and git log before continuing. All progress is persisted in those files, so the post-summary turn rehydrates from the source of truth instead of relying on whatever survived compaction. No tuning required — if pi's auto-compaction is enabled (the default), this just works.


Confidence scoring

After 3+ experiments in a session, pi-autoresearch computes a confidence score — how the best improvement compares to the session's noise floor. This helps distinguish real gains from benchmark jitter, especially on noisy signals like ML training, Lighthouse scores, or flaky benchmarks.

How it works:

Confidence Color Meaning
≥ 2.0× 🟢 green Improvement is likely real
1.0–2.0× 🟡 yellow Above noise but marginal
< 1.0× 🔴 red Within noise — consider re-running to confirm

Backpressure checks (optional)

Create .auto/checks.sh to run correctness checks (tests, types, lint) after every passing benchmark. This ensures optimizations don't break things.

#!/bin/bash
set -euo pipefail
pnpm test --run
pnpm typecheck

How it works:


Hooks (optional)

Drop executable scripts in .auto/hooks/ to run code at iteration boundaries. Hooks are transparent to the agent — the agent calls tools and sees results; hooks run alongside without any agent-facing surface.

Contract:

before.sh stdin (on fresh activation last_run is null):

{
  "event": "before",
  "cwd": "/path/to/workdir",
  "next_run": 6,
  "last_run": {
    "run": 5, "status": "discard", "metric": 42.1,
    "description": "…",
    "asi": { "hypothesis": "…", "next_focus": "…" }
  },
  "session": {
    "metric_name": "total_ms", "metric_unit": "ms", "direction": "lower",
    "baseline_metric": 40.7, "best_metric": 33.5,
    "run_count": 5, "goal": "optimize sort speed"
  }
}

after.sh stdin:

{
  "event": "after",
  "cwd": "/path/to/workdir",
  "run_entry": {
    "run": 6, "status": "discard", "metric": 38.9,
    "description": "…",
    "asi": { "hypothesis": "…", "learned": "…" }
  },
  "session": { "metric_name": "total_ms", "direction": "lower", "baseline_metric": 40.7, "best_metric": 33.5, "run_count": 6, "goal": "…" }
}

Agent signal. The agent writes description and asi.* fields in its log_experiment calls for its own future-self reasoning. The hook opportunistically mines whichever fields the agent naturally uses — asi.hypothesis, asi.next_focus, description, etc. There is no dedicated "hook input" field; the agent is unaware the hook exists.

Examples. Reference scripts for both stages live at skills/autoresearch-hooks/examples/ — external search, qmd document search, persistent learnings, native notifications, git tagging, anti-thrash, idea rotator, hypothesis reflection, context rotation. Copy one to your session's .auto/hooks/ directory, adapt, chmod +x.


Prerequisites

  1. Install pi — follow the instructions at pi.dev
  2. An API key for your preferred LLM provider (configured in pi)

Security and trust

Pi packages run with your full user permissions. Review this repository before installing it, and run autoresearch in a dedicated branch or worktree with a clean working tree.

Autoresearch intentionally edits files, creates and reverts commits, and executes the commands in .auto/measure.sh, .auto/checks.sh, and .auto/hooks/. Treat those files as executable code: review them before each session, keep credentials and sensitive files out of scope, and use a sandbox or restricted environment for untrusted projects.

For reproducible installs, pin a version you have reviewed, for example pi install npm:[email protected]. Published npm releases include provenance attestations.

Controlling costs

Autoresearch loops run autonomously and can burn through tokens. Two ways to cap spend:

License

MIT

pi-autoresearch (davebcn87/pi-autoresearch)

Searching Database…

Что это такое?pi-autoresearch — это расширение для pi, терминального ИИ-агента для написания кода, которое запускает автономные циклы оптимизации: пробует изменение в коде, замеряет его производительность, оставляет изменение, если оно улучшает результат, откатывает, если нет, и повторяет это без остановки.
Это самостоятельное приложение или для работы нужен pi?Это пакет расширения для pi (ИИ-агента для написания кода, который работает в терминале): он добавляет инструменты, навык и команду /autoresearch и работает только внутри сессии pi.
Как запустить цикл autoresearch?Загрузите расширение на одну сессию командой 'pi -e npm:pi-autoresearch' или установите его постоянно и перезапустите pi, затем выполните /autoresearch внутри сессии. Агент спросит о вашей цели, команде, метрике и файлах, которые входят в область работы (или определит их сам), создаст ветку и сразу начнёт цикл.
Что нужно подготовить перед использованием?Нужно установить сам pi (с сайта pi.dev) и настроить в pi API-ключ для выбранного вами провайдера больших языковых моделей.
Можно ли просто отпустить это на мою кодовую базу?Не стоит делать это без осторожности: агент редактирует файлы, создаёт и откатывает коммиты и запускает произвольный код из .auto/measure.sh и хуков с вашими полными правами пользователя, поэтому сначала проверьте репозиторий и запускайте его в отдельной ветке или в чистом рабочем дереве.
Кто будет этим пользоваться и для какой оптимизации?Разработчики, которым нужна ненаблюдаемая настройка любой измеряемой цели: в README в качестве примеров перечислены скорость тестов, размер сборки, функция потерь при обучении LLM, время сборки и оценки Lighthouse. Каждой из них нужна только команда оболочки и метрика.
Как оно не даёт сжечь токены в бесконечном цикле?Можно ограничить число экспериментов за сессию параметром maxIterations в .auto/config.json, а также отдельно задать лимиты расходов по ключу или на месяц у вашего провайдера LLM, так как автономные циклы работают без присмотра и могут потратить много токенов.
Что означает показатель уверенности на дашборде?После 3+ запусков он сравнивает лучшее улучшение с уровнем шума сессии, используя медианное абсолютное отклонение (MAD). Значение 2.0x и выше (зелёный) означает, что прирост, скорее всего, настоящий, а 1.0–2.0x (жёлтый) — что он выше шума, но незначителен. Показатель носит только рекомендательный характер: решение о том, оставить изменение или отбросить, всё равно принимает агент.
Когда цикл завершится, как превратить результаты во что-то, что можно слить?Агент читает полную историю .auto/log.jsonl, группирует сохранённые эксперименты в непересекающиеся наборы изменений, предлагает такую группировку на ваше одобрение, а затем создаёт независимые ветки (каждая с коммитами, описывающими улучшение метрики) от merge-base, чтобы их можно было проверить и слить по отдельности.
Сохранится ли сессия, если терминал упадёт или контекст pi будет сжат?Да: каждый результат добавляется в .auto/log.jsonl, а план хранится в .auto/prompt.md, поэтому новый агент (после перезапуска или сброса из-за сжатия контекста) может перечитать оба файла и продолжить ровно с того места, где остановилась предыдущая сессия.
Creator
davebcn87
Size
2.2 MB
Stars
8.2K
Age
7mo
Commits · 90 Days