> For the complete documentation index, see [llms.txt](https://www.opencodebook.xyz/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://www.opencodebook.xyz/en/chapter_10_snapshot_and_file_system/10.1_git_snapshot_system.md). Agents can also search and read this documentation through its [MCP server](https://www.opencodebook.xyz/~gitbook/mcp).

# 10.1 Git Snapshot System

> **Model**: claude-opus-4-6 (anthropic/claude-opus-4-6) **Date Generated**: 2026-02-17

***

When an AI Agent modifies files, it can make mistakes -- it might erroneously delete code, overwrite important content, or introduce syntax errors. Without a rollback mechanism, users would have to manually restore these changes, or might not be able to restore them at all. OpenCode's **Snapshot system** was designed to solve exactly this problem -- it automatically creates a file system snapshot before each step of an Agent's operation, ensuring that any change can be precisely rolled back.

## 10.1.1 Design Goals

The design goals of the Snapshot system are:

1. **Fine-grained**: A snapshot is created before each tool invocation step, not just at the session level.
2. **Zero interference**: Snapshot operations are completely transparent to both the user and the Agent, and do not affect the project's Git history.
3. **Low overhead**: Leverages Git's content-addressable storage and incremental mechanisms to minimize disk usage.
4. **Automatic cleanup**: Expired snapshots are automatically cleaned up and do not grow indefinitely.

## 10.1.2 Separate Git Repository Strategy

The core design decision of the Snapshot system is to use a **separate, hidden Git repository** to store snapshots, rather than using the project's own Git repository. This repository is located in OpenCode's global data directory:

```typescript
// snapshot/index.ts
function gitdir() {
  const project = Instance.project
  return path.join(Global.Path.data, "snapshot", project.id)
  // Typical path: ~/.local/share/opencode/snapshot/<project-id>
}
```

Why not use the project's Git repository directly? There are three reasons:

1. **No pollution of project history**: Snapshots are an internal implementation detail of OpenCode and should not appear in the project's Git log.
2. **No interference with the working tree**: The project may have uncommitted changes, staging area state, etc., and snapshot operations should not affect these.
3. **Support for non-Git projects**: Although the current implementation depends on Git, separating the snapshot repository from the project repository leaves room for supporting other version control systems in the future.

Git's `--git-dir` and `--work-tree` parameters make this "separate repository managing an external working tree" approach possible -- the Git repository metadata (`.git`) is stored in OpenCode's data directory, but the tracked files are in the project's working tree.

## 10.1.3 Snapshot.track(): Creating Snapshots

`track()` is the core function for creating snapshots:

```typescript
export async function track() {
  // Only works in Git projects
  if (Instance.project.vcs !== "git") return

  // Skip if the user has disabled the snapshot feature
  const cfg = await Config.get()
  if (cfg.snapshot === false) return

  const git = gitdir()

  // If the snapshot Git repository doesn't exist, initialize it
  if (await fs.mkdir(git, { recursive: true })) {
    await $`git init`
      .env({
        ...process.env,
        GIT_DIR: git,
        GIT_WORK_TREE: Instance.worktree,
      })
      .quiet()
      .nothrow()

    // Disable line-ending conversion on Windows
    await $`git --git-dir ${git} config core.autocrlf false`
      .quiet().nothrow()

    log.info("initialized")
  }

  // Add all files in the working tree to the staging area
  await $`git --git-dir ${git} --work-tree ${Instance.worktree} add .`
    .quiet()
    .cwd(Instance.directory)
    .nothrow()

  // Use write-tree to create a tree object (without creating a commit)
  const hash = await $`git --git-dir ${git} --work-tree ${Instance.worktree} write-tree`
    .quiet()
    .cwd(Instance.directory)
    .nothrow()
    .text()

  log.info("tracking", { hash, cwd: Instance.directory, git })
  return hash.trim()
}
```

> **Extended Explanation: Git's Low-Level Object Model**
>
> At the low level, Git uses three core object types:
>
> * **Blob**: Stores file contents
> * **Tree**: Stores directory structure (records each file/subdirectory's name, permissions, and corresponding blob/tree hash)
> * **Commit**: Points to a tree object, plus metadata such as author, timestamp, and parent commit
>
> `git write-tree` is a low-level command (plumbing command) that writes the contents of the current staging area (index) into a tree object and returns the SHA-1 hash of that tree. Unlike `git commit`, `write-tree` does not create a commit object, nor does it modify HEAD. This makes snapshot operations extremely lightweight -- it simply "freezes" the current file state as a tree object.

The return value of `track()` is the hash of a tree object (e.g., `"a3f7b2c..."`). This hash is stored in the Session's message data as an anchor point for subsequent rollbacks.

In `session/processor.ts`, `track()` is called at the beginning of each step:

```typescript
// session/processor.ts
case "start-step":
  snapshot = await Snapshot.track()  // Create snapshot
  // ... subsequent tool invocations
```

## 10.1.4 Snapshot.restore(): Restoring Snapshots

When a user needs to roll back to a particular snapshot, the `restore()` function restores the working tree to the state of the specified tree:

```typescript
export async function restore(snapshot: string) {
  log.info("restore", { commit: snapshot })
  const git = gitdir()

  // read-tree: Read the tree object into the staging area
  // checkout-index -a -f: Write all files from the staging area to the working tree
  const result = await $`
    git --git-dir ${git} --work-tree ${Instance.worktree} read-tree ${snapshot} &&
    git --git-dir ${git} --work-tree ${Instance.worktree} checkout-index -a -f
  `
    .quiet()
    .cwd(Instance.worktree)
    .nothrow()

  if (result.exitCode !== 0) {
    log.error("failed to restore snapshot", { ... })
  }
}
```

The restoration process consists of two low-level Git operations:

1. **`git read-tree`**: Reads the specified tree object into the staging area (index), replacing the current staging area contents.
2. **`git checkout-index -a -f`**: Force-writes (`-f`) all files (`-a`) from the staging area to the working tree, overwriting existing files.

### Fine-Grained Rollback: revert()

In addition to full restoration, the `revert()` function supports more fine-grained, file-level rollbacks:

```typescript
export async function revert(patches: Patch[]) {
  const files = new Set<string>()
  const git = gitdir()

  for (const item of patches) {
    for (const file of item.files) {
      if (files.has(file)) continue  // Only roll back each file once

      const result = await $`
        git --git-dir ${git} --work-tree ${Instance.worktree}
        checkout ${item.hash} -- ${file}
      `.quiet().cwd(Instance.worktree).nothrow()

      if (result.exitCode !== 0) {
        // Check if the file exists in the snapshot
        const checkTree = await $`
          git --git-dir ${git} --work-tree ${Instance.worktree}
          ls-tree ${item.hash} -- ${relativePath}
        `.quiet().cwd(Instance.worktree).nothrow()

        if (checkTree.exitCode === 0 && checkTree.text().trim()) {
          // File existed in snapshot but checkout failed; keep current state
          log.info("file existed in snapshot but checkout failed, keeping")
        } else {
          // File didn't exist in snapshot, meaning it was newly created; delete it
          await fs.unlink(file).catch(() => {})
        }
      }
      files.add(file)
    }
  }
}
```

The logic of `revert()` is more nuanced:

* It accepts a set of `Patch` objects (each containing a tree hash and a list of changed files).
* For each changed file, it attempts to restore from the corresponding snapshot.
* If the file didn't exist in the snapshot (meaning it was newly created by the Agent), the file is deleted.
* A `Set` is used to ensure each file is processed only once, avoiding duplicate operations.

## 10.1.5 Snapshot.diff(): Change Comparison

The `diff()` function compares the differences between the current working tree and a given snapshot:

```typescript
export async function diff(hash: string) {
  const git = gitdir()

  // First add the current state to the staging area
  await $`git --git-dir ${git} --work-tree ${Instance.worktree} add .`
    .quiet().cwd(Instance.directory).nothrow()

  // Generate the diff
  const result = await $`
    git -c core.autocrlf=false -c core.quotepath=false
    --git-dir ${git} --work-tree ${Instance.worktree}
    diff --no-ext-diff ${hash} -- .
  `.quiet().cwd(Instance.worktree).nothrow()

  return result.text().trim()
}
```

The `patch()` function returns only the list of changed files (without detailed content diffs), making it more lightweight:

```typescript
export async function patch(hash: string): Promise<Patch> {
  // Use --name-only to get only file names
  const result = await $`
    git ... diff --no-ext-diff --name-only ${hash} -- .
  `.quiet().cwd(Instance.directory).nothrow()

  return {
    hash,
    files: result.text().trim().split("\n")
      .map(x => x.trim()).filter(Boolean)
      .map(x => path.join(Instance.worktree, x)),
  }
}
```

`diffFull()` provides the most complete diff information, including before/after content, added/deleted line counts, and status for each file:

```typescript
export async function diffFull(from: string, to: string): Promise<FileDiff[]> {
  // 1. Get file statuses (Added/Deleted/Modified)
  const statuses = await $`git ... diff --name-status --no-renames ${from} ${to}`.text()

  // 2. Get line change statistics for each file
  for await (const line of $`git ... diff --numstat ${from} ${to}`.lines()) {
    const [additions, deletions, file] = line.split("\t")

    // 3. Get full file contents before and after the change
    const before = await $`git ... show ${from}:${file}`.text()
    const after = await $`git ... show ${to}:${file}`.text()

    result.push({ file, before, after, additions, deletions, status })
  }
  return result
}
```

## 10.1.6 Automatic Cleanup Mechanism

Snapshot data accumulates over time. OpenCode registers an hourly cleanup task through the Scheduler (a scheduled task dispatcher, covered in detail in Chapter 11):

```typescript
export function init() {
  Scheduler.register({
    id: "snapshot.cleanup",
    interval: hour,           // 60 * 60 * 1000 = 1 hour
    run: cleanup,
    scope: "instance",        // Independent per project instance
  })
}

export async function cleanup() {
  if (Instance.project.vcs !== "git") return
  const cfg = await Config.get()
  if (cfg.snapshot === false) return

  const git = gitdir()
  const exists = await fs.stat(git).then(() => true).catch(() => false)
  if (!exists) return

  // Use git gc to clean up data older than 7 days
  const result = await $`
    git --git-dir ${git} --work-tree ${Instance.worktree}
    gc --prune=${prune}
  `.quiet().cwd(Instance.directory).nothrow()
}
```

`gc --prune=7.days` is Git's garbage collection command -- it compresses Git objects (packing them into packfiles) and deletes unreachable objects older than 7 days. Since snapshots only use `write-tree` (without creating commits), tree objects that have no commit referencing them are "unreachable" and will naturally be removed during cleanup.

This design means: **snapshots from the last 7 days are always available**, while older snapshots are automatically cleaned up to free disk space. For everyday development, a 7-day window is sufficient to cover the vast majority of rollback needs.

***

> **Section Summary**
>
> OpenCode's Snapshot system uses a separate Git repository (stored in `~/.local/share/opencode/snapshot/`) to track changes in project file states. The core operation `track()` uses `git write-tree` to create lightweight tree objects as snapshots (without creating commits), while `restore()` and `revert()` support full restoration and fine-grained file-level rollback respectively. An automatic cleanup task runs every hour, using `git gc --prune=7.days` to clean up expired data. This design ensures zero interference (no pollution of the project's Git history) while achieving fine-grained file change tracking and rollback capabilities with minimal overhead.
