# pi-mpc

> **MPC — Mental Preview & Correction** for [pi coding agent](https://github.com/mariozechner/pi-coding-agent)

A pi extension that forces the LLM to fully rehearse a task before touching a single file. It explores the codebase, dry-runs every change, hunts for type errors and broken imports, backtracks to fix them, and only then surfaces a structured **Verified Plan** for you to approve — or discard.

---

## Why MPC?

Normal agents interleave thinking and writing. They guess, edit, re-guess, and leave a trail of partial fixes behind. MPC introduces a mandatory **rehearse → verify** loop:

```
explore → dryrun → issues → (backtrack →) verified → execute
```

All tool calls before `execute` are **read-only**. Nothing is written until the plan passes verification and you say go.

---

## Phases

| # | Phase | What happens | Tools |
|---|-------|-------------|-------|
| 1 | **explore** | Read files, grep patterns, identify everything that needs to change | read-only |
| 2 | **dryrun** | Narrate each edit step-by-step; predict the result of every change | read-only |
| 3 | **issues** | Actively check for type errors, broken imports, failing tests, wrong assumptions | read-only |
| 4 | **backtrack** | Fix identified issues, revise the plan (up to 2 rounds) | read-only |
| 5 | **verified** | Output a structured final plan with Assumptions, Steps, Risks, and Confidence | read-only |
| 6 | **execute** | User confirms → execute the verified plan with full tool access | full |

### Automatic phase transitions

Each phase ends when the LLM emits a phase marker; the extension detects it and advances automatically:

| Marker | Transition |
|--------|-----------|
| `EXPLORATION COMPLETE: …` | → dryrun |
| `DRY RUN COMPLETE: …` | → issues |
| `NO ISSUES FOUND` | → verified (skips backtrack) |
| `ISSUE N: …` | → backtrack (or force → verified after max retries) |
| `REVISED PLAN: …` | → verified |

---

## Install

```bash
pi install npm:pi-mpc
```

Or add to your project settings (`.pi/settings.json`) so teammates get it automatically:

```json
{
  "packages": ["npm:pi-mpc"]
}
```

---

## Commands

| Command | Description |
|---------|-------------|
| `/mpc` | Toggle MPC mode on / off |
| `/mpc-next` | Manually advance to the next phase (fallback when the LLM misses a marker) |
| `/mpc-resume` | Resume the most recent in-progress plan from disk |
| `/mpc-status` | Show current phase and plan file path |

**Shortcut:** `Ctrl + Alt + M` — toggle MPC mode

---

## Typical workflow

```
1.  /mpc                      ← enable MPC
2.  Refactor UserService to support async interfaces
     │
     ├─ [explore]   reads files, maps dependencies
     ├─ [dryrun]    narrates every edit, traces types
     ├─ [issues]    finds a missing export in utils.ts → ISSUE 1
     ├─ [backtrack] revises plan to add the export
     └─ [verified]  outputs structured plan + confidence rating
     │
3.  ❯  Execute the plan   ← you pick one
       Refine further
       Abort
```

---

## Safety — read-only phases

During phases 1–4, `edit` and `write` are unavailable. `bash` calls are intercepted and must match a safe-command allowlist (`cat`, `grep`, `git status`, `ls`, etc.). Destructive patterns are blocked:

- File writes (`>`, `>>`, `tee`, `truncate`)
- File mutations (`rm`, `mv`, `cp`, `mkdir`)
- Package installs (`npm install`, `pip install`, `brew install`, …)
- Git writes (`commit`, `push`, `merge`, `rebase`, …)
- System ops (`sudo`, `kill`, `reboot`, …)

Any blocked command returns an error explaining why, with a hint to use `/mpc-next` or `/mpc` to abort.

---

## Plan persistence

Every MPC session is saved to disk automatically:

```
<project>/.pi/mpc/<timestamp>-<task-slug>.md
```

The file is human-readable Markdown (with phase outputs) plus a machine-readable JSON block at the bottom. Use `/mpc-resume` in any new session to pick up where you left off — the LLM skips completed phases and continues from the breakpoint.

---

## Verified Plan format

When the LLM reaches phase 5 it outputs a structured plan:

```markdown
## Verified Plan

### Summary
One paragraph: what this does and why.

### Assumptions Verified
- [assumption]: [how it was verified]

### Steps
1. **[File / Action]**: [what and why]
2. …

### Potential Risks
- [remaining unknowns or caveats]

### Confidence
HIGH / MEDIUM / LOW: [reason]
```

---

## Mode comparison

| Feature | Normal agent | Plan mode | MPC |
|---------|-------------|-----------|-----|
| Trigger | direct chat | `/plan` · `Ctrl+Alt+P` | `/mpc` · `Ctrl+Alt+M` |
| Workflow | think → act (interleaved) | explore → plan → execute | explore → dryrun → issues → (backtrack) → verified → execute |
| Phases | none | 2 | up to 6, auto-advancing |
| Tool lock | full always | read-only during explore | read-only until execute |
| Issue detection | ✗ | ✗ | ✓ dedicated phase |
| Auto-backtrack | ✗ | ✗ | ✓ up to 2 rounds |
| Plan format | none | numbered list | structured (Assumptions / Risks / Confidence) |
| Plan persisted | ✗ | session only | ✓ `.pi/mpc/*.md`, cross-session resume |
| Confirm before execute | — | Execute / Stay / Refine | Execute / Refine / Abort |
| Best for | quick edits | medium complexity | high-risk · multi-file · unfamiliar codebases |

---

## File structure

```
mpc/
├── index.ts      # entry point: commands, events, state machine
├── phases.ts     # phase labels + per-phase LLM prompts
├── persist.ts    # plan persistence (.pi/mpc/*.md read/write)
└── utils.ts      # types, marker detection, text helpers
```

---

## Package this for npm

To publish as an npm package so others can `pi install npm:pi-mpc`:

**`package.json`**

```json
{
  "name": "pi-mpc",
  "version": "1.0.0",
  "description": "MPC (Mental Preview & Correction) extension for pi coding agent",
  "type": "module",
  "license": "MIT",
  "keywords": ["pi-package", "pi-extension", "mpc", "plan-mode", "coding-agent"],
  "pi": {
    "extensions": ["./index.ts"]
  },
  "files": [
    "index.ts",
    "phases.ts",
    "persist.ts",
    "utils.ts",
    "README.md"
  ],
  "peerDependencies": {
    "@mariozechner/pi-coding-agent": "*",
    "@mariozechner/pi-tui": "*"
  }
}
```

Then:

```bash
npm publish --access public
```

Consumers install with:

```bash
pi install npm:pi-mpc
```

---

## Contributing

Issues and PRs welcome at [github.com/ShawnRong/pi-mpc](https://github.com/ShawnRong/pi-mpc).

---

## License

MIT
