<div align="center">

# pi-rollback
### Branch-aware rollback for pi
**[Install](#install)** · **[Usage](#usage)** · **[How it works](#how-it-works)**

</div>

*When pi goes down the wrong path, roll back to the last relevant point, keep a concise summary of the detour, and continue from a cleaner context.*

An extension package for **[pi](https://pi.dev/)** — an AI coding agent that runs in your terminal.

`pi-rollback` gives both **humans** and **agents** a safe recovery workflow:

- go back to a better point in the session tree
- preserve only the lessons that still matter
- continue from a smaller, more relevant context window

Instead of deleting history, it uses pi's **tree navigation** and **branch summaries**.
That makes rollback **non-destructive, branch-aware, and recoverable**.

> **Caveat:** `pi-rollback` rewinds the agent's **active session context**, not your repo state. It does **not** automatically undo code, files, or patches the agent already generated during the abandoned detour. It only moves the conversation back to an earlier point in pi's tree and optionally leaves behind a compact summary.

---

## Quick start

Install from npm:

```bash
pi install npm:pi-rollback
```

Then reload pi:

```bash
/reload
```

Start using it:

```bash
/checkpoint before-auth-refactor
/rollback {"targetLabel":"before-auth-refactor","continuePrompt":"Fix the auth bug with the smallest possible change."}
```

If you want to install straight from git instead of npm:

```bash
pi install https://github.com/uriafranko/pi-rollback
```

---

## What's included

| | |
|---|---|
| **Extension tool** | `rollback` — lets the agent recover when it realizes the current direction is not useful |
| **Command** | `/rollback` — rollback by recent count, checkpoint label, or exact entry id |
| **Command** | `/checkpoint` — mark the current leaf so future rollbacks are precise and easy |

The commands are there for explicit human control, but the main idea is to let the **agent cut its own stale context** when it realizes the current branch is no longer helping.

---

## Why this exists

Agent sessions often contain expensive detours:

- a refactor that turned out unnecessary
- a debugging theory that was plausible but wrong
- an optimization branch that drifted away from the real user goal
- repeated tool calls that added tokens but not durable value
- scope creep after a perfectly good checkpoint

If you keep pushing forward from there, the active context gets worse:

- more tokens are spent on irrelevant history
- the model gets anchored to the wrong plan
- the same dead end is more likely to repeat
- recovery gets harder the longer the branch drifts

A full restart is not great either, because it throws away the useful context along with the bad branch.

`pi-rollback` gives you the middle path:

> keep the good checkpoint, keep the useful learnings, drop the detour.

---

## Use cases

| Situation | Why rollback helps | Best command |
|---|---|---|
| **Bad refactor** | Return to the clean pre-refactor state and keep only the useful findings | `/checkpoint before-refactor` then `/rollback {"targetLabel":"before-refactor"}` |
| **Noisy debugging detour** | Drop several recent low-value steps quickly | `/rollback 2` |
| **Agent drifted from the user goal** | Remove irrelevant branch context and resume on-task | `rollback` tool with `continuePrompt` |
| **Risky exploration after a good state** | Explore freely, knowing there is a precise way back | `/checkpoint <label>` before exploring |
| **Need a pure rewind** | Go back without leaving a new summary entry | `/rollback {"targetLabel":"before-refactor","summarize":false}` |

---

## Benefits

### 1. Cleaner context
After a rollback, the active branch is smaller and more relevant. The model sees less junk and makes better next-step decisions.

### 2. Preserves useful lessons
When summarization is enabled, the abandoned path is compressed into a short branch summary instead of being kept as raw noisy history.

### 3. Non-destructive
Rollback does **not** erase the old branch. The original path remains in pi's session tree and can still be revisited with `/tree`.

### 4. Good for autonomous agents
The `rollback` tool is LLM-callable, so the agent can recover on its own when it notices it is optimizing the wrong thing.

### 5. Better than “start over”
You keep the important checkpoint, the surviving context, and optional lessons learned, instead of throwing away the whole session.

---

## Usage

### 1. Create a checkpoint

Use `/checkpoint` before risky work:

```bash
/checkpoint before-auth-refactor
/checkpoint before-db-migration
/checkpoint
```

If you omit the label, the extension generates a timestamp-based checkpoint name.

### 2. Roll back by label

This is the best and most reliable workflow:

```bash
/checkpoint before-auth-refactor
/rollback {"targetLabel":"before-auth-refactor"}
```

### 3. Roll back by recent count

This is fastest when the detour is recent:

```bash
/rollback
/rollback 2
/rollback {"dropMessages":3}
```

Count-based rollback uses recent **completed checkpoints on the current branch**. In practice, think of it as:

> “undo the last few completed branch steps.”

### 4. Roll back by exact entry id

For advanced automation:

```bash
/rollback {"targetEntryId":"abcd1234"}
```

### 5. Continue automatically after rollback

Turn rollback into a recovery-and-resume step:

```bash
/rollback {"targetLabel":"before-auth-refactor","continuePrompt":"Take the smaller fix path and keep auth changes minimal."}
```

### 6. Choose whether to keep a summary

Default behavior keeps a concise summary of the abandoned branch:

```bash
/rollback {"targetLabel":"before-auth-refactor"}
```

Keep only the highest-signal learnings:

```bash
/rollback {"targetLabel":"before-auth-refactor","instructions":"Keep only validated findings and touched files."}
```

Pure rewind with no summary:

```bash
/rollback {"targetLabel":"before-auth-refactor","summarize":false}
```

---

## Flow diagram

```text
Good state reached
      |
      v
/checkpoint before-auth-refactor
      |
      v
Explore risky branch / refactor / debugging detour
      |
      v
Realize branch is no longer helpful
      |
      v
rollback tool or /rollback command
      |
      v
pi navigates back to target point in the session tree
      |
      +-----------------------------+
      | summarize = true            | summarize = false
      v                             v
Create branch summary              No summary entry
for abandoned detour               pure rollback move
      |                             |
      +-------------+---------------+
                    |
                    v
Smaller, cleaner active context
                    |
                    v
Continue from the earlier relevant point
```

---

## How it works

The package is intentionally simple:

```text
/checkpoint     -> labels the current leaf in pi's session tree
/rollback       -> resolves the rollback target
rollback tool   -> queues /rollback as a follow-up command
navigateTree()  -> moves the active branch backward
branch summary  -> optionally captures the abandoned path
continuePrompt  -> optionally resumes work immediately
```

### Important design choice

Rollback does **not** mutate or delete the session JSONL history, and it does **not** revert your working tree for you.

Instead, it uses pi's existing branching model:

- move the active leaf backward
- preserve the abandoned path in the tree
- optionally attach a summary of what was learned

That is why the feature is safe, reversible, and compatible with `/tree`.

---

## Install

### From npm

```bash
pi install npm:pi-rollback
```

### From GitHub

```bash
pi install https://github.com/uriafranko/pi-rollback
```

### Manual install

```bash
cp -r extensions/pi-rollback ~/.pi/agent/extensions/
```

Then `/reload` in pi.

---

## Development

Install dev dependencies and run the smoke check:

```bash
npm install
npm run check
npm run pack:check
```

Or:

```bash
bash tests/smoke.sh
```

---

## License

MIT
