# env

> Package env defines the Environment port: where zelk's tools act.

<!-- Generated from the Go source of github.com/barevoidco/zelk/core/env (cmd/zelk/internal/reference TestReferenceGoAPI). Don't edit: change the code, then run make reference. -->

```go
import "github.com/barevoidco/zelk/core/env"
```

Package env defines the Environment port: where zelk's tools act. An Environment runs processes, reads and writes files with revisions, globs and greps, and reports what it actually enforces.

FileRestorer optionally plans and applies confirmed file-only restores within the same confinement; sessions own confirmation and durable progress. FileObserver optionally reads the current versions of named files, which checkpoints save before the session's tools change them (docs/design/checkpoints.md).

The local implementation is in env/local. Hosts can bring their own, such as a remote sandbox, and declare its enforcement honestly: a requirement an environment can't meet is a construction error, never a silent downgrade.

**Example (optionalCapabilities)**

```go
var e env.Environment // an environment without a ProcessReconciler
msg, err := reconcile(context.Background(), e, lease.Token{})
fmt.Println(msg, err)
// Output: processes may still be running; their calls are outcome unknown <nil>
```

Output:

```text
processes may still be running; their calls are outcome unknown <nil>
```


## Constants

```go
const (
	MaxMaterializeFiles    = event.MaxMaterializeFiles
	MaxMaterializeBytes    = event.MaxMaterializeBytes
	MaxMaterializeMetadata = event.MaxMaterializeMetadata
)
```

Materialization bounds apply before any filesystem work. Implementations may impose tighter limits and must also bound their total retained storage.


## Variables

```go
var (
	// ErrFenced refuses a stale environment authority before it acts.
	ErrFenced = errors.New("stale environment fence")
	// ErrNotDispatched marks an error after which the operation provably
	// did nothing, such as a process that was refused before it started.
	// A remote environment that can't tell whether a request arrived must
	// not use it.
	ErrNotDispatched = errors.New("operation not dispatched")
	// ErrStale is returned by WriteFile when the file's revision isn't the
	// one the write expected: something changed it since it was read.
	ErrStale = errors.New("file changed since it was read")
	// ErrExists is returned by WriteFile with IfRevision NoFile when the
	// file already exists.
	ErrExists = errors.New("file already exists")
	// ErrOutsideWorkspace is returned for a path that leaves the
	// environment's workspace.
	ErrOutsideWorkspace = errors.New("path is outside the workspace")
	// ErrNotRegular is returned for a path that names something other than
	// a regular file, such as a device or a FIFO.
	ErrNotRegular = errors.New("not a regular file")
	// ErrTooLarge is returned for a file, or data to write, bigger than
	// the environment's size bound. Bounds are checked before acting, so
	// the environment never reads or writes part of what it refuses.
	ErrTooLarge = errors.New("file exceeds the environment's size bound")
	// ErrNotFound is returned by ProcessReconciler.Lookup for a process
	// that is gone.
	ErrNotFound = errors.New("not found")
	// ErrProcessUnobservable means this backend cannot establish the state of
	// a recorded process.
	ErrProcessUnobservable = errors.New("process cannot be observed by this host")
	// ErrUnenforced is returned by Enforcement.Require when the
	// environment can't meet a required level.
	ErrUnenforced = errors.New("required enforcement not available")
)
```

Errors from an environment say whether the operation had an effect, which decides how the tool calling it is recorded: an error for which NoEffect is true means the operation provably did nothing, and any other error means it may have acted.

```go
var ErrMaterializeQuota = errors.New("materialized storage quota exceeded")
```

ErrMaterializeQuota reports a backend's retained-storage limit. It does not imply that an interrupted attempt left no owned staging data.


## NoEffect

```go
func NoEffect(err error) bool
```

NoEffect reports whether err means the operation provably did nothing: it wraps ErrNotDispatched, or a refusal checked before acting (ErrStale, ErrExists, ErrOutsideWorkspace, ErrNotRegular, ErrTooLarge, ErrFenced). A nil error is an operation that acted.

**Example**

```go
// A write refused because the file changed since it was read did
// nothing, so the tool call can be reported as not dispatched.
err := fmt.Errorf("write main.go: %w", env.ErrStale)
fmt.Println(env.NoEffect(err))
fmt.Println(env.NoEffect(errors.New("connection reset")))
// Output:
// true
// false
```

Output:

```text
true
false
```


## BundleReleaser

```go
type BundleReleaser interface {
	ReleaseBundle(ctx context.Context, bundle MaterializeBundle) error
}
```

BundleReleaser optionally releases a session's complete and interrupted publications directly from recorded bytes. It must validate the bundle and remove only matching owned paths, preserving unknown or changed data. Absent artifacts succeed. It must not allocate a replacement publication, so cleanup remains possible when storage is full. Repeating after cancellation or a lost acknowledgment completes cleanup safely. Calls honor ctx and are concurrency safe. Fence must be enforced before acting. The host first ensures no live session or process uses the bundle.

Session-end cleanup requires this capability in addition to Materializer; releasing only successful receipts can miss an interrupted publication.


## Cell

```go
type Cell struct {
	Level Level
	Note  string
}
```

Cell is one operation and dimension's level, with a note saying how it holds or why it doesn't.


## Cmd

```go
type Cmd struct {
	// Path is the executable's absolute path, or its name with SearchPath.
	Path string
	// SearchPath permits name lookup using Env. The local environment
	// searches only absolute PATH entries and omits workspace executables.
	SearchPath bool
	// Args are the arguments after the program name, which is Path.
	Args []string
	// Dir is the working directory, relative to the workspace.
	Dir string
	// Env is the whole environment, as KEY=value pairs. Nothing is
	// inherited from the host process.
	Env []string
	// Stdin is written to the process's standard input before it is
	// closed; use Proc.Write for interactive input instead.
	Stdin []byte
	// DiscardStderr discards the process's standard error instead of
	// combining it with its standard output, for a protocol server, such
	// as an MCP server, whose standard output must stay a clean stream.
	DiscardStderr bool
	// Stderr, if set with DiscardStderr, receives the process's standard
	// error as it is written instead of the null device, so a host sees
	// why a protocol server failed. Writes come from a goroutine of the
	// environment's and must not block for long. An environment that
	// can't keep the stream apart discards it.
	Stderr io.Writer
	// KeepHead and KeepTail bound the output the environment keeps: the
	// first KeepHead bytes are kept until the process is gone, however
	// late they are read, and of the rest only the latest KeepTail bytes
	// are. Output between the two is dropped and counted, so memory stays
	// bounded while a caller can still show a head and tail preview and
	// page through everything up to KeepHead. Zero means the environment's
	// default for each.
	KeepHead, KeepTail int64
	// Fence tags the process with the lease token of the driver that
	// started it, so a process reconciler can find it after a crash.
	Fence lease.Token
	// Scratch is an absolute directory on the environment's host that the
	// process may write whatever confines it, such as the session's
	// scratch directory. The environment makes it if missing. It isn't
	// the process's TMPDIR: that stays the one Env gives, or a sandbox's
	// own, so commands see the temporary root they see outside zelk.
	Scratch string
}
```

Cmd describes a process to start.


## Cursor

```go
type Cursor int64
```

Cursor is an offset into a process's combined output.


## Differ

```go
type Differ interface {
	Baseline(ctx context.Context) (json.RawMessage, error)
	Diff(ctx context.Context, baseline json.RawMessage) (event.WorkspaceDelta, error)
}
```

Differ is an optional capability for bounded workspace changes. Baseline returns self-contained JSON, at most 512 KiB, persisted before dispatch. Diff compares it with current files. Implementations must be concurrency-safe, honor cancellation and report exclusions and incomplete coverage. Observed changes may include other editors or background processes.


## Dimension

```go
type Dimension int
```

Dimension is a kind of protection.

```go
const (
	FSRead Dimension = iota
	FSWrite
	Network
	CredentialIsolation
	ProcessVisibility
	Resources
	// Offline is enforced when commands can reach no network at all, not
	// even hosts an allowlist names, where Network is enforced for an
	// allowlist too.
	Offline
)
```

The dimensions an environment reports on.


### Dimensions

```go
func Dimensions() []Dimension
```

Dimensions lists every dimension.


### Dimension.String

```go
func (d Dimension) String() string
```


### Dimension.Valid

```go
func (d Dimension) Valid() bool
```

Valid reports whether d is one of the defined dimensions.


## Enforcement

```go
type Enforcement struct {
	// contains filtered or unexported fields
}
```

Enforcement reports, per operation and dimension, what an environment enforces. The zero value claims nothing. It is a value: copies are independent, so a published profile can't be altered.


### NewEnforcement

```go
func NewEnforcement() Enforcement
```

NewEnforcement returns a matrix that claims nothing.


### Enforcement.Cell

```go
func (e Enforcement) Cell(op Operation, dim Dimension) Cell
```

Cell returns one operation and dimension's level. An undefined op or dim names no cell and claims nothing: the zero Cell.


### Enforcement.Require

```go
func (e Enforcement) Require(reqs ...Requirement) error
```

Require returns an error wrapping ErrUnenforced, listing every requirement e falls short of, or nil if it meets them all. A requirement naming an undefined operation, dimension or level is an error, and a cell with an undefined level meets nothing, so an invalid value fails closed.

**Example**

```go
// What a launcher might publish: file reads jailed to the workspace,
// network only advisory.
published := env.NewEnforcement().
	With(env.FileRead, env.FSRead, env.Enforced, "path jail").
	With(env.Exec, env.Network, env.Advisory, "proxy, bypassable")

err := published.Require(
	env.Requirement{Op: env.FileRead, Dim: env.FSRead, Min: env.Enforced},
	env.Requirement{Op: env.Exec, Dim: env.Network, Min: env.Enforced},
)
fmt.Println(errors.Is(err, env.ErrUnenforced))
fmt.Println(err)
// Output:
// true
// required enforcement not available: exec/network needs enforced, have advisory
```

Output:

```text
true
required enforcement not available: exec/network needs enforced, have advisory
```


### Enforcement.With

```go
func (e Enforcement) With(op Operation, dim Dimension, level Level, note string) Enforcement
```

With returns a copy of e with one cell set. An undefined op or dim names no cell, so e is returned unchanged; a level that isn't valid is kept, and never meets a requirement.


## Environment

```go
type Environment interface {
	// Start starts a process.
	Start(ctx context.Context, cmd Cmd) (Proc, error)
	// ReadFile reads at most opt.MaxBytes of a file from opt.Offset, with
	// the revision of the whole file at the time of the read.
	ReadFile(ctx context.Context, path string, opt ReadOpt) (File, error)
	// WriteFile replaces a file's contents if its revision is still
	// opt.IfRevision, or creates it if opt.IfRevision is NoFile, and
	// returns the new revision. A mismatch is ErrStale or ErrExists.
	WriteFile(ctx context.Context, path string, data []byte, opt WriteOpt) (Revision, error)
	// Glob lists files matching a pattern, at most q.Limit of them.
	Glob(ctx context.Context, q GlobQuery) (GlobResult, error)
	// Grep searches file contents, returning at most q.Limit results.
	Grep(ctx context.Context, q GrepQuery) (GrepResult, error)
	// Enforcement reports what the environment enforces, per operation and
	// dimension.
	Enforcement() Enforcement
}
```

Environment is where tools act. Implementations must be safe for concurrent use and honour ctx. Paths are relative to the environment's workspace, with forward slashes.


## Exit

```go
type Exit struct {
	// Code is the exit status, or -1 if a signal ended the process.
	Code int
	// Signal names the signal that ended the process, if one did.
	Signal string
}
```

Exit is how a process ended.


## File

```go
type File struct {
	// Data is the file's content from the read's Offset.
	Data []byte
	// Revision is the whole file's revision when the page was read. Pages
	// with the same revision come from the same content.
	Revision Revision
	// Size is the whole file's size; Truncated reports that the file goes
	// on after Data.
	Size      int64
	Truncated bool
}
```

File is a page of a file.


## FileObserver

```go
type FileObserver interface {
	ObserveFiles(ctx context.Context, paths []string) ([]FileVersion, error)
}
```

FileObserver optionally reads the current versions of named workspace files, for checkpoints (docs/design/checkpoints.md). It reads only the paths it is given, through the Environment's confinement, without following symlinks. A path that can't be saved, such as a symlink, a hard link, a file larger than event.MaxCheckpointFileBytes or one outside the workspace, is reported as skipped with a reason, not as an error; an error means the observation as a whole failed. Methods are safe for concurrent use and honor cancellation.


## FileRestorer

```go
type FileRestorer interface {
	RestoreFile(context.Context, event.FileRestoreChange, []byte) error
}
```

FileRestorer optionally applies file-only restores within an Environment's confinement: RestoreFile writes or deletes one file, only if it is still as the change's Before says, refuses symlinks and restores the recorded executable bit. Methods are safe for concurrent use and honor cancellation; external writers can still race a local filesystem check.


## FileVersion

```go
type FileVersion struct {
	event.FileVersion
	Data []byte
}
```

FileVersion is an observed path's version and, when it was saved, its content.


## Fingerprinter

```go
type Fingerprinter interface {
	Fingerprint(ctx context.Context) (string, error)
}
```

Fingerprinter is an optional capability: a digest of the workspace's files, to tell whether a command changed them. It returns "" when it can't cover every file a change could reach, and must be concurrency-safe and honor cancellation.


## GlobQuery

```go
type GlobQuery struct {
	// Pattern is matched against each file's whole path relative to Dir,
	// in the portable glob language of docs/design/tools.md.
	Pattern string
	// Dir is where to search, relative to the workspace: a directory, or a
	// regular file, which is searched alone whatever Include says.
	Dir string
	// Limit is the most paths to return; zero means the environment's
	// default.
	Limit int
}
```

GlobQuery asks for files matching a pattern.


## GlobResult

```go
type GlobResult struct {
	// Paths are relative to the workspace, not to Dir.
	Paths []string
	// Truncated reports that more files matched than Limit, or that the
	// environment stopped at one of its own bounds before searching
	// everything.
	Truncated bool
}
```

GlobResult lists matched files, most recently modified first, then by path: the order is deterministic.


## GrepQuery

```go
type GrepQuery struct {
	// Pattern is an RE2 regular expression, matched against each line
	// without its newline; it never matches across lines.
	Pattern string
	// Dir is where to search, relative to the workspace.
	Dir string
	// Include limits the search to files matching this glob: against the
	// file's name if it has no slash, otherwise against its path relative
	// to Dir.
	Include         string
	CaseInsensitive bool
	// Context is how many lines before and after each match to include.
	Context int
	// Limit is the most matches to return; zero means the environment's
	// default.
	Limit int
	// MaxLineBytes is the most of any one line, matched or context, to
	// return; longer lines are cut. With Limit and Context it bounds the
	// whole result, however long the lines in the files. Zero means the
	// environment's default.
	MaxLineBytes int
}
```

GrepQuery asks for file contents matching a regular expression, with the portable semantics of docs/design/tools.md.


## GrepResult

```go
type GrepResult struct {
	Matches []Match
	// Truncated reports that more matches were found than Limit, or that
	// the environment stopped at one of its own bounds before searching
	// everything.
	Truncated bool
	// File reports that Dir named a regular file, searched alone.
	File bool
}
```

GrepResult lists matching lines in a deterministic order: files as a depth-first walk visits them, each directory's entries in byte order of their names, and lines in order within a file.


## Level

```go
type Level int
```

Level is how strongly a protection holds. Levels are ordered.

```go
const (
	// None: nothing stops the action.
	None Level = iota
	// Advisory: checked, but a determined process can get around it.
	Advisory
	// Enforced: the environment prevents it.
	Enforced
)
```

The levels, weakest first.


### Level.String

```go
func (l Level) String() string
```


### Level.Valid

```go
func (l Level) Valid() bool
```

Valid reports whether l is one of the defined levels.


## Match

```go
type Match struct {
	// Path is relative to the workspace, not to Dir.
	Path string
	// Line is the 1-based number of the matching line.
	Line   int
	Text   string
	Before []string
	After  []string
	// Cut reports that Text or a context line was cut at MaxLineBytes.
	Cut bool
}
```

Match is a matching line, with its context. Each match carries its own context, so lines near two matches appear in both.


## Materialization

```go
type Materialization struct {
	// Fence is the authority that received this receipt, for direct Release.
	Fence    lease.Token `json:"fence,omitzero"`
	Identity string      `json:"identity"`
	Dir      string      `json:"dir"`
	Bytes    int64       `json:"bytes"`
}
```

Materialization is a receipt for one complete owned publication. Identity is the bundle's validated Identity, Dir is its environment-visible directory, and Bytes counts file contents, excluding metadata. A receipt is not proof that its directory still exists or remains unchanged: resume must verify it.


## MaterializeBundle

```go
type MaterializeBundle struct {
	// Fence is the current session authority. Backends serialize operations and
	// reject fences older than one already observed for this session. The zero
	// token is for standalone, unfenced use only; it cannot downgrade a fenced
	// session. Fence does not change the immutable content identity.
	Fence   lease.Token
	Session string
	Key     string
	Files   []MaterializeFile
}
```

MaterializeBundle binds recorded files to a session and durable effect key. Keys identify publications, not arbitrary destination paths. The driver reads Data from recorded blobs; it must not reload a skill's current source files.


### MaterializeBundle.Identity

```go
func (b MaterializeBundle) Identity() (string, error)
```

Identity validates the entire bundle and returns its canonical SHA-256 identity, including session ownership, effect key, paths, sizes and digests. File order does not affect it. Validation bounds contents and encoded metadata, rejects unsafe paths and file/directory collisions, and verifies bytes against every recorded digest. It performs no I/O.

**Example**

```go
data := []byte("echo hello\n")
bundle := env.MaterializeBundle{
	Session: "session-1", Key: "materialize-effect-1",
	Files: []env.MaterializeFile{{Path: "scripts/hello.sh", Digest: blob.Digest(data), Data: data}},
}
identity, err := bundle.Identity()
fmt.Println(strings.HasPrefix(identity, "sha256:"), err)
// Output: true <nil>
```

Output:

```text
true <nil>
```


## MaterializeFile

```go
type MaterializeFile struct {
	Path   string
	Digest string
	Data   []byte
}
```

MaterializeFile is a regular file from a recorded content-addressed bundle. Data belongs to the caller and must not be changed during Materialize. Backends must not retain it after returning. Symbolic links are not supported.


## Materializer

```go
type Materializer interface {
	Materialize(ctx context.Context, bundle MaterializeBundle) (Materialization, error)
	Release(ctx context.Context, publication Materialization) error
}
```

Materializer optionally publishes recorded skill bundles in an Environment. Implementations must be safe for concurrent use and honor cancellation. Materialize verifies every digest before writing and atomically commits a complete read-only directory before returning its path. A retry may reuse a publication only after verifying all its bytes. Staging data in the reserved cache may be incomplete until commit. Dir must be usable by the environment's file and process operations, and must remain stable for the same bundle across resume/recreation. Publication grants no execution permissions and does not replace the normal skill-script hash checks or launcher confinement.

Release removes only an exactly identified owned publication, never unknown files. It is idempotent when the publication is absent. Suspension is not a reason to release; a later Materialize must recreate an absent publication from the supplied recorded bytes without consulting the original source. Hosts coordinate live references before Release. Neither operation may use unvalidated session/key strings as filesystem paths.


## MaterializerNamespace

```go
type MaterializerNamespace interface {
	MaterializationNamespace() string
}
```

MaterializerNamespace optionally identifies a backend's stable publication namespace. The SHA-256 digest binds storage and its Environment-visible mapping across resume and cleanup; it must not depend on transient inodes or leases. The driver refuses a different or missing namespace before dispatch. Backends without this capability retain the host's obligation to inject the same store.


## Operation

```go
type Operation int
```

Operation is a kind of action an environment performs.

```go
const (
	Exec Operation = iota
	FileRead
	FileWrite
)
```

The operations an environment reports on.


### Operations

```go
func Operations() []Operation
```

Operations lists every operation.


### Operation.String

```go
func (o Operation) String() string
```


### Operation.Valid

```go
func (o Operation) Valid() bool
```

Valid reports whether o is one of the defined operations.


## Output

```go
type Output struct {
	Data []byte
	// Next is where the next read continues.
	Next Cursor
	// Dropped counts bytes between the requested cursor and Data that
	// fell outside KeepHead and KeepTail and are gone.
	Dropped int64
	// Done reports that the process has exited and all its output has been
	// read.
	Done bool
}
```

Output is a page of process output.


## OutsideFiles

```go
type OutsideFiles interface {
	Glob(ctx context.Context, q GlobQuery) (GlobResult, error)
	Grep(ctx context.Context, q GrepQuery) (GrepResult, error)
	Close() error
}
```

OutsideFiles searches files under a directory outside the workspace, by slash-separated names relative to it, as Environment does under the workspace. It reads nothing else: no file outside the workspace is one a session edits.


## OutsideReader

```go
type OutsideReader interface {
	// ReadOutside is ReadFile for the clean absolute path name, which may
	// lie anywhere on the environment's filesystem. It reads no more than
	// the environment's commands could: where they are confined, it
	// refuses with an error wrapping ErrOutsideWorkspace.
	ReadOutside(ctx context.Context, name string, opt ReadOpt) (File, error)
}
```

OutsideReader is an optional capability, detected with a type assertion, of an environment that can read a file outside its workspace. The Read tool uses it only for an absolute path the session's permissions allowed it to read, such as a plot a command wrote to /tmp in bypass mode (docs/design/permissions.md). An environment without it, such as a client's, keeps file reads in the workspace.


## OutsideSearcher

```go
type OutsideSearcher interface {
	// OpenOutside returns searches confined to dir, an existing clean
	// absolute directory that may lie anywhere on the environment's
	// filesystem. It searches no more than the environment's commands
	// could read: where they are confined, it refuses with an error
	// wrapping ErrOutsideWorkspace. The caller closes what it returns.
	OpenOutside(ctx context.Context, dir string) (OutsideFiles, error)
}
```

OutsideSearcher is an optional capability, detected with a type assertion, of an environment that can search a directory outside its workspace. Glob and Grep use it, as Read uses OutsideReader, only for an absolute path the session's permissions allowed them to read, such as a dependency's source in a module cache.


## PersistentProcesses

```go
type PersistentProcesses interface {
	StartPersistent(ctx context.Context, key string, cmd Cmd) (Proc, error)
	Lookup(ctx context.Context, id ProcID) (Proc, error)
	Root() string
	Enforcement() Enforcement
}
```

PersistentProcesses is an explicitly supplied, independently owned process supervisor. It retains generation-safe identity, stdin and bounded output when an Agent/client closes. The host must keep the supervisor alive and confined to Root; a supervisor restart may report jobs lost, but must never identify a new process as an old one. Processes must not be relaunched from Lookup. Methods must be safe for concurrent use. The host owns the supervisor.


## Proc

```go
type Proc interface {
	// Write writes to the process's standard input.
	Write(ctx context.Context, p []byte) (int, error)
	// Read returns output from cursor on, waiting up to yield for some to
	// arrive. Output is paged and bounded; output that was kept stays
	// readable after the process exits or is killed, until Close.
	Read(ctx context.Context, from Cursor, yield time.Duration) (Output, error)
	// Wait waits for the process to exit. A cancelled ctx stops the
	// waiting, not the process.
	Wait(ctx context.Context) (Exit, error)
	// Kill kills the process's group; the whole tree only where the
	// launcher contains it.
	Kill(ctx context.Context) error
	// Close kills the process if it is still running and releases what
	// the environment keeps for it, its output included. Every process
	// must be closed.
	Close() error
	// ID identifies the process, including a generation, never a bare PID.
	ID() ProcID
}
```

Proc is a running or finished process.


## ProcID

```go
type ProcID string
```

ProcID identifies a process, even after its PID is reused. No two processes get the same ID, in this environment or in any other whose processes a shared store records: hosts that share sessions tell processes apart by it. An environment includes something no other gives, such as a random generation, rather than counting from one.


## ProcessPresence

```go
type ProcessPresence interface {
	// ProcessGone reports true only when the backend can confirm that the
	// process no longer has an owner that can report its exit. IDs outside
	// the backend's observation scope leave the exit unknown.
	ProcessGone(ctx context.Context, id ProcID) (bool, error)
}
```

ProcessPresence is an optional capability for backends that can establish absence without reattaching a process. A false result leaves its exit unknown.


## ProcessReconciler

```go
type ProcessReconciler interface {
	// Lookup returns the process with the given ID, or an error wrapping
	// ErrNotFound if it is gone. ErrProcessUnobservable leaves the exit
	// pending when this backend cannot establish the process's state.
	Lookup(ctx context.Context, id ProcID) (Proc, error)
	// KillFenced kills every process started with the given fence.
	KillFenced(ctx context.Context, fence lease.Token) error
}
```

ProcessReconciler is an optional capability, detected with a type assertion, of an environment whose processes outlive the driver that started them. After a crash or takeover, the new lease holder looks processes up by ID, or kills those tagged with the old holder's fence before reconciling. Without it, processes from a dead holder may still be running, and reconciliation reports their tool calls as outcome unknown. The local environment doesn't have it.


## ReadOpt

```go
type ReadOpt struct {
	// Offset is the byte offset to read from.
	Offset int64
	// MaxBytes is the most to read; 0 means the environment's default.
	MaxBytes int64
}
```

ReadOpt bounds a read to a range of the file, so a caller can page through a large file without transferring what comes before the page.


## Requirement

```go
type Requirement struct {
	Op  Operation
	Dim Dimension
	Min Level
}
```

Requirement is a level a host requires for an operation and dimension.


## Revision

```go
type Revision string
```

Revision identifies a file's contents at a point in time. It is opaque: compare revisions for equality only.

```go
const NoFile Revision = "none"
```

NoFile is the WriteOpt.IfRevision of a write that creates a new file.


## ScratchFiles

```go
type ScratchFiles interface {
	ReadFile(ctx context.Context, name string, opt ReadOpt) (File, error)
	WriteFile(ctx context.Context, name string, data []byte, opt WriteOpt) (Revision, error)
	Glob(ctx context.Context, q GlobQuery) (GlobResult, error)
	Grep(ctx context.Context, q GrepQuery) (GrepResult, error)
	Close() error
}
```

ScratchFiles reads, writes and searches files under a scratch directory, by slash-separated names relative to it, as Environment does under the workspace: confined to it, with revisions and conditional writes.


## ScratchOpener

```go
type ScratchOpener interface {
	// OpenScratch returns file operations confined to dir, a clean
	// absolute directory on the environment's host, which it makes if
	// missing. The caller closes what it returns.
	OpenScratch(ctx context.Context, dir string) (ScratchFiles, error)
}
```

ScratchOpener is an optional capability, detected with a type assertion, of an environment whose file tools can reach a session's scratch directory: a directory on the environment's host outside the workspace, where the session keeps temporary files (zelk.WithScratch). An environment without it, such as a client's, keeps the file tools in the workspace; its commands may still use the directory.


## Snapshotter

```go
type Snapshotter interface {
	Snapshot(ctx context.Context) (TreeHash, error)
}
```

Snapshotter is an optional capability, detected with a type assertion, of an environment that can hash its workspace, so a session can record what the files looked like.


## TreeHash

```go
type TreeHash string
```

TreeHash identifies a workspace's contents. It is opaque: compare hashes for equality only.


## WriteOpt

```go
type WriteOpt struct {
	// IfRevision is the revision the file must still have, or NoFile for a
	// file that must not exist yet. It is required: writes never clobber
	// a file blind.
	IfRevision Revision
}
```

WriteOpt conditions a write.
