---
title: "Autoresearch Experiment Loops"
description: "Use /autoresearch when progress can be measured repeatedly: change one variable, run a benchmark and correctness checks, keep or revert the result, record what happened, and choose the next experiment."
slug: "guides/teams-and-swarms/autoresearch"
sidebar:
  label: "/autoresearch"
seo:
  description: "Configure and operate Autohand autoresearch experiment loops with measurable metrics, adaptive sampling, constraints, a replayable ledger, sub-agent phases, hooks, dashboards, and finalization."
---

:::warning
**Availability:** `/autoresearch` is a newer command surface. Run `/help` and confirm it appears before relying on it in a workflow. Update Autohand Code if your installed build does not advertise the command.
:::

:::warning
**Use a clean branch or dedicated worktree.** A new replayable session requires the workspace to be the root of a clean Git repository with at least one commit. Accepted experiments are committed by the loop; rejected, inconclusive, and failed candidates are removed from the working tree after their records are saved. Commit or move unrelated work before starting, and review the generated benchmark and checks before allowing the loop to run.
:::

## Use it for a measurable objective [#when-to-use]

Autoresearch is an optimizer, not a general “keep trying” mode. A good objective has one primary numeric metric, a direction, a stable benchmark, correctness checks, an editable scope, and a finite budget.

| Good fit | Metric | Direction | Backpressure check |
| --- | --- | --- | --- |
| Reduce unit-test runtime | `total_ms` | Lower | Full tests and typecheck |
| Shrink a browser bundle | `bundle_bytes` | Lower | Build plus smoke tests |
| Improve retrieval quality | `ndcg_at_10` | Higher | Latency and regression set |
| Reduce query latency | `p95_ms` | Lower | Result equivalence and migration safety |

Use `/deep-research` when the primary outcome is an evidence-backed answer. Use a normal agent team when the outcome is a multi-part implementation without a stable numeric objective.

## Start interactively or from the CLI [#start]

```bash
# Interactive session
/autoresearch optimize unit test runtime

# Non-interactive aliases
autohand auto-research optimize unit test runtime
autohand autoresearch optimize unit test runtime
```

With only a goal, Autohand infers the metric, unit, direction, benchmark, checks, scope, iteration budget, timeout, and useful sub-agent phases from the repository. It asks concise setup questions only for material gaps, then initializes the session before the first experiment.

Initialization captures the current commit and runs a zero-diff baseline before any candidate edit. It stops on dirty paths, changed submodules, an unsafe scope, a `HEAD` that moves during setup, an invalid environment allowlist, or an evaluator that does not meet the metric contract.

### Initialize the contract explicitly

```bash
/autoresearch reduce unit test runtime \
  --metric total_ms \
  --unit ms \
  --direction lower \
  --measure "node scripts/measure-tests.mjs" \
  --checks "npm run typecheck && npm test" \
  --secondary-objective memory_mb:MB:lower \
  --constraint memory_mb:<=:512 \
  --min-samples 3 --max-samples 9 --confidence 2 \
  --max-iterations 20 \
  --timeout-ms 600000 \
  --max-artifact-bytes 1073741824 --max-artifact-age-days 30 \
  --scope src \
  --scope tests \
  --allow-env CI \
  --subagent-ideas \
  --subagent-analysis \
  --subagent-finalization
```

When `--metric`, `--unit`, `--direction`, and `--measure` are all present, the command writes the initial benchmark configuration immediately. Flags accept `--flag value` or `--flag=value`.

| Flag | Meaning |
| --- | --- |
| `--metric`, `--unit`, `--direction lower\|higher`, `--measure` | Define the primary objective and its evaluator command (aliases: `--metric-name`, `--metric-unit`, `--measure-command`) |
| `--checks` | Correctness checks that run after a passing benchmark (alias: `--checks-command`) |
| `--secondary-objective name:unit:lower\|higher` | Repeatable. Extra objectives that participate in Pareto ranking but do not decide automatic acceptance |
| `--constraint metric:op:value` | Repeatable. Hard constraint with `<`, `<=`, `>`, or `>=`, for example `memory_mb:<=:512`. Constraints fail closed |
| `--min-samples`, `--max-samples` | Adaptive sampling bounds. Defaults: 3 and 9 |
| `--confidence` | Confidence threshold a primary improvement must reach to be accepted (alias: `--confidence-threshold`). Default: 2 |
| `--max-iterations` | Iteration budget. Default: 30 |
| `--timeout-ms` | Benchmark timeout in milliseconds (alias: `--timeout`). Default: 600000 |
| `--max-artifact-bytes`, `--max-artifact-age-days` | Optional artifact retention limits. Both default to unlimited |
| `--scope` | Repeatable. Editable paths or globs recorded in the experiment prompt |
| `--allow-env NAME` | Repeatable. Adds a non-secret environment variable to the replay fingerprint. Secret-like names (containing `TOKEN`, `SECRET`, `PASSWORD`, `CREDENTIAL`, `PRIVATE`, `API_KEY`, `AUTH`, `COOKIE`, or `SESSION`) are rejected even when named explicitly |
| `--subagent-ideas`, `--subagent-analysis`, `--subagent-finalization` | Enable sub-agent phases (see below) |

Repeated `--scope` flags are an instruction boundary, not a filesystem sandbox. Run Autohand in an isolated worktree when enforcement matters.

## Build a deterministic metric contract [#metric-contract]

The measure command must exit successfully and print one machine-readable metric line for every configured objective:

```text
METRIC total_ms=1842.6
METRIC memory_mb=310
```

Each name must exactly match a configured objective, and each value must be a finite number. Decimal, signed, and scientific-notation values are accepted. Additional benchmark output is preserved as a bounded excerpt, but only the `METRIC <name>=<number>` lines drive comparison.

### Example measurement wrapper

```js
// scripts/measure-tests.mjs
import { spawnSync } from 'node:child_process';
import { performance } from 'node:perf_hooks';

const started = performance.now();
const result = spawnSync('npm', ['run', 'test:unit'], {
  stdio: 'inherit',
  env: { ...process.env, CI: '1' }
});
const elapsed = performance.now() - started;

if (result.status !== 0) process.exit(result.status ?? 1);
console.log(`METRIC total_ms=${elapsed.toFixed(2)}`);
```

- Warm or reset caches consistently; do not let setup differ between runs.
- Pin datasets, concurrency, environment variables, and hardware where possible.
- Keep correctness checks separate from the optimized metric so a faster wrong result cannot win.

## How a candidate is decided [#decision-policy]

The engine samples each candidate adaptively. It starts with `--min-samples` runs, adds one sample at a time while the noise bands of the candidate and the baseline overlap, and stops at `--max-samples`. Each objective is aggregated with the median and the median absolute deviation (MAD). The primary improvement is measured against the latest accepted evaluation.

| Decision | When |
| --- | --- |
| `accepted` | Every hard constraint passes and the primary improvement reaches the confidence threshold |
| `rejected` | A hard constraint fails or the primary metric clearly regresses |
| `inconclusive` | The measurements still overlap at the sample limit |
| `checks_failed` / `crashed` | Correctness checks or the evaluator itself failed |

Accepted changes stay in place so the agent can commit them, and the accepted candidate must be committed and logged before another candidate runs. Every other outcome is restored out of the working tree after its record is saved, but its artifacts stay in the ledger for replay and comparison.

## Understand one experiment iteration [#loop]

1. Read prior outcomes from `.auto/log.jsonl` and the living context in `.auto/prompt.md`.
2. Optionally delegate idea generation or surprising-result analysis to sub-agents.
3. Choose one focused hypothesis and make one bounded change.
4. Run the before hook, the sampled benchmark, the after hook, and correctness checks within the configured timeout.
5. Persist the candidate patch, evaluation, and decision to the ledger.
6. Commit an accepted candidate and log it; a non-accepted candidate is removed from the working tree.
7. Update the living prompt with wins, dead ends, and constraints, then repeat until the budget or stop condition is reached.

The default maximum is 30 iterations and the default benchmark timeout is 600,000 ms. Set smaller budgets first; expand only after the metric is stable and the keep/revert behavior is trustworthy.

## Know the experiment tools [#tools]

| Tool | Writes or runs | Important contract |
| --- | --- | --- |
| `init_experiment` | `config.json`, `measure.sh`, `prompt.md`, optional `checks.sh`, the ledger baseline | Freezes evaluator artifacts, fingerprints the safe environment, and records a sampled zero-diff baseline |
| `run_experiment` | Local hooks, sampled benchmark, metric parser, correctness checks | Captures the full Git patch plus untracked files, persists the evaluation and decision, and returns an `attemptId`, metric vectors, samples, and the decision |
| `log_experiment` | `log.jsonl` and session statistics | Takes an `attemptId` and projects the persisted decision; model-supplied metric or status values cannot override the engine |
| `replay_experiment` | A detached temporary worktree | Re-evaluates a stored candidate at its recorded base commit without changing your branch, index, or working tree |
| `analyze_experiments` | Ledger reads and appends | History, rescoring, comparison, Pareto candidates, pinning, and preview-first pruning |

## Delegate the thinking, not the metric [#subagents]

The sub-agent flags store phase choices in `.auto/config.json` and `.auto/prompt.md`. The lead then uses existing `delegate_task` or `delegate_parallel` tools during those phases.

| Flag | Phase | Good agent choices | Expected output |
| --- | --- | --- | --- |
| `--subagent-ideas` | Before selecting a change | `performance-engineer`, `researcher`, language specialist | Ranked hypotheses with affected paths and predicted mechanism |
| `--subagent-analysis` | When a result is noisy or surprising | `data-analyst`, `debugger`, `database-optimizer` | Variance diagnosis, confounders, and a discriminating next run |
| `--subagent-finalization` | After useful runs are kept | `reviewer`, `knowledge-synthesizer`, `technical-writer` | Review of kept commits, interactions, risks, and branch grouping |

:::warning
**The lead keeps benchmark authority.** Sub-agents may propose or analyze experiments, but the configured measure script, correctness checks, and the engine's decision remain the source of truth.
:::

## Inspect the `.auto/` workspace [#artifacts]

| Artifact | Purpose | Review it for |
| --- | --- | --- |
| `.auto/ledger/events.jsonl` | Versioned append-only candidate, evaluation, decision, pin, and prune records | The full, immutable experiment history |
| `.auto/ledger/objects/<sha256>` | Deduplicated patches, untracked content, evaluator scripts and config, and raw outputs | Replayable candidate artifacts |
| `.auto/config.json` | Objectives, constraints, sampling, retention, safe environment names, budget, timeout, sub-agent phases, and lineage commits | Wrong optimization target or unsafe budget |
| `.auto/measure.sh` | Current evaluator; emits one metric per objective | Determinism and exact metric output |
| `.auto/checks.sh` | Optional correctness backpressure after a passing benchmark | Missing functional or compatibility coverage |
| `.auto/prompt.md` | Goal, scope, tried ideas, wins, dead ends, and delegation plan | Repeated failed ideas or scope drift |
| `.auto/log.jsonl` | Backward-compatible summary of experiment results | Metric trend, regressions, and commits |
| `.auto/state.json` | Active/paused state and iteration count | Unexpected resume behavior |
| `.auto/dashboard.html` | Self-contained dashboard with full history, replay drift, and advisory Pareto candidates | Run comparison and status distribution |
| `.auto/finalize.md` | Reviewable finalization plan for kept runs | Interactions and follow-up before integration |
| `.auto/finalize-branches.json` | Structured kept-run branch manifest | Exact commits and suggested branch commands |

Sessions created before the ledger still load; history marks them non-replayable because no candidate artifacts exist.

## Control, inspect, and finalize a session [#control]

```bash
/autoresearch status
/autoresearch off
/autoresearch export
/autoresearch finalize
/autoresearch clear --yes
```

- `status` summarizes active state, iterations, metric configuration, and recorded runs.
- `off` pauses the loop and disables automatic resume without deleting artifacts.
- `export` writes the self-contained `.auto/dashboard.html`.
- `finalize` derives a review plan and branch manifest from kept runs. It does not create or switch branches, rewrite history, or cherry-pick changes.
- `clear --yes` deletes session state and requires explicit confirmation.

The same subcommands are available through `autohand auto-research ...` and `autohand autoresearch ...` for non-interactive use.

Starting again while a paused session has `.auto/prompt.md` resumes persisted context rather than replacing the original goal. Clear the session explicitly before beginning an unrelated objective.

## Replay, compare, and manage the ledger [#ledger]

```bash
/autoresearch history
/autoresearch replay <id> [--evaluator original|current]
/autoresearch rescore <id>
/autoresearch rescore --all
/autoresearch compare <a> <b>
/autoresearch pareto
/autoresearch pin <id>
/autoresearch unpin <id>
/autoresearch prune
/autoresearch prune --yes
```

| Subcommand | What it does |
| --- | --- |
| `history` | Lists every attempt with its replayability, decision, and whether it was materialized |
| `replay <id>` | Rebuilds the candidate in a detached temporary Git worktree at its recorded base commit, applies the stored patch and untracked files, evaluates it, and appends a new evaluation and decision. `--evaluator original` (default) uses the frozen evaluator; `current` uses today's evaluator and records drift. The worktree is removed even after failure or cancellation |
| `rescore <id>` / `rescore --all` | Appends new decisions using the stored measurements and the current policy. Past decisions are never rewritten |
| `compare <a> <b>` | Compares samples, aggregates, constraints, and decisions for two attempts |
| `pareto` | Lists constraint-passing, non-dominated candidates across all objectives. These are advisory and never committed automatically |
| `pin <id>` / `unpin <id>` | Protects a candidate's artifacts from automatic retention, or releases that protection |
| `prune` | Previews artifact retention (candidates and bytes freed). Nothing is deleted without `--yes` |
| `prune --yes` | Applies retention, including protected artifacts. Metadata and decisions are permanent, and each deletion is logged so the lost replayability stays visible |

Automatic retention only considers unpinned rejected or inconclusive candidates, oldest first, within the `--max-artifact-*` limits. Accepted and pinned artifacts are protected.

Replay freezes evaluator scripts and configuration but does not restore arbitrary environment variables. The environment fingerprint contains only OS, architecture, CLI, Node.js, Bun, and Git versions, lockfile and evaluator hashes, and the non-secret values you allowed with `--allow-env`. Full process environments, tokens, credentials, cookies, and keys are never persisted.

## Add lifecycle and workspace hooks [#hooks]

Autoresearch emits lifecycle events for start, pause, initialization, before/after benchmark execution, run, log, completion, and errors, plus `autoresearch:decision`, `autoresearch:replay`, `autoresearch:rescore`, and `autoresearch:prune` for ledger activity. Attempt IDs and decision outcomes are available in the hook JSON and as `HOOK_AUTORESEARCH_ATTEMPT_ID` and `HOOK_AUTORESEARCH_DECISION`. See the [Hooks Reference](/working-with-autohand-code/hooks#events) for the full event table.

For benchmark-local setup and cleanup, add executable scripts:

```bash
.auto/hooks/before.sh
.auto/hooks/after.sh
```

Both run with `AUTO_RESEARCH_WORKSPACE` set to the project root and `AUTO_RESEARCH_HOOK` set to `before` or `after`, and both are frozen with each candidate. A failed or timed-out hook is recorded as an experiment failure; do not hide benchmark invalidation inside a successful exit.

## Use the same state from RPC and ACP [#rpc-acp]

JSON-RPC clients can start, inspect, and stop the same persisted session through `autohand.autoresearch.start`, `autohand.autoresearch.status`, and `autohand.autoresearch.stop`. The start payload can supply metric name/unit, direction, measure or checks command/script, timeout, file scope, iteration budget, sub-agent phase configuration, and `secondaryObjectives`, `constraints`, `sampling`, `retention`, and `environmentAllowlist`.

The ledger is available through `autohand.autoresearch.history`, `autohand.autoresearch.replay`, `autohand.autoresearch.rescore`, `autohand.autoresearch.compare`, `autohand.autoresearch.pareto`, `autohand.autoresearch.pin`, and `autohand.autoresearch.prune`. Ledger operations emit `autohand.autoresearch.event` notifications with `started`, `completed`, or `failed` phases.

ACP sessions advertise `/autoresearch` in command metadata and use the same slash-command path. This keeps the experiment contract consistent across the terminal, editors, and automation clients.

## Failure modes and corrections [#failure-modes]

### No metric is parsed

Make the benchmark print exactly `METRIC configured_name=<number>` for every objective. Check spelling, exit code, working directory, and whether output is written to standard output or standard error.

### Initialization refuses to start

Commit or stash local changes, make sure the repository has at least one commit, and run Autohand from the repository root. Remove secret-like names from `--allow-env`.

### Results oscillate or stay inconclusive

Raise `--max-samples`, control caches and background load, and delegate measurement analysis before accepting small improvements. Use `/autoresearch compare` to inspect the overlapping samples.

### Faster runs break behavior

Strengthen `.auto/checks.sh` or add a `--constraint`. A metric improvement with failed correctness checks or a failed constraint is never accepted.

### The loop repeats dead ends

Inspect and update `.auto/prompt.md` with the mechanism, evidence, and why the idea failed. Ask idea-generation agents for hypotheses that are materially different, not syntactic variants.

### The working tree becomes hard to review

Reduce experiment scope, require one focused change per iteration, pause the loop, and run `/autoresearch finalize` before further changes.
