pi-autoresearch README

项目的 README,来自 github.com/davebcn87/pi-autoresearch。合并为一个 markdown 文件: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 benchmark + checks, parses METRIC/TIMING, decides keep/discard/crash/checks_failed, auto-commits/reverts code, persists .auto/ in git, and updates dashboards

/autoresearch command

Subcommand Description
/autoresearch or /autoresearch help Show help without activating autoresearch mode. --help and -h work too.
/autoresearch <text> Enter autoresearch mode. If .auto/prompt.md exists, resumes the loop with <text> as context. Otherwise, sets up a new session.
/autoresearch pause Pause the loop, keeping history and showing autoresearch paused in the bar. Aborts an in-progress run.
/autoresearch resume Resume a paused session without resetting its baseline or history.
/autoresearch off Legacy alias: pauses rather than turning off when .auto/prompt.md exists.
/autoresearch finalize Stop the loop (including a paused loop), then load the finalize skill when experiments exist. A recorded finalization stays stopped even if the playbook remains.
/autoresearch clear Delete .auto/log.jsonl and reset results; remains visibly paused when the playbook exists.
/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.

Subcommands autocomplete: type /autoresearch and pick one from the list, or start typing (/autoresearch fi → finalize).

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 pause
/autoresearch resume
/autoresearch finalize
/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 also activates the mode before skill expansion. An existing .auto/prompt.md or experiment log activates a same-directory session, including when those files are created during an already-running session. An explicit pause remains visibly paused across reloads; finalize or deleting .auto/ stops the session. Redirected working directories still require this session to opt in.

The agent infers the goal and metric and calls init_experiment immediately, before implementation, optimization, or lengthy exploration. It then creates a branch, writes the playbook and benchmark/check scripts, and runs every attempt through run_experiment. Crashes and failed correctness checks are logged and auto-reverted (never establishing the baseline); passing commands that omit the required METRIC <primary>=<number> line report a format error without logging or touching git. The first successful run establishes the baseline; optimization continues from there.

2. The loop

The agent runs autonomously: edit → run_experiment (which runs, checks, decides, commits/reverts code, and commits .auto/ learnings) → repeat. Continuation uses Pi’s native { continue: true } boundary, not timers or injected “continue” messages.

Esc means pause. Aborting an active run—including during a continuation boundary or retry backoff—leaves autoresearch paused visible and persisted across reloads. It never queues an automatic restart. Resume explicitly with /autoresearch resume (or /autoresearch <context>). Closing the dashboard with Esc only closes that UI; it does not abort the agent.

LLM errors use Pi’s native recovery. Pi handles transient-error retries/backoff, context-overflow recovery and automatic compaction before autoresearch decides whether another iteration is needed. If recovery is exhausted or the error is not recoverable, autoresearch pauses instead of sending a fresh prompt to restart the retry budget. Configure retries through Pi’s retry settings, not .auto/config.json. A manual /compact also leaves the loop paused rather than launching a model request from a notification.

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

3. Finalize into reviewable branches

/autoresearch finalize

This stops the loop (aborting a run in progress) and loads the autoresearch-finalize skill. Loading the skill directly with /skill:autoresearch-finalize leaves autoresearch mode on, so a running loop keeps going.

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.

Loop timing (optional instrumentation)

Every executed run_experiment emits an automatic timing pair, even without script changes:

TIMING start run_experiment 1795811000000
TIMING end run_experiment 1795811032000

To break the command down further, optionally emit TIMING start <name> and TIMING end <name> lines from .auto/measure.sh:

printf 'TIMING start build\n'
pnpm build
printf 'TIMING end build\n'
printf 'TIMING start benchmark\n'
pnpm bench
printf 'TIMING end benchmark\n'

An optional third field is an absolute Unix timestamp in milliseconds, e.g. TIMING start build "$(date +%s%3N)" (emit it with printf/echo). Without it, timing uses receipt time as output streams in; flush buffered output or provide timestamps for precision. Names allow letters, digits, _, ., :, /, and - (up to 80 characters). Nested and repeated spans work. run_experiment, checks, and agent/other are reserved. Invalid/unmatched/unclosed spans are ignored with an advisory note, never treated as benchmark failures. Markers are parsed before output truncation, on both stdout and stderr. Custom spans are optional and currently collected from the benchmark command, not the separately buffered correctness-check output.

Timing is automatically attached to each logged run under timing in .auto/log.jsonl:

The terminal widget, log results, fullscreen dashboard, exported live dashboard, and compaction summary expose timing in compact form, for example:

Loop 7m 2s · run 32s · checks 10s · longest: agent/other 6m 20s

After reinitializing a baseline, Progress keeps the current-segment delta and appends a dimmed lifetime comparison, e.g. (+25.7%) (+321.0% from first baseline). Only successful baselines with matching metric name, unit, and direction are compared. Workload changes can still affect comparability; this is historical context, not proof of equivalent workloads.

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       │
│  (auto-commit/log)   │     │  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.
compactEvery number Optional periodic deterministic compaction cadence: every N logged experiments, emit a lossless persisted-state compaction boundary (firstKeptEntryId: null) so each window starts with fresh context.
compactAtPercent number | false Context-window percentage ceiling for deterministic compaction between experiments (default 70). Set 0 or false to disable.
compactAtTokens number | false Optional absolute token ceiling override instead of compactAtPercent. Set 0 or false to disable automatic compaction.

Long-running loops and context

The loop is designed to run unattended across context limits. When pi compacts the conversation (or when optional compactEvery triggers a periodic reset), autoresearch replaces the LLM compaction call with a deterministic summary built directly from .auto/prompt.md, .auto/ideas.md, and the tail of .auto/log.jsonl, then continues cleanly via pi's agent_before_settle boundary. 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, hypothesis, prev_learning, and asi.* fields in its run_experiment calls for its own future-self reasoning. The hook opportunistically mines whichever fields the agent naturally uses — asi.hypothesis, asi.learning, 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:

Development

pnpm install
pnpm test     # unit tests, including the check of the loop against its model
pnpm model    # TLC checks the loop's TLA+ model and saves the table the tests use (Java 11+)

The loop's lifecycle is one pure function in extensions/pi-autoresearch/loop.ts, modelled in formal/. formal/README.md explains how the two are kept together and how to change the loop.

License

MIT

pi-autoresearch (davebcn87/pi-autoresearch)

正在搜索数据库…

这是什么?pi-autoresearch 是 pi 的一个扩展。pi 是一款在终端中运行的 AI 编程智能体,该扩展可运行自主优化循环:尝试修改代码、进行基准测试,若结果有提升则保留修改,否则撤销,并无限重复。
这是独立应用,还是需要 pi 才能运行?它是 pi(一款在终端中运行的 AI 编程智能体)的扩展包,会添加工具、一项技能和一个 /autoresearch 命令,并且只能在 pi 会话中使用。
我该如何启动一个 autoresearch 循环?使用 'pi -e npm:pi-autoresearch' 为单次会话加载,或永久安装后重新加载 pi,然后在会话中运行 /autoresearch;智能体会询问你的目标、命令、指标和涉及的文件范围(也可自行推断),创建分支,并立即开始循环。
使用前我需要准备什么?你需要先安装 pi 本体(可从 pi.dev 获取),并在 pi 中配置你偏好的大模型服务商的 API 密钥。
直接让它在我的代码库上自动运行安全吗?需要谨慎对待。智能体会编辑文件、创建和撤销提交,并以你的完整用户权限运行 .auto/measure.sh 和钩子中的任意代码,因此请先审查代码仓库,并在专用分支或干净的工作树上运行。
谁会用它?用于哪类优化?需要对任意可量化目标进行无人值守调优的开发者。README 列举的示例领域包括测试速度、包体积、大模型训练损失、构建时间和 Lighthouse 分数,每个领域只需提供一条 shell 命令和一个指标。
如何防止它在无尽循环中耗尽 token?你可以在 .auto/config.json 中通过 maxIterations 限制每次会话的实验次数,同时还可以在大模型服务商处为每个密钥或按月设置预算上限,因为自主循环无人值守运行,可能消耗大量 token。
仪表盘中显示的置信度分数是什么?运行 3 次以上后,它会使用中位数绝对偏差(MAD),将最佳提升幅度与本次会话的噪声基线进行比较。分数达到 2.0x 或以上(绿色)表示提升很可能是真实的;1.0-2.0x(黄色)表示高于噪声但幅度较小。该分数仅供参考,智能体仍会决定保留还是丢弃某项修改。
循环结束后,如何把结果整理成可以合并的内容?智能体会读取完整的 .auto/log.jsonl 历史记录,将保留的实验分组为互不重叠的变更集,并提交分组方案供你确认;随后基于 merge-base 创建相互独立的分支(每个分支都包含记录指标提升的提交),以便分别审查和合并。
如果我的终端崩溃了,或者 pi 的上下文被压缩,会话还能保留吗?可以。每条结果都会追加到 .auto/log.jsonl,计划保存在 .auto/prompt.md 中,因此新的智能体(无论是在重启后还是上下文压缩重置后)都可以重新读取这两个文件,并从上一次会话停止的地方准确继续。
作者
davebcn87
大小
2.2 MB
星标
8.3K
时长
8个月
提交 · 90 天