Create an isolated overlay workspace

Use an overlay when a preview, generator, or agent should edit a project without changing its starting state. An overlay is an ordinary writable Volume backed by one immutable snapshot.

Install the core package and your runtime's Crypto provider as described in Build and transport filesystem snapshots. The examples below run with Bun.

Create, edit, and capture a workspace

Start with a snapshot of the files that every workspace should see. This example creates two workspaces from the same base, edits one of them, reviews the result, and captures it:

import * as BunCrypto from "@effect/platform-bun/BunCrypto"
import { VirtualFileSystem as Vfs } from "@effect-vfs/core"
import { Effect } from "effect"
 
const encoder = new TextEncoder()
const decoder = new TextDecoder()
 
const program = Effect.gen(function* () {
  const source = yield* Vfs.fromFixture({
    entries: [
      { kind: "directory", path: "/project" },
      {
        kind: "file",
        path: "/project/package.json",
        bytes: encoder.encode('{"scripts":{}}')
      }
    ]
  })
  const base = yield* source.snapshot
 
  const workspace = yield* Vfs.makeOverlay(base)
  const sibling = yield* Vfs.makeOverlay(base)
  const fs = yield* workspace.caller()
 
  yield* fs.writeFile(
    "/project/package.json",
    encoder.encode('{"scripts":{"check":"tsc --noEmit"}}'),
    { access: "write", truncate: true }
  )
  yield* fs.writeFile(
    "/project/notes.md",
    encoder.encode("Review the generated type errors.\n"),
    { access: "write", create: "exclusive" }
  )
 
  const changes = yield* workspace.changes()
  const changedKinds = changes.map((change) => change._tag)
 
  const siblingFs = yield* sibling.caller()
  const unchanged = decoder.decode(
    yield* siblingFs.readFile("/project/package.json")
  )
 
  const accepted = yield* workspace.capture()
  const acceptedFs = yield* (yield* Vfs.fromSnapshot(
    accepted.snapshot
  )).caller()
  const notes = decoder.decode(yield* acceptedFs.readFile("/project/notes.md"))
 
  return { changedKinds, unchanged, notes }
})
 
console.log(await Effect.runPromise(program.pipe(Effect.provide(BunCrypto.layer))))

changedKinds contains Updated and Added. The sibling still contains {"scripts":{}}, while the restored capture contains the new notes file.

Make changes without changing the base

Each execution of makeOverlay(base) creates a fresh workspace. Workspaces made from the same snapshot have private namespaces, metadata, callers, handles, watches, and mutation coordination. A write in one workspace cannot change the base, the source volume, or a sibling workspace.

Unchanged regular-file payloads are shared. The first content mutation replaces the whole file payload with workspace-private storage, including a same-size handle write. This is whole-file copy-on-write, not block-level copying. Reads return owned byte copies.

Capacity limits passed to makeOverlay apply to the complete visible filesystem. They do not measure changed data alone.

Inspect the final differences

Call workspace.changes() to compare the current workspace with its base. The result describes final state, not the sequence of operations that produced it.

Changes can be:

  • Added or Removed when a path exists on only one side;
  • Updated when content, ownership, permissions, or another reported field changed;
  • Replaced when the same path now refers to a new object identity; or
  • Renamed when retained base identity proves one unambiguous move.

Equal file contents do not prove a rename. Ambiguous hard-link moves remain additions and removals. Timestamp-only differences are hidden by default; pass { includeTimestamps: true } when they matter.

Summary paths are opaque BytePath values because a virtual filesystem can contain names that are not UTF-8. Use pathToBytes to obtain their raw bytes. Compare paths as bytes. For display, use hex or base64, or attempt fatal UTF-8 decoding with a byte-safe fallback. A normal TextDecoder can turn different invalid byte sequences into the same replacement-character text. Overlay summaries are in-process values and do not have a portable encoding.

Capture a matching result and summary

Use workspace.capture() when you need both the complete snapshot and its change summary. It observes both from one successfully completed state, so a concurrent write cannot leave the snapshot and summary describing different states.

The returned snapshot and changes remain stable after later workspace writes. You can restore or encode the snapshot, and you can store it with @effect-vfs/persistence.

Do not replace capture() with separate workspace.snapshot and workspace.changes() calls when the two results must match. A mutation can commit between those observations.

Merge two workspaces

To carry edits to a new filename, follow Merge overlays across file renames.

When several workspaces start from one base, combine their results with mergeSnapshotDeltas. It takes the base and one delta per side, applies every change the two sides do not dispute, and reports path-level conflicts as data instead of failing. The merged delta is bound to the same base and applies with applySnapshotDelta.

import * as BunCrypto from "@effect/platform-bun/BunCrypto"
import { VirtualFileSystem as Vfs } from "@effect-vfs/core"
import { Effect } from "effect"
 
const encoder = new TextEncoder()
const decoder = new TextDecoder()
 
const program = Effect.gen(function* () {
  const source = yield* Vfs.fromFixture({
    entries: [
      { kind: "file", path: "/README.md", bytes: encoder.encode("# Project\n") },
      { kind: "file", path: "/config.json", bytes: encoder.encode("{}") }
    ]
  })
  const base = yield* source.snapshot
 
  const docs = yield* Vfs.makeOverlay(base)
  const build = yield* Vfs.makeOverlay(base)
  const docsFs = yield* docs.caller()
  const buildFs = yield* build.caller()
 
  yield* docsFs.writeFile("/README.md", encoder.encode("# Project\n\nSee docs/.\n"), {
    access: "write",
    truncate: true
  })
  yield* buildFs.writeFile("/config.json", encoder.encode('{"target":"es2024"}'), {
    access: "write",
    truncate: true
  })
  yield* buildFs.writeFile("/README.md", encoder.encode("# Project (build)\n"), {
    access: "write",
    truncate: true
  })
 
  const ours = yield* Vfs.diffSnapshots(base, (yield* docs.capture()).snapshot)
  const theirs = yield* Vfs.diffSnapshots(base, (yield* build.capture()).snapshot)
 
  const first = yield* Vfs.mergeSnapshotDeltas(base, ours, theirs)
  const reasons = first.conflicts.map((conflict) => conflict.reason)
 
  // Keep the docs workspace's README and merge again. The config change was never in dispute.
  const resolved = yield* Vfs.mergeSnapshotDeltas(base, ours, theirs, {
    resolutions: first.conflicts.map((conflict) => ({ path: conflict.path, take: "ours" as const }))
  })
  const merged = yield* Vfs.applySnapshotDelta(base, resolved.delta).pipe(Effect.flatMap(Vfs.fromSnapshot()))
  const reader = yield* merged.caller()
 
  return {
    reasons,
    remaining: resolved.conflicts.length,
    readme: decoder.decode(yield* reader.readFile("/README.md")),
    config: decoder.decode(yield* reader.readFile("/config.json"))
  }
})
 
console.log(await Effect.runPromise(program.pipe(Effect.provide(BunCrypto.layer))))

reasons is ["BothChanged"] because both workspaces rewrote /README.md. The config change was taken on the first merge already, while the conflicted path kept the base file. Passing resolutions with take set to ours, theirs, or base settles each reported path; the second merge reports nothing and the restored volume holds the chosen README and the merged config.

A conflict names each side's change as kinds and changed fields, never bytes; read the three snapshots when you need the contents. Fields merge independently, so a permission change on one side combines with a content change on the other, and timestamps never conflict. A directory removed or replaced on one side with additions or edits beneath it on the other reports ParentRemoved for each added or edited path and keeps the whole directory. A conflict also holds every name of a hard-linked file it touches at base, and reports any such name whose change it holds back. A rename appears to the merge as a removal and an addition, so renaming a file one side edited reports ChangedRemoved at the old name. Hard links merge per file: an edit through one name combines with a new or removed name on the other side, two sides that only remove names agree, and two sides that change which names share a file in different ways report HardLinkGroupDiverged for the group. Resolving a removed directory or a hard-link group means resolving every reported path in it the same way. Identical changes on both sides merge as one, which makes merging three or more deltas depend on the order you merge them in.

Reset the workspace

Create another overlay from the original base and replace the workspace reference in your application:

const freshWorkspaceEffect = Vfs.makeOverlay(base)

Execute the effect where your application installs the replacement workspace.

There is no in-place reset. Existing callers, handles, and watches remain attached to the old workspace until their normal lifetimes end.

Restoring a captured snapshot recovers its filesystem state, not its previous overlay relationship. Calling makeOverlay(captured.snapshot) establishes a new base and starts with an empty change summary.

Keep host access outside the assumption

An overlay isolates virtual filesystem state. It is not a security sandbox and cannot intercept code that uses node:fs, child processes, native extensions, or another host-access API. Code must use the overlay caller or a bound Effect FileSystem service for the isolation to apply.

Next steps