> ## Documentation Index
> Fetch the complete documentation index at: https://docs.myrmagent.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# File Checkpoints & Rollback

> Automatic file snapshots with selective rollback, external effect detection, and Agent-aware recovery.

# File Checkpoints & Rollback

Every time your Agent runs a destructive command (file edits, shell commands), Myrm automatically captures a **Shadow Git snapshot** of your workspace. You can view changes, selectively restore files, and the Agent automatically adapts to your rollbacks.

## Batch Atomic Edits

When the Agent needs to change multiple regions in one file (rename imports, update several constants, etc.), `file_edit_tool` accepts an **`edits` array** (up to 20 items) and applies them in a **single atomic transaction**:

* **One read, one write** — all replacements happen in memory before a single disk commit
* **Overlap protection** — edits whose search spans overlap in the original file are rejected up front
* **All-or-nothing verify** — if `verify_command` fails (e.g. syntax check), **every** edit in the batch rolls back
* **UI** — the progress panel shows a merged diff with `--- edit 1 ---`, `--- edit 2 ---` sections

This avoids the classic multi-call failure mode where edit 3 fails but edits 1–2 already corrupted your file. Verified by Chrome LIVE WebUI E2E (real LLM + real workspace write).

## How It Works

<Steps>
  <Step title="Automatic Snapshot">
    Before any destructive action (file writes, bash commands), the system transparently snapshots all tracked files using an isolated Shadow Git repository — completely separate from your project's `.git`.
  </Step>

  <Step title="Visual Timeline">
    Open the History panel to see a chronological timeline of all snapshots. Each card shows which files changed, with line-level statistics (+X/-Y lines).
  </Step>

  <Step title="Selective Restore">
    Choose specific files to roll back while keeping other changes. Or restore everything at once with a confirmation dialog.
  </Step>

  <Step title="Agent Auto-Awareness">
    After you restore files, the Agent automatically detects the rollback on its next turn and re-reads the affected files — no manual intervention needed.
  </Step>
</Steps>

## Multi-Agent Activity View

When multiple Agents collaborate on a task, each snapshot is automatically tagged with the Agent that triggered it. The snapshot panel provides:

* **Agent Name Badge** — each snapshot card shows the responsible Agent's name in a blue tag
* **Agent Filter** — when 2+ Agents have created snapshots, a filter bar appears letting you view snapshots from a specific Agent
* **SSE Real-Time Refresh** — new snapshots appear automatically via Server-Sent Events with a 500ms debounce (no manual refresh needed)

This makes it easy to answer "which Agent changed what?" and perform targeted rollbacks when one Agent's work needs to be undone while keeping another's.

## External Effect Warnings

When a command involves irreversible side effects beyond the file system, Myrm flags it:

| Category            | Examples                                         | Warning                                        |
| ------------------- | ------------------------------------------------ | ---------------------------------------------- |
| **Database**        | `psql`, `mysql`, `redis-cli`, `mongo`            | DB mutations cannot be undone by file rollback |
| **Network**         | `curl -d`, `http POST`, `wget --post`            | HTTP writes already sent to remote servers     |
| **Container/Cloud** | `docker rm`, `kubectl delete`, `terraform apply` | Infrastructure changes persist externally      |

When restoring a snapshot that included these operations, the UI shows a clear warning:

> "Files will be restored, but database/network/container changes made during this command cannot be reversed."

## Zero Configuration

File checkpoints work out of the box:

* **No setup required** — enabled by default on all deployment modes
* **No git pollution** — Shadow Git is completely isolated from your project
* **No performance impact** — async snapshots with 3-second timeout
* **Auto storage management** — 50 snapshots per project, 2GB global cap, automatic cleanup

## Storage Architecture

The Shadow Git system uses a shared bare repository with per-project refs:

* **Content deduplication** — identical files across projects stored only once
* **Orphan cleanup** — deleted projects automatically pruned
* **Corruption repair** — automatic `git fsck` + repack on detection
* **Global gc** — periodic garbage collection keeps disk usage minimal

## Crash Recovery

If the server crashes mid-task:

1. LangGraph's persistent SQLite checkpointer saves full state at every graph transition
2. On restart, `OfflineDurableTask` detects interrupted tasks
3. Tasks resume from the exact interruption point — no user action needed

This is architecturally superior to manual checkpoint callbacks (as used by some competitors) because state is captured at every graph node transition automatically, not just at manually-instrumented points.

## 6-Layer Resilience System

File checkpoints are just one layer of Myrm's comprehensive interruption recovery system:

| Layer                 | What It Protects                           | Recovery Mechanism                                                 |
| --------------------- | ------------------------------------------ | ------------------------------------------------------------------ |
| **Graph State**       | Entire agent execution state               | LangGraph SQLite checkpointer with incremental dill serialization  |
| **Subagent Tasks**    | Child agent work during shutdowns          | Automatic SIGTERM checkpoint save + seamless resume                |
| **Conversation Fork** | Conversation exploration branches          | Fork from any checkpoint with full parent lineage tracking         |
| **Goal Management**   | Long-running goals paused by budget/user   | Resume with counter reset, preserving all prior progress           |
| **File Snapshots**    | Workspace file modifications               | Shadow Git with selective restore + Agent auto-awareness           |
| **Stream Recovery**   | Network interruptions during LLM streaming | 4 strategies: oneshot, continuation, truncation, overflow failover |

No matter the interruption — process crash, network drop, user pause, or budget exhaustion — Myrm recovers from the exact point of interruption with zero data loss.

## Real-Time Diff Visualization

Every time your Agent modifies a file, Myrm automatically computes a unified diff and streams it to the UI via SSE — no refresh needed.

### What You See

* **File list with change stats** — each modified file shows `+N/-N` lines added/removed
* **Click to expand** — view the full diff inline with syntax highlighting
* **Unified or Split view** — toggle between single-pane (GitHub-style) and side-by-side comparison
* **Language-aware highlighting** — Prism.js automatically detects the file language
* **Line numbers** — old and new line numbers displayed in dual columns
* **Copy diff** — one-click copy of the raw diff content

### How It Works

1. **DiffCollectorObserver** (harness layer) intercepts every file write/edit
2. Computes a cumulative unified diff against the turn's initial snapshot
3. Pushes a `FILE_DIFF` SSE event to the frontend
4. **FilePathRenderer** shows the file badge with change stats
5. **DiffViewer** renders the full interactive diff on expand

### Safety Limits

* Long diffs are automatically truncated at **2,000 lines** with a `(truncated)` indicator
* Binary files display "Binary file changed" instead of garbled content
* DiffViewer has a **400px max-height** with scroll — never overwhelms the conversation

### Message-Level Turn Undo (Honest UX)

Each assistant message that changed files shows an **Undo** control in the WebUI. One click lets you preview the diff and restore revertible files for that turn only.

**Honest feedback — no false promises:**

| Situation                             | What you see                                         |
| ------------------------------------- | ---------------------------------------------------- |
| No file changes on this turn          | “No file changes on this message”                    |
| All changes skipped (e.g. file >2 MB) | Clear reason — file too large or snapshot store full |
| Mixed revertible + skipped            | Popover shows which paths can and cannot be restored |

Session-level **Undo all files** lives in the chat header chips row — same honest rules.

IM channels: `/undo` removes the last turn and reverts linked files; if some paths cannot be restored, the reply says so explicitly.

After a successful Turn Undo (message, session, or IM), the Agent receives a **restore\_inbox** notification on its next turn—the same mechanism as Shadow Git restore—so it re-reads affected files instead of relying on stale chat memory.

### Empty write rejection & failure banner

If the Agent calls `file_write_tool` with **empty, whitespace-only, or invisible-only content (ZWSP/BOM)**, Myrm **does not** create a misleading file on disk. Instead:

1. The tool returns a clear error (`Cannot write empty file content`)
2. The per-turn mutation verifier records the failure
3. The WebUI shows a **FileModificationWarning** amber banner under that assistant message: file modification failed — changes were rolled back automatically

The banner survives a page reload (`fileMutationFailures` is persisted in assistant message metadata).

Users are not misled by the model claiming success when nothing was written. Many competitors allow empty writes and lack an equivalent honest UI cue.

<Note>
  Turn undo uses lightweight per-message snapshots (default on, zero setup). Shadow Git checkpoints (below) are a separate, deeper rollback layer for destructive shell workflows.
</Note>

### Decide & Act

After reviewing the diff, you can:

* **Undo this message** — one-click turn restore (Honest UX above)
* **Approve** — continue the conversation, the change stays
* **Rollback** — use File Checkpoints (above) to restore any file to its previous state
* The Agent automatically detects rollbacks and adjusts its next actions accordingly
