Personal fork of pi-autoresearch
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, repeat. Git keeps improvements and reverts regressions; native jj retains every attempted implementation and supports Pareto trade-offs.

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 Configure a scalar Git session or approved native jj workspace, objectives and evaluation version
run_experiment Runs the benchmark, times wall-clock duration, captures output and checks
log_experiment Records results; Git auto-commits/reverts, jj retains immutable snapshots with saved runtime measurements
manage_experiment Native jj: list/select/pin/unpin/recover/promote candidates (active mode only)

/autoresearch command #

Subcommand Description
/autoresearch or /autoresearch help Show help without activating autoresearch mode. --help and -h work too.
/autoresearch <text> Enter mode and resume from the resolved session playbook, or set up a new session.
/autoresearch off Stop auto-resume and turn tools off; preserve history and native pending checkpoints.
/autoresearch finalize [<full-candidate-id> <new-bookmark>] jj: stop/settle the loop and promote one saved candidate to a new bookmark, even with tools off. Bare interactive use asks for candidate/bookmark approval; headless use requires explicit arguments. Git: bare finalize loads the branch-grouping skill.
/autoresearch clear Turn mode off and delete the active log. jj requires confirmation (or clear --confirm), warns with retained/frontier/pin counts, and refuses pending work; keeps tags and source files.
/autoresearch export Open the live browser dashboard for Git sessions. Native jj uses the terminal dashboard; the legacy browser cannot safely represent versioned evaluations.
/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 off
/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 #

  • Dashboard widget — results above the editor. Native jj shows raw objectives, outcomes, frontier membership, pins and selected parent separately.
  • Confidence score (Git scalar) — after 3+ runs, compares the best improvement to the session noise floor. ≥2.0× (green) = likely real, 1.0–2.0× (yellow) = marginal, <1.0× (red) = within noise. No aggregate Pareto winner or confidence claim.
  • Fullscreen overlay — /autoresearch dashboard opens a scrollable terminal dashboard with a live run spinner; native history remains inspectable while the loop is off.

Skills #

autoresearch-create agrees the goal, benchmark, objectives and scope. In jj it first obtains workspace/provisioning approval and initializes stable session paths; in Git it creates a branch and scalar playbook, then starts the loop.

autoresearch-finalize proposes one saved implementation for jj promotion, preserving all alternatives. In Git only, it groups kept experiments into independent review branches from the merge-base; groups must not share files.

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.

Git session files live in .auto/ at the working-directory root (legacy flat autoresearch.* inputs remain readable). Native jj uses the same filenames under <research workspace root>/.jj/autoresearch/.auto/, outside candidate trees. Existing root/legacy files are copied once and left untouched. Use the exact paths returned by init_experiment, not stale root .auto/ files. The table below shows Git paths.

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. New sessions load autoresearch-create; existing sessions resume from the resolved playbook. Calling /skill:autoresearch-create directly does not activate the mode, so tools remain unavailable in a fresh session.

The agent asks about the goal, benchmark, metrics, and scope. A .jj directory anywhere above the execution directory selects native jj, including colocated repositories and scalar sessions. Otherwise it creates a Git branch and .auto/ playbook, runs the baseline, and starts looping.

Native jj and Pareto exploration #

Use jj 0.46+, the tested baseline. Setup proposes a dedicated workspace outside the source workspace and obtains approval; ignored dependencies/data are not copied. Using the current workspace instead requires explicit approval. Original source files stay unchanged in dedicated mode, apart from VCS metadata. Run concurrent loops from distinct jj workspaces: each origin workspace has one research binding.

Initialization returns the actual research directory, stable session/evaluator/config paths and exact shell-safe benchmark command. Relative built-in file/search/Bash tools follow that research directory while active; accidental absolute original-source writes are blocked. This is not an OS sandbox. Use the returned controller configPath for limits/workspace binding; jj origins store it in metadata instead of altering tracked root .auto/config.json.

For example:

/autoresearch optimize answer quality and latency; quality higher, latency_ms lower;
use quality resolution 0.001 and latency resolution 1 ms; propose a dedicated jj workspace

A quality 0.90 / latency 800 ms implementation and a quality 0.87 / latency 450 ms implementation can both belong to the observed frontier: neither dominates the other. Pin a preferred alternative with a human note, even if dominated. Select any saved candidate as the next parent with a rationale before editing; retention, outcome, frontier, pin and parent are separate.

Every attempted snapshot, including failures and dominated results, is retained with full immutable commit identity and native tags. Candidate-defining source must be tracked: custom auto-track restrictions cannot silently omit new source. Explicitly track intended files or ignore out-of-scope artifacts before measuring. Equal-score implementations stay distinct. The benchmark owns repeat aggregation and dataset/remote-model provenance; candidate-defining prompts/config belong in versioned source. Changed evaluator/provenance/command requires a new evaluation version and consent on which candidates to re-evaluate, not an automatic archive-wide rerun. Precision/direction-only changes reuse raw scores without resetting the per-version budget.

See native configuration and candidate controls for initialization parameters, rounding rules, storage and recovery; design rationale records the agreed model.

2. The loop #

Git: edit → run_experiment → log_experiment (auto-commit or revert) → repeat. Native jj: select a saved parent → edit → run_experiment (snapshot + measure) → log_experiment (retain + record) → repeat. jj logging uses saved runtime measurements/identity, ignoring caller-supplied overrides. Pending checkpoints survive restart: use manage_experiment recover, then log the saved crash, rather than automatically repeating a paid run. Confirm a stale lock's process has stopped before explicitly removing it.

The loop continues until interrupted, paused for approval/recovery, or its budget is reached. Results append to the resolved log.jsonl. This means:

  • Survives restarts — the agent can resume a session by reading the file
  • Survives context resets — the resolved prompt.md captures what's been tried
  • Human readable — open the stable log anytime for full history beyond bounded candidate summaries
  • Stable ownership — Git uses the working directory's .auto/; jj uses workspace-local metadata unaffected by candidate navigation

3. Finalize a chosen candidate or review branches #

/autoresearch finalize

Native jj: stops/settles the loop, offers candidate choice, new bookmark input and approval. In headless use, supply the full evaluation UUID and new bookmark explicitly:

/autoresearch finalize <full-candidate-id> <new-bookmark>

This works even with mode/tools off. It creates a bookmark at the exact saved immutable snapshot, never overwrites an existing bookmark, combines alternatives, or rewrites measured code. All alternatives and checkpoints remain preserved. Native off/finalization also remains stopped in a fresh Pi session; explicitly use /autoresearch <text> to resume. Later content-changing cleanup requires new evaluation.

Git only: bare finalize stops the loop and loads the finalization skill, which groups kept experiments, asks for approval, then creates independent branches from the merge-base. Groups must not share files. Direct /skill:autoresearch-finalize does not itself stop the loop; the skill selects the native or Git workflow before any VCS operation.

4. Monitor progress #

  • Widget — full results table, always visible above the editor
  • /autoresearch dashboard — fullscreen scrollable dashboard overlay (optional chord: shortcuts.fullscreenDashboard)
  • /autoresearch export — Git browser dashboard with chart and share card; native jj uses the terminal table
  • Escape — interrupt anytime and ask for a summary

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 (Git paths shown; jj uses the stable metadata session directory):

.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) #

For Git, create .auto/config.json in your Pi origin directory to customize behavior. With a jj origin, the controller configPath returned by initialization lives under that workspace's .jj/autoresearch/.auto/; workingDir points to the approved research directory. Non-jj origins retain their explicit .auto/config.json controller, which an approved new redirection updates. Use the returned path; explicit controller edits are allowed while native mode is active. Malformed ownership/budget configuration stops the loop instead of falling back to the original directory.

{
  "workingDir": "/path/to/project",
  "maxIterations": 50
}
Field Type Description
workingDir string Override the execution directory for file I/O, commands and VCS. Absolute or relative to the Pi origin cwd; must exist. Controller config stays under the origin directory.
maxIterations number Positive safe integer: maximum logged experiments per Git segment or native evaluation version. Omit for unlimited. Native precision/direction-only edits do not reset the count.

Long-running loops and context #

The loop is designed to run across context limits. On pi's auto-compaction, the extension builds a deterministic summary from the resolved playbook, log and ideas. Native jj includes the evaluation version, strategy, frontier, pins and selected parent, even when important alternatives are older than recent runs. Read the archive for more detail; pending work must be logged/recovered before continuing.


Confidence scoring (Git scalar) #

Pareto membership uses reported objective values, not this confidence estimator.

After 3+ experiments in a Git 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:

  • Uses Median Absolute Deviation (MAD) of all metric values in the current segment as a robust noise estimator.
  • Confidence = |best_improvement| / MAD. A score of 2.0× means the best improvement is twice the noise floor.
  • Shown in the widget, fullscreen dashboard, and log_experiment output.
  • Persisted to .auto/log.jsonl on each result for post-hoc analysis.
  • Advisory only — never auto-discards. The agent is guided to re-run experiments when confidence is low, but the final keep/discard decision stays with the agent.
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 for Git, or the returned checksPath for native jj, to run correctness checks (tests, types, lint) after every passing benchmark.

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

How it works:

  • If the file doesn't exist, everything behaves exactly as before — no changes to the loop.
  • If it exists, it runs automatically after every benchmark that exits 0.
  • Checks execution time does not affect the primary metric.
  • If checks fail, log checks_failed: Git reverts changes; jj retains the failed snapshot, which cannot enter the frontier.
  • The checks_failed status is shown separately in the dashboard so you can distinguish correctness failures from benchmark crashes.
  • Checks have a separate timeout (default 300s, configurable via checks_timeout_seconds in run_experiment).

Hooks (optional) #

Drop executable scripts in the resolved session hooks/ directory to run code at iteration boundaries. The following paths and scalar payload examples describe Git's unchanged contract. In native jj, before.sh fires at the actual benchmark boundary after parent selection, before snapshotting; after.sh fires after durable evaluation logging. There is no extra native activation/log-next before hook. Multiobjective native session uses version:2, mode:"pareto" and archive fields instead of scalar best/baseline metrics; single-objective sessions retain the scalar payload shape; see the detailed hook contract.

  • .auto/hooks/before.sh — fires before every iteration (at /autoresearch activation and at the end of every log_experiment, after after.sh). Use for prospective work: fetch research, prime context for the next attempt.
  • .auto/hooks/after.sh — fires at the end of every log_experiment. Use for retrospective work: annotate learnings, send notifications.

Contract:

  • Must be executable (chmod +x). Preserved on revert — the entire .auto/ folder survives (as do legacy autoresearch.* artefacts).
  • Stdin — a JSON object on a single line. Shape depends on the stage (see below). Extract fields with jq.
  • Stdout is delivered to the agent as a steer message (capped at 8 KB). Empty stdout = silent.
  • Non-zero exit or >30s timeout surfaces an error steer to the agent.
  • Each fire appends a {"type":"hook",…} entry to .auto/log.jsonl for observability.

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 the active session's resolved hooks/ directory, adapt its payload/path assumptions, and chmod +x. Git-tagging examples are Git-only; native snapshot retention already happens in the extension.


Prerequisites #

  1. Pi 1.3+ and Node.js 22.19+ — follow the instructions at pi.dev. The extension uses Pi's skill-dispatch and sequential-tool APIs and is tested against Pi 1.3.
  2. An API key for your preferred LLM provider (configured in pi)
  3. Git, or jj 0.46+ for the native workflow (including Pareto)

Security and trust #

Pi packages run with your full user permissions. Review this repository before installing it; use a dedicated Git branch/worktree or an approved jj research workspace. Native directory routing is not a security sandbox.

Autoresearch edits files, runs the resolved benchmark/checks/hooks, and either commits/reverts (Git) or retains snapshots (jj). Review executable session files, keep credentials and sensitive files out of scope, and use a sandbox or restricted environment for untrusted projects.

Before native clear or deleting workspace/session metadata, archive the stable log: retention tags live in the shared repository, but measurements, pins and history are workspace-local. Clear removes only the active native log after confirmation, never the tags, original .auto/ or source; there is no automatic pruning.

For reproducible installs, pin a version you have reviewed, for example pi install npm:pi-autoresearch@1.7.0. Published npm releases include provenance attestations.

Controlling costs #

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

  • API key limits — most providers let you set per-key or monthly budgets. Check your provider's dashboard.
  • maxIterations — cap experiments in the controller config (.auto/config.json for Git; returned metadata configPath for jj):
    {
      "maxIterations": 30
    }
    

License #

MIT