Snapshot record and storage
Eachworktree_snapshot session entry (see WorktreeSnapshotEntry) records a JSON WorktreeSnapshot object:
root: absolute checkout path on the recording machine (informational).remotes: configured remote fetch URLs with embedded credentials stripped.branchandhead: active branch name (ornullwhen detached) andHEADcommit SHA.snapshotandtree: local snapshot commit SHA (parented onhead) and Git tree SHA of the working copy, built through a private Git index under~/.atomic/agent/worktree-snapshots/capture-index/(safe to delete; rebuilt automatically on the next capture).deltaandchain: binary patch chain starting from a full delta againstheadand continuing with incremental deltas against previous snapshots, restarting fromheadeverysnapshots.fullEverysnapshots (default10) or whenHEADchanges.bundle: optional Git bundle of commits reachable fromheadand not reachable from any remote-tracking ref.omitted: structured list of paths or unpushed commits left out of the snapshot.filters: conversion settings on the recording host (core.autocrlf,core.eol, and.gitattributesfilter drivers such aslfs).envHash: SHA-256 fingerprint of root-relative lockfiles and toolchain files.
snapshot_blobs table. Payloads over 1 MiB split into rows of at most 1 MiB so every SQL backend supports files up to snapshots.maxFileBytes (default 5 MiB).
- Unpushed-commit omission caching. When unpushed commits are omitted because a commit touches a deny-listed secret or the bundle exceeds
snapshots.maxSnapshotBytes(default 50 MiB), Atomic caches that omission in memory for the running process. It re-checks and re-bundles automatically if the unpushed commit set changes (including after a push or force push), a new Atomic process starts, the repository is repacked (git gcorgit repack), Git packing or attributes settings change, orsnapshots.maxSnapshotBytesis raised above the bundle size. - Blob-less stores and transient failures. A new session in a store without blob tables (JSONL directory, memory, or custom store without
snapshotBlobs) reportsblob-store-unsupportedonce; a transient database failure reportsblob-store-failedonce without failing the turn.
Omission reasons
Every entry insnapshot.omitted carries a typed reason:
Environment fingerprint
envHash (computeEnvironmentHash(root)) computes a SHA-256 digest over "atomic-env-v1\n" followed by each present file’s path and content hash from these 25 root-relative lockfiles and toolchain files (ENVIRONMENT_INPUT_FILES):
.devcontainer.json, .devcontainer/Dockerfile, .devcontainer/devcontainer.json, .mise.toml, .node-version, .nvmrc, .python-version, .tool-versions, Cargo.lock, Gemfile.lock, Pipfile.lock, bun.lock, bun.lockb, composer.lock, flake.lock, go.sum, mise.toml, npm-shrinkwrap.json, package-lock.json, pnpm-lock.yaml, poetry.lock, rust-toolchain, rust-toolchain.toml, uv.lock, and yarn.lock.
Files outside this list (such as requirements.txt, build.gradle, and pom.xml) are not included in envHash.
Pooling, leases, and restore internals
Restored checkouts live at pooled paths under~/.atomic/agent/worktree-snapshots/worktrees/<repository>-<n>, with pool metadata in ~/.atomic/agent/worktree-snapshots/pool/ and shared per-repository Git object stores in ~/.atomic/agent/worktree-snapshots/repositories/.
Only checkouts sharing the same repository remotes share a pool. Checkouts without remotes are never pooled (so ignored files such as node_modules or .env cannot cross between unrelated projects); they restore into fresh worktrees each time, and atomic blueprint prebuild refuses them.
Worktree leases
An open session keeps its worktree reserved by refreshing its lease every 10 seconds:- Same host. A worktree held by a live process is never reclaimed. Linux and Windows verify both PID and process start time so reused PIDs after a reboot do not block reuse; macOS falls back to a 24-hour cap without a refresh.
- Other hosts sharing the pool. If a process stalls or exits abnormally on another host, the worktree remains reserved for 90 seconds after the last refresh before another host can claim or remove it.
- Lease verification. Before saving a snapshot or continuing in a pooled worktree, Atomic verifies the session still holds the lease. If another session claimed it meanwhile, capture skips and warns with
pooled-worktree-lost; stop editing there and run/resumeto open a fresh worktree.
Idle reuse, eviction, and set-aside worktrees
- Idle reuse. Restore reuses an idle pooled worktree that still matches its last recorded snapshot with no extra untracked or excluded files, resetting tracked files while preserving ignored directories (
node_modules,target,.venv) and preferring worktrees with a matchingenvHash./session snapshotmarks reused worktrees(claimed). - Eviction. When clean idle worktrees for a repository exceed
snapshots.pool.maxIdlePerRepository(default2,0keeps none; invalid values silently fall back to2without throwingWorkspaceConfigError), Atomic deletes the oldest clean idle ones. Worktrees with unrecorded edits or excluded files (such as.env) are never evicted. - Set-aside worktrees. If Atomic is killed (
SIGKILL) mid-blueprint build, the next resume marks that worktree set-aside under~/.atomic/agent/worktree-snapshots/pool/set-aside/so no session reuses it while build processes might still be running (see Start the first turn while the build runs). On Linux (/proc) and macOS (lsof), Atomic deletes set-aside pooled worktrees automatically on a later restore once no process owned by the current user holds open files or a working directory inside them. If another user’s or protected process blocks checking, on Windows (where open-file inspection conservatively assumes in-use, though job objects normally terminate child processes on exit), or for non-pooled worktrees, inspect open handles (lsof +D <path>on Unix) and remove the directory manually.
Object stores, SSH, LFS, and interrupted restores
- Shared object stores. Missing commits fetch shallowly (
--depth=1), falling back to a full fetch when needed; rungit fetch --unshallow originif you need full local history. Credential-free remotes are added asorigin,origin-2, and so on, and pushed commits receive refs underrefs/remotes/atomic/pushed/so later snapshots bundle only truly unpushed commits. - Non-interactive fetches. Unless
GIT_SSH_COMMAND,GIT_SSH, orcore.sshCommandis configured, SSH runs withBatchMode=yesand a 15-second connect timeout. Unknown host keys or locked SSH keys fail fast withcommits-unavailable(reason: "not-fetched"); rungit ls-remote <remote>once interactively and resume again. - Git LFS concurrency. Restores download missing LFS objects across recorded remotes without prompting. During a session resume, at most 2 LFS downloads run in parallel per session resume (
LFS_DOWNLOAD_CONCURRENCY = 2, enforced in memory per resume rather than cross-process per host). A checkout’s blueprint and first prompt (or first tool call underresume.waitForBlueprint: "tools") wait until its download finishes, and a second resume waits up to 10 minutes for an in-flight download. Unavailable LFS objects stay as pointer files with anlfs-objects-unavailablewarning; push them withgit lfs push --all <remote>orgit lfs push --object-id <remote> <oid>and resume again. - Interrupted restores. Restores stage and verify worktrees before publishing them. If a process dies mid-restore, the next restore cleans up staging records under
~/.atomic/agent/worktree-snapshots/restores/once their lock is 30 seconds stale without deleting files it did not create. Any retained leftover emitsstale-restore-retainedonce withkind("worktree","record", or"records-directory"). - Security checks. Before invoking Git, Atomic validates snapshot IDs, hashes, and remotes. Unsafe values (embedded credentials, leading
-, control characters, or Git remote helpers such asext::) fail withinvalid-snapshot.
Partial restore recovery
Only three errors refuse a session resume: an unreadable session,invalid-snapshot, or unsafe-target. Working directories reached through symlinks compare by their resolved physical path.
When an exact restore fails with a degradable error (blob-missing, blob-corrupt, commits-unavailable, delta-failed, or tree-mismatch), Atomic records restore.degraded (or unrestored if no commit is reachable) on the worktree_snapshot entry and pins the original snapshot ID in degradedFrom on subsequent captures in that worktree for up to 30 days.
On a later resume:
- Full restore succeeds with local partial-restore edits. Atomic applies the partial-restore edits on top as a single patch, records
restore.degradedWorkwithoutcome: "applied", shows an info notice, and captures a fresh snapshot immediately, releasing the old target. - Carried-over edits conflict. Atomic leaves the restored worktree at the original snapshot, saves the conflicting edits under
refs/atomic/degraded-work/<snapshot>, recordsrestore.degradedWorkwithoutcome: "kept", retains those blobs for 30 days (or until discarded), and prints agit diff ... | git apply --3waycommand. - Carried-over edits are unavailable. If edits made in the partial worktree cannot be read on this machine (for example, unpushed commits made there), Atomic records
outcome: "unavailable", reports them, leaves them in the partial worktree, and clears the original target. - Full restore still fails. Atomic restores the partial worktree’s latest snapshot so new work stays intact, warns that the original is still unreachable, and keeps retrying.
discardDegradedRestore()—the partial worktree’s latest snapshot becomes the active restore target and degradedFrom clears on the next capture.
Snapshot refs in your repository
Every snapshot is also written as a Git commit in the checkout’s repository and kept reachable atrefs/atomic/snapshots/<session-id>/<checkout> so git gc and git maintenance do not prune it, and resume recognizes your local checkout even after further edits.
- Each new snapshot advances the ref so at most one snapshot commit stays alive per session and checkout.
- Moving work to or from a restored worktree deletes the old ref once a snapshot is captured in the new location.
- Deleting a session through
/resumeorSessionManager.deleteSession()deletes its local refs along with refs of its non-running subagents.
git gc later prunes that commit and the checkout drifted, resume restores into a fresh worktree).
Snapshot refs sit outside refs/heads and refs/tags, so git push, git push --all, git push --tags, and snapshot bundles ignore them. Avoid git push --mirror if you do not want to push snapshot commits.
Exclude snapshot commits from git log --all:
SessionStore.delete()):
Retention and garbage collection
Snapshot blobs live in one shared table per database and are garbage-collected automatically when no retained session references them:- Retained snapshots. For every branch of every session (including internal subagent sessions), Atomic retains the latest snapshot of each checkout on that branch. Deleting a session releases its snapshots. A partly restored snapshot remains retained for up to 30 days. Unfinished workflow runs left from earlier releases retain their snapshots until removed.
- Background schedule. When
snapshots.autoCollectistrue, Atomic triggers collection in the background 10 seconds after an interactive or RPC session starts and 10 seconds after it closes, at most once persnapshots.collectIntervalSecondsper database (measured on the database clock). Collection sweeps in short batches so the UI stays responsive, aborts cleanly when the last store on the database closes, and resumes later if interrupted. - Grace window. Blobs stored or reused within
snapshots.graceSeconds(default 1 hour) are never deleted, protecting captures in progress. Reusing an earlier patch refreshes its age; if a blob is collected before its snapshot commits, Atomic retries storing it or reportsblobs-collectedwithout recording a broken snapshot. Raisesnapshots.graceSecondsifblobs-collectedrepeats. - Failures and disk space. Collection errors never fail an active session; they are recorded in the
snapshot_collectiontable (finished_at,deleted,error_code) and retried after the configured interval. SQLite reuses freed pages internally without shrinking the file; runVACUUMwhile no Atomic process uses the database to reclaim disk space.
Older SQLite chunk-table migration (
pendingChunkMove). Earlier local SQLite databases stored snapshot chunks in an older table layout. When background collection skips the live table migration (for example because free disk space is low), collectSnapshotGarbage() reports pendingChunkMove so you can run the offline migration with atomic storage move-snapshot-chunks. Because SQLite’s ALTER TABLE RENAME validates every view and trigger in the database, any broken custom view or trigger referencing renamed or missing tables causes the migration to fail with a hint naming the offending object—drop or fix it, then re-run. See Moving snapshot data in an old SQLite file.SDK
Open aSqliteDatabase handle with openNodeSqliteDatabase() or openPostgresDatabase() (see SDK session storage and SQLite storage), then open a SqlSnapshotBlobStore on that database:
SqlSnapshotBlobStore.open(database, prefix?) takes prefix as an optional positional string (unlike SqlSessionStore.open(database, { prefix }), which takes an options object). SqlSnapshotBlobStore does not own database and has no close() method; close your caller-owned database in a finally block after snapshot operations and any running garbage collection finish.
In createAgentSession({ snapshots }), pass partial snapshot settings to override settings.json for one session.
Capture, restore, and verification
captureWorktreeSnapshot(dir, { settings?, previous?, blobs?, signal? }): resolves tocaptured,unchanged,disabled, orunavailablewith a typedGitUnavailableErrororWorkspaceSnapshotError.restoreWorktreeSnapshot(bindingOrSnapshot, { into?, blobs?, snapshots?, storeDir?, onWarning?, deferLfs?, signal?, git? }): resolves to the path of a new verified worktree (intomust be new or empty). Checks the target and blobs before writing, cleans up on failure, emitsomitted-content,filters,lfs-objects-unavailable, andstale-restore-retainedwarnings toonWarning, and optionally hands off exact-restore Git LFS pulls todeferLfs(worktree, pull).restoreWorktree(bindingOrSnapshot, options?): same asrestoreWorktreeSnapshot(), resolving the fullRestoredWorktreeobject ({ path, snapshot, binding, warnings }).restoreDegradedWorktree(snapshot, failure, { blobs?, storeDir?, candidates?, onWarning?, signal?, git? }): restores the closest reachable state after a degradableWorkspaceRestoreErroraccepted byisDegradableRestoreFailure(blob-missing,blob-corrupt,commits-unavailable,delta-failed, ortree-mismatch). Resolves{ path, degraded, warnings }.restoreBestWorktree(snapshot, { blobs?, storeDir?, candidates?, signal?, git? }): runs exact restore followed by degraded restore, resolving{ status: "restored", path, warnings, degraded? }or{ status: "unrestored", reason }. Rejects only oninvalid-snapshot,unsafe-target, abort, or untyped errors. Pair withunrestoredRecord(snapshot, reason, continuedIn, place)to build aWorktreeUnrestoredentry.verifyWorktree(binding, dir, { settings?, signal? }): resolves to the checkout’s current binding whenHEADand tree match, or rejects withWorkspaceDriftError.isHeadOnlyAdvance(driftError, signal?): resolvestruewhenWorkspaceDriftErrorreflects onlyHEADadvancing over the same recorded tree.bindingOf(snapshot): extracts{ remotes, head, tree, envHash }from aWorktreeSnapshot.computeEnvironmentHash(root)andENVIRONMENT_INPUT_FILES: compute the 25-fileenvHashor inspect the input file list.canonicalizeWorktreePath(path)andcanonicalizeWorktreePathAsync(path): resolve symlinks in the existing portion of a path so paths compare consistently with snapshot roots.defaultWorktreeSnapshotStoreDir(agentDir?): return the default host snapshot store directory (<agentDir>/worktree-snapshots).removeRestoredWorktree(path, { storeDir?, onWarning?, signal? }): remove a worktree created by Atomic restore (for rolling back multi-checkout restores); rejects any non-restored path withunsafe-target.MemorySnapshotBlobStore,snapshotBlob(data), andsnapshotBlobHashes(snapshot): in-memory blob store (for tests or prebuild), content-hash blob helper, and blob-hash extraction.resolveWorktreeSnapshotSettings(input, source, prefix, base?),DEFAULT_WORKTREE_SNAPSHOT_SETTINGS,SNAPSHOT_DENY_PATTERNS,SNAPSHOT_KEY_FILE_PATTERNS,SNAPSHOT_IGNORE_FILE, andsetWorktreeSnapshotGit(resolver): settings validation, policy constants, and custom Git executable resolution.
Session resume and partial restores
openSessionInWorktree(sessionManager, { settings, storeDir?, signal?, beforeRecord?, pendingMappings?, keepInPlace?, cannotRestore?, fallbackCwd?, skipMissingRecords? }): checks every recorded checkout and restores drifted or missing ones without running blueprints, resolving{ sessionManager, notices, unrestored, missingRecords }.resumeSessionWorktreeperforms the same restore without reopening the session. For standard SDK resume with blueprints, passsessionManagerdirectly tocreateAgentSession({ sessionManager })(see Worktree snapshots in the SDK).discardDegradedRestore(sessionManager, { settings, root?, signal? }): records each partly restored worktree (or onlyroot) withoutdegradedFromso it becomes the active restore target and releases the original snapshot on the next collection.degradedRestorePin(sessionManager, root): returns{ snapshotId, since, base?, lapsed, work?, kept? }for a checkout with an active partial-restore target, orundefinedotherwise.withWorktreeRestoreNotices(notices, work)andcurrentWorktreeRestoreNotices(): scopeworktree_restoresystem prompt notices across sessions opened insidework.
Reading older snapshots on demand
Sessions opened at the default tail window load only the snapshot records needed for resume into memory. UsesessionManager.readWorktreeSnapshotPages() and sessionManager.loadWorktreeSnapshotRecords() (see SessionManager API) to inspect older snapshots on demand:
Garbage collection
collectSnapshotGarbage(blobs, { graceSeconds?, signal? }): deletes eligible unreferenced blobs from aSqlSnapshotBlobStore(defaultgraceSecondsisDEFAULT_BLOB_GRACE_SECONDS, 1 hour) and resolves{ deleted, pendingChunkMove? }. Rejects non-SQL stores withblob-store-unsupported.scheduleSnapshotCollection(blobs, settings, { onFailure?, delayMs? }): starts background collection whensettings.autoCollectis enabled and due (sessions passSNAPSHOT_COLLECTION_SESSION_DELAY_MS, 10 seconds). Never rejects after validating settings; resolves withcollected,skipped,interrupted, orfailed, and does not keep an idle process alive.runningSnapshotCollection(blobs): returns a promise settling when the current process’s active collection finishes, orundefinedif none is running.
Errors
Every workspace error exceptGitUnavailableError extends WorkspaceError. Each error carries a stable code, JSON-safe fields, a hint, a summary, and retryable.
- Among snapshot and restore errors below,
WorkspaceCollectionErrorsetsretryable: true;WorkspaceConfigError,WorkspaceGitError,WorkspaceSnapshotError,WorkspaceRestoreError, andWorkspaceDriftErrorsetretryable: false. - Across the broader
WorkspaceErrorhierarchy (also used by workspace binding and pull-request publication),WorkspaceTimeoutErroralways setsretryable: true, andWorkspaceBindingError(onwriter-conflict,addition-in-progress, clone/fetch/push Git failures, and retryable filesystem errnos) andWorkspacePublicationError(onpush-failedandgh-failed) setretryable: trueconditionally.
error.retryable or isRetryableWorkspaceError(error) and branch on class or code, never on message text. Use findWorkspaceError(error, guard) to inspect cause chains up to 8 levels deep, and serializeWorkspaceError / rehydrateWorkspaceError to preserve typed errors across process boundaries.