> 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.2_file_system_tools.md). Agents can also search and read this documentation through its [MCP server](https://www.opencodebook.xyz/~gitbook/mcp).

# 10.2 File System Tools

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

***

OpenCode's file system module (`file/`) provides the Agent with low-level capabilities such as file reading, searching, listing, and change monitoring. This section analyzes the five sub-files of this module.

## 10.2.1 file/index.ts: File Operations Core

`file/index.ts` (584 lines) is the core of the file system module, providing file reading, directory listing, fuzzy search, and Git status querying functionality.

### File Reading

`File.read()` is the underlying implementation of the Read tool, handling multiple file types:

```typescript
export async function read(file: string): Promise<Content> {
  const full = path.join(Instance.directory, file)

  // Security check: prevent path traversal
  if (!Instance.containsPath(full)) {
    throw new Error("Access denied: path escapes project directory")
  }

  // Image files: base64 encoding
  if (isImageByExtension(file)) {
    const buffer = await bunFile.arrayBuffer()
    return { type: "text", content: Buffer.from(buffer).toString("base64"),
             mimeType: getImageMimeType(file), encoding: "base64" }
  }

  // Known binary files: return empty content
  if (isBinaryByExtension(file)) {
    return { type: "binary", content: "" }
  }

  // Text files: read content + attach git diff
  const content = await bunFile.text()

  if (project.vcs === "git") {
    let diff = await $`git diff ${file}`.text()
    if (!diff.trim()) diff = await $`git diff --staged ${file}`.text()
    if (diff.trim()) {
      const original = await $`git show HEAD:${file}`.text()
      const patch = structuredPatch(file, file, original, content, "old", "new", {
        context: Infinity, ignoreWhitespace: true,
      })
      return { type: "text", content, patch, diff: formatPatch(patch) }
    }
  }
  return { type: "text", content }
}
```

Key design points:

1. **Path security check**: `Instance.containsPath()` prevents the Agent from escaping the project directory via paths like `../../etc/passwd`.
2. **Smart binary file handling**: Maintains a large set of file extensions (`binaryExtensions`) covering 100+ formats including executables, audio/video, archives, fonts, etc. Binary files are not read, avoiding filling the LLM context with meaningless data.
3. **Special image handling**: Image files are returned as base64-encoded data, supporting the LLM's multimodal understanding capabilities.
4. **Attached Git diff**: For files under Git management, if there are uncommitted changes, the return value includes structured diff and patch information -- this lets the LLM know not only the file's current content but also "which parts were recently modified."

### File Search

`File.search()` provides fuzzy file search based on `fuzzysort`:

```typescript
export async function search(input: {
  query: string;
  limit?: number;
  dirs?: boolean;
  type?: "file" | "directory"
}) {
  const result = await state().then(x => x.files())

  // Hidden file sorting strategy: unless the query starts with ".", push hidden files to the back
  const preferHidden = query.startsWith(".") || query.includes("/.")

  // Use fuzzysort for fuzzy matching
  const sorted = fuzzysort.go(query, items, { limit: searchLimit })
    .map(r => r.target)

  return output
}
```

> **Extended Explanation: Fuzzy Search**
>
> Fuzzy search is a search algorithm that allows approximate matching. When a user types `"indx"`, fuzzy search can match `"index.ts"` -- even with typos or missing characters. `fuzzysort` is a high-performance JavaScript fuzzy search library that uses a scoring algorithm based on the Longest Common Subsequence (LCS) to rank results.

The file list is preloaded in the background via Ripgrep (introduced below), and searches are performed directly in memory, ensuring sub-millisecond response times.

## 10.2.2 file/ignore.ts: Ignore Rules

The `FileIgnore` module defines which directories and files OpenCode should skip when scanning:

```typescript
export namespace FileIgnore {
  const FOLDERS = new Set([
    "node_modules", "bower_components", ".pnpm-store",  // JavaScript
    "vendor",                                            // PHP/Go
    "dist", "build", "out", ".next",                     // Build output
    "target",                                            // Rust/Java
    ".git", ".svn", ".hg",                               // Version control
    ".vscode", ".idea",                                  // IDE
    "__pycache__", ".pytest_cache",                       // Python
    // ...30+ directories in total
  ])

  const FILES = [
    "**/*.swp", "**/*.swo",        // Vim swap files
    "**/*.pyc",                     // Python bytecode
    "**/.DS_Store", "**/Thumbs.db", // Operating system
    "**/logs/**", "**/tmp/**",      // Logs and temporary files
    "**/coverage/**",               // Test coverage
  ]

  export function match(filepath: string, opts?) {
    // 1. Whitelist takes priority (if matching whitelist, do not ignore)
    for (const glob of opts?.whitelist || []) {
      if (glob.match(filepath)) return false
    }
    // 2. Does the path contain an ignored directory name?
    const parts = filepath.split(sep)
    for (let i = 0; i < parts.length; i++) {
      if (FOLDERS.has(parts[i])) return true
    }
    // 3. Does the filename match an ignored pattern?
    for (const glob of [...FILE_GLOBS, ...extra]) {
      if (glob.match(filepath)) return true
    }
    return false
  }
}
```

This module is used by FileWatcher to filter out file changes that don't need to be monitored, preventing change events from massive directories like `node_modules` from overwhelming the system.

## 10.2.3 file/ripgrep.ts: Ripgrep Integration

Ripgrep (`rg`) is an extremely fast file search tool. OpenCode uses it for file list enumeration, content search, and directory tree generation.

### Automatic Installation

If ripgrep is not installed on the system, OpenCode automatically downloads and installs it to the global bin directory:

```typescript
const state = lazy(async () => {
  // 1. Prefer the system-installed rg
  const system = Bun.which("rg")
  if (system) return { filepath: system }

  // 2. Otherwise download a precompiled binary
  const filepath = path.join(Global.Path.bin, "rg")
  if (!(await file.exists())) {
    const version = "14.1.1"
    const url = `https://github.com/BurntSushi/ripgrep/releases/download/${version}/${filename}`
    const response = await fetch(url)
    // ... extract and install
  }
  return { filepath }
})
```

Supported platforms include macOS (arm64/x64), Linux (arm64/x64), and Windows (x64), each corresponding to different precompiled package formats.

### File List Enumeration

`Ripgrep.files()` uses `rg --files` to enumerate all files in the project:

```typescript
export async function* files(input: { cwd: string; glob?: string[]; ... }) {
  const args = [await filepath(), "--files", "--glob=!.git/*"]
  if (input.hidden !== false) args.push("--hidden")
  // ...

  const proc = Bun.spawn(args, { cwd: input.cwd, stdout: "pipe" })
  const reader = proc.stdout.getReader()

  // Stream reading, yielding line by line
  while (true) {
    const { done, value } = await reader.read()
    if (done) break
    buffer += decoder.decode(value, { stream: true })
    const lines = buffer.split(/\r?\n/)
    buffer = lines.pop() || ""
    for (const line of lines) {
      if (line) yield line
    }
  }
}
```

This is an **async generator** -- it does not load all file names into memory at once, but yields them line by line in a streaming fashion. This is very important for large projects (tens of thousands of files), as it avoids memory spikes.

### Directory Tree Generation

`Ripgrep.tree()` builds a compressed directory tree string from the file list:

```typescript
export async function tree(input: { cwd: string; limit?: number }) {
  const files = await Array.fromAsync(Ripgrep.files({ cwd: input.cwd }))

  // Build tree structure
  const root: Node = { name: "", children: new Map() }
  for (const file of files) {
    if (file.includes(".opencode")) continue  // Skip OpenCode's own files
    const parts = file.split(path.sep)
    let node = root
    for (const part of parts.slice(0, -1)) {
      node = dir(node, part)  // Create directory nodes level by level
    }
  }

  // BFS traversal with truncation
  const lines: string[] = []
  // ... breadth-first traversal, truncate if exceeding limit
  if (total > used) lines.push(`[${total - used} truncated]`)
  return lines.join("\n")
}
```

This directory tree is the data source for the "project structure" section of OpenCode's System Prompt -- it allows the LLM to understand the project's overall directory layout from the very first round of conversation.

## 10.2.4 file/watcher.ts: File Change Monitoring

`FileWatcher` uses `@parcel/watcher` (a high-performance, cross-platform file system monitoring library) to watch file changes in real time:

```typescript
export namespace FileWatcher {
  export const Event = {
    Updated: BusEvent.define("file.watcher.updated", z.object({
      file: z.string(),
      event: z.union([z.literal("add"), z.literal("change"), z.literal("unlink")]),
    })),
  }

  const state = Instance.state(async () => {
    // Select the optimal file monitoring backend based on platform
    const backend = (() => {
      if (process.platform === "win32") return "windows"
      if (process.platform === "darwin") return "fs-events"
      if (process.platform === "linux") return "inotify"
    })()

    // Watch the project directory
    const sub = await w.subscribe(Instance.directory, subscribe, {
      ignore: [...FileIgnore.PATTERNS, ...cfgIgnores],
      backend,
    })

    // Also watch the .git directory's HEAD file (to detect branch switches)
    if (vcsDir) {
      const gitDirContents = await readdir(vcsDir)
      const ignoreList = gitDirContents.filter(entry => entry !== "HEAD")
      await w.subscribe(vcsDir, subscribe, {
        ignore: ignoreList,  // Only watch HEAD changes
        backend,
      })
    }
  })
}
```

> **Extended Explanation: File System Monitoring Technologies**
>
> Different operating systems provide different file system event notification mechanisms:
>
> * **macOS**: FSEvents -- Apple's file system event framework, capable of efficiently monitoring changes across an entire directory tree.
> * **Linux**: inotify -- The Linux kernel's file monitoring interface, which requires registering a watch on each directory individually.
> * **Windows**: ReadDirectoryChangesW -- The Windows API's directory change notification.
>
> `@parcel/watcher` wraps these platform-specific interfaces, providing a unified cross-platform API.

File change events are published through the Bus and subscribed to by other modules (such as the TUI):

```typescript
const subscribe = (err, evts) => {
  for (const evt of evts) {
    if (evt.type === "create") Bus.publish(Event.Updated, { file: evt.path, event: "add" })
    if (evt.type === "update") Bus.publish(Event.Updated, { file: evt.path, event: "change" })
    if (evt.type === "delete") Bus.publish(Event.Updated, { file: evt.path, event: "unlink" })
  }
}
```

## 10.2.5 file/time.ts: File Timestamp Management

The `FileTime` module implements a "read-before-write" safety check mechanism -- ensuring that the Agent has read the latest version of a file before modifying it:

```typescript
export namespace FileTime {
  // Record the last read time for each file in each Session
  export function read(sessionID: string, file: string) {
    read[sessionID] = read[sessionID] || {}
    read[sessionID][file] = new Date()
  }

  // Assert that the file has not been externally modified before writing
  export async function assert(sessionID: string, filepath: string) {
    const time = get(sessionID, filepath)
    if (!time) {
      throw new Error("You must read file before overwriting it. Use the Read tool first")
    }
    const stats = await Bun.file(filepath).stat()
    if (stats.mtime.getTime() > time.getTime()) {
      throw new Error(
        `File ${filepath} has been modified since it was last read.\n` +
        `Last modification: ${stats.mtime.toISOString()}\n` +
        `Last read: ${time.toISOString()}\n\n` +
        `Please read the file again before modifying it.`
      )
    }
  }

  // File lock: serialize concurrent writes to the same file
  export async function withLock<T>(filepath: string, fn: () => Promise<T>): Promise<T> {
    const currentLock = current.locks.get(filepath) ?? Promise.resolve()
    let release: () => void
    const nextLock = new Promise<void>(resolve => { release = resolve })
    current.locks.set(filepath, currentLock.then(() => nextLock))
    await currentLock  // Wait for the previous write to complete
    try {
      return await fn()
    } finally {
      release!()  // Release the lock, allowing the next write
    }
  }
}
```

This module addresses two critical concurrency safety issues:

1. **Stale read detection**: If the user manually modifies a file after the Agent has read it but before the Agent writes to it, `assert()` throws an error, preventing the Agent from overwriting the user's changes.
2. **Concurrent write serialization**: `withLock()` ensures that multiple concurrent write operations to the same file are executed serially, preventing content interleaving.

***

> **Section Summary**
>
> OpenCode's file system module consists of five sub-files: `index.ts` provides file reading (with smart routing for binary/image/text files and attached Git diffs) and fuzzy search; `ignore.ts` defines 30+ directory and file patterns that should be ignored; `ripgrep.ts` integrates the ripgrep tool for high-performance file enumeration and content search (including automatic download and installation); `watcher.ts` uses `@parcel/watcher` for cross-platform file change monitoring; and `time.ts` ensures concurrency safety through read timestamps and file locks.
