Skip to content
Source on GitHub (opens in a new tab)
import "github.com/barevoidco/zelk/core/env/local"

Package local is the local Environment: zelk’s tools act on a workspace directory on this machine.

File operations resolve every path beneath the workspace, with openat2 on Linux and an os.Root elsewhere, so a path, or a symbolic link on it, can’t leave the workspace. Each file has a revision (a hash of its contents plus its size, mtime and file identity), and writes are conditional on the revision the caller read: they go through a synced temporary file and an atomic rename, so a file changed since it was read is detected rather than overwritten. Every read and write is bounded; see Bounds and docs/design/tools.md.

FileRestorer plans regular-file restoration with current ignore rules and applies conditional synced writes/deletions through the same jail. Sessions own confirmation and the persisted restore transaction. FileObserver reads named files for checkpoints, without following symlinks or applying ignore rules, and skips what can’t be restored safely.

Processes run with a caller-supplied environment and bounded output. Unix owns commands in separate sessions. Windows owns commands in kill-on-close Job Objects. Batch files use cmd.exe from the command’s injected SystemRoot and are prepared before sandbox wrapping. For other programs, Windows supplies SystemRoot when it was omitted. Launcher resources such as MXC path pins are released once the job is empty. The default launcher runs with the user’s privileges. Process handles live only in this Env and can’t be recovered after the host process dies. Under a protecting launcher, linked-worktree processes also receive their validated common Git directory as an explicit writable root, with Git’s configuration, hooks and pointer inputs kept read-only. This does not broaden the workspace jail used by file operations.

const (
DefaultReadBytes = 1 << 20
DefaultFileBytes = 64 << 20
DefaultKeepHead = 1 << 20
DefaultKeepTail = 1 << 20
DefaultKeepBytes = 16 << 20
DefaultWalkEntries = 200_000
DefaultGlobLimit = 1000
DefaultGrepLimit = 1000
DefaultGrepLineBytes = 2000
DefaultGrepScanBytes = 512 << 20
DefaultGrepResultBytes = 8 << 20
)

The defaults for zero fields of Bounds.

const DefaultKillGrace = 2 * time.Second

DefaultKillGrace is how long Kill and Close wait, after asking a process to stop with SIGTERM, before they kill its group with SIGKILL.

func LookPath(ctx context.Context, name, path, pathExt, workspace string) string

LookPath finds a bare executable name in the supplied absolute PATH directories. Windows also uses the supplied PATHEXT. If workspace is set, paths within it are excluded, including through symlinks.

Example

dir, err := os.MkdirTemp("", "toolchain")
if err != nil {
panic(err)
}
defer os.RemoveAll(dir)
bin := filepath.Join(dir, "rg.exe")
if err := os.WriteFile(bin, nil, 0o700); err != nil {
panic(err)
}
// The host supplies the search directories and Windows extensions.
fmt.Println(local.LookPath(context.Background(), "rg.exe", dir, ".EXE", "") == bin)
// Output: true

Output:

true
type Bounds struct {
// ReadBytes is the page ReadFile returns when the caller gives no
// MaxBytes. Default 1 MiB.
ReadBytes int64
// FileBytes is the largest file ReadFile reads and WriteFile writes:
// a revision hashes the whole file, so a file over the bound is
// refused with env.ErrTooLarge rather than read in part. Default
// 64 MiB.
FileBytes int64
// KeepHead and KeepTail are how much of a process's output is kept
// when its Cmd doesn't say: the first KeepHead bytes and the latest
// KeepTail bytes after them. Default 1 MiB each.
KeepHead, KeepTail int64
// KeepBytes is the most a Cmd may ask to keep, head and tail
// together; Start refuses more with env.ErrTooLarge. Default 16 MiB.
KeepBytes int64
// WalkEntries is the most directory entries one Glob or Grep visits;
// past it the walk stops and the result is truncated. Default 200,000.
WalkEntries int
// GlobLimit is the most paths Glob returns when the query gives no
// Limit. Default 1,000.
GlobLimit int
// GrepLimit is the most matches Grep returns when the query gives no
// Limit. Default 1,000.
GrepLimit int
// GrepLineBytes is how much of a line Grep returns when the query
// gives no MaxLineBytes. Default 2,000.
GrepLineBytes int
// GrepScanBytes is the most one Grep reads; past it the search stops
// and the result is truncated. Default 512 MiB.
GrepScanBytes int64
// GrepResultBytes is the most line text one Grep returns, matches and
// context together; past it the search stops and the result is
// truncated. Default 8 MiB.
GrepResultBytes int
}

Bounds limit what the environment reads and writes, so no request can make it use unbounded memory or time. Every bound is enforced while reading, never by trimming a result that was read in full. A zero field takes its default (docs/design/tools.md lists them).

type Env struct {
// contains filtered or unexported fields
}

Env is the local environment: it acts on a workspace directory on this machine. File operations are confined to the workspace by resolving every path beneath it: with openat2 on Linux, an os.Root elsewhere; processes are not confined at all. An Env is safe for concurrent use. Close it when done.

func New(ctx context.Context, dir string, opts ...Option) (*Env, error)

New returns an environment acting on the workspace dir, which must be the absolute path of an existing directory: a relative one would depend on the host process’s working directory.

func (e *Env) Baseline(ctx context.Context) (json.RawMessage, error)

Baseline captures bounded content hashes under the workspace’s path jail. It excludes ignored/nonregular files and files larger than 1 MiB, scans at most 64 MiB and 2048 files, and bounds stored path/hash bytes to 256 KiB. The environment’s tighter traversal and file bounds still apply.

func (e *Env) Close() error

Close closes every process the environment started that is not closed yet, killing those still running, and releases the workspace directory. Operations after Close fail.

func (e *Env) Diff(ctx context.Context, baseline json.RawMessage) (event.WorkspaceDelta, error)

Diff compares a persisted Baseline with current content hashes. Missing paths are never reported as deleted when the current scan was incomplete or excluded them; an incomplete baseline never proves a file was newly created.

func (e *Env) Enforcement() env.Enforcement

Enforcement reports what the local environment enforces. Its own file operations resolve every path beneath the workspace, with openat2 on Linux (no escapes, magic links or mount crossings) or os.Root elsewhere, which resists traversal out of the workspace and nothing more. On Windows os.Root also refuses every junction and mount point, whose targets are absolute. Processes are confined by the environment’s launcher, whose profile is the Exec row: by default none, which confines nothing.

func (e *Env) Fingerprint(ctx context.Context) (string, error)

Fingerprint returns a digest of the workspace’s files, their names and contents, within Baseline’s bounds. Paths git ignores and the environment’s own cache are outside it. It returns “” when anything else is left out (a file too large, unreadable or changing, a scan cut short), since a change there would go unseen.

func (e *Env) Glob(ctx context.Context, q env.GlobQuery) (env.GlobResult, error)

Glob lists the regular files under q.Dir whose paths relative to it match q.Pattern, most recently modified first, then by path. It skips what docs/design/tools.md says a search skips, and returns at most q.Limit paths, or Bounds.GlobLimit without one.

func (e *Env) Grep(ctx context.Context, q env.GrepQuery) (env.GrepResult, error)

Grep searches the regular files under q.Dir for lines matching q.Pattern, with the portable semantics of docs/design/tools.md; when q.Dir names a regular file, it searches that file alone. It returns at most q.Limit matches, or Bounds.GrepLimit without one, and stops early, truncated, at Bounds.GrepScanBytes read or Bounds.GrepResultBytes returned.

func (e *Env) ObserveFiles(ctx context.Context, paths []string) ([]env.FileVersion, error)

ObserveFiles reads the current version of each named workspace path for a checkpoint. Paths are workspace-relative. Nothing is followed through a symlink, and ignore rules don’t apply: a checkpoint keeps what the session’s tools changed, whatever the ignore files say.

Example

dir, err := os.MkdirTemp("", "checkpoint-workspace-")
if err != nil {
panic(err)
}
defer os.RemoveAll(dir)
if err := os.WriteFile(filepath.Join(dir, "hello"), []byte("hello\n"), 0600); err != nil {
panic(err)
}
e, err := local.New(context.Background(), dir)
if err != nil {
panic(err)
}
defer e.Close()
versions, err := e.ObserveFiles(context.Background(), []string{"hello", "missing"})
if err != nil {
panic(err)
}
for _, v := range versions {
fmt.Println(v.Path, v.Size, v.Absent)
}
// Output:
// hello 6 false
// missing 0 true

Output:

hello 6 false
missing 0 true
func (e *Env) OpenOutside(ctx context.Context, dir string) (env.OutsideFiles, error)

OpenOutside implements env.OutsideSearcher: an environment on dir, an existing directory, for its searches alone, with this one’s bounds. It is confined to dir as this one is to the workspace, and starts no processes; the caller closes it. Where this environment’s commands are confined in what they read, it refuses, as ReadOutside does.

func (e *Env) OpenScratch(ctx context.Context, dir string) (env.ScratchFiles, error)

OpenScratch implements env.ScratchOpener: an environment on dir, made private to the user if missing, for its file operations alone, with this one’s bounds. It is confined to dir as this one is to the workspace, and starts no processes; the caller closes it.

func (e *Env) ProcessGone(ctx context.Context, id env.ProcID) (bool, error)

ProcessGone reports whether a local command is confirmed gone. It checks the owning process and watchdog pipe: the owner keeps the pipe open even after Kill, until it releases the handle or closes. If the owner dies, the kernel closes the pipe and the watchdog kills the group.

A command counts as gone only when this backend can know:

  • the ID names this machine in an earlier boot: local commands die with their host, which a reboot ends, so nothing survives it;
  • in this boot and PID namespace, the owner’s PID is absent, belongs to a process that started at another time, or, for an owner in this OS process, the pipe is released or no longer the same pipe.

A different machine, an unknown machine, another PID namespace, a foreign ID, or a start time that can’t be read leaves the exit unknown, as does anything else it can’t establish.

Example

dir, err := os.MkdirTemp("", "process-workspace-")
if err != nil {
panic(err)
}
defer os.RemoveAll(dir)
ctx := context.Background()
e, err := local.New(ctx, dir)
if err != nil {
panic(err)
}
defer e.Close()
p, err := e.Start(ctx, env.Cmd{Path: "/bin/sh", Args: []string{"-c", "exit 23"}})
if err != nil {
panic(err)
}
defer p.Close()
exit, err := p.Wait(ctx)
if err != nil {
panic(err)
}
gone, err := e.ProcessGone(ctx, p.ID())
if err != nil {
panic(err)
}
// The owner still holds the handle and can report the exit.
fmt.Println(exit.Code, gone)
// Output: 23 false

Output:

23 false
func (e *Env) ReadFile(ctx context.Context, name string, opt env.ReadOpt) (env.File, error)

ReadFile reads a page of a regular file in the workspace, with the whole file’s revision. The whole file is read to hash it, so a file larger than Bounds.FileBytes is refused with env.ErrTooLarge. The page and the revision come from the same pass over the same open file: a page is never paired with a revision of other contents.

func (e *Env) ReadOutside(ctx context.Context, name string, opt env.ReadOpt) (env.File, error)

ReadOutside implements env.OutsideReader: ReadFile for an absolute path anywhere on the host, which the caller’s permissions allowed. It follows symbolic links, as reading the same path with a command does.

It reads no more than a command could: where the launcher confines what processes read, it refuses with an error wrapping env.ErrOutsideWorkspace, since a permission that lets a command ask for the path doesn’t let the command see it, and containment holds through the environment, not through review.

func (e *Env) RestoreFile(ctx context.Context, c event.FileRestoreChange, data []byte) error

RestoreFile conditionally writes or deletes one regular file through the workspace jail. Writes stage and sync before rename; deletions sync their parent directory. Recorded executable bits replace only the executable bits; other existing permission bits are preserved (new files use 0644 or 0755). The caller plans the change against the file’s current content (Before), which is checked again here, so a file changed since isn’t overwritten.

func (e *Env) Start(ctx context.Context, cmd env.Cmd) (env.Proc, error)

Start runs cmd with piped standard streams and a process tree owned by this Env. The process outlives ctx, which bounds only the start.

func (e *Env) WriteFile(ctx context.Context, name string, data []byte, opt env.WriteOpt) (env.Revision, error)

WriteFile replaces a regular file in the workspace with data, or creates it, if its revision is still opt.IfRevision. The data goes to a temporary file beside the target, which is synced and renamed over it, so the file is never seen half written. A new file’s missing parent directories are created.

The rename replaces the directory entry: hard links to the old file keep the old contents, and a symbolic link as the final component is refused with env.ErrNotRegular rather than replaced. A replaced file keeps its permission bits but not its owner.

Example

A write names the revision it read, so a change made in between is caught instead of overwritten.

dir, err := os.MkdirTemp("", "workspace")
if err != nil {
panic(err)
}
defer os.RemoveAll(dir)
if err := os.WriteFile(filepath.Join(dir, "go.mod"), []byte("module old\n"), 0o644); err != nil {
panic(err)
}
e, err := local.New(context.Background(), dir)
if err != nil {
panic(err)
}
defer e.Close()
ctx := context.Background()
f, err := e.ReadFile(ctx, "go.mod", env.ReadOpt{})
if err != nil {
panic(err)
}
edited := bytes.Replace(f.Data, []byte("old"), []byte("new"), 1)
if _, err := e.WriteFile(ctx, "go.mod", edited, env.WriteOpt{IfRevision: f.Revision}); err != nil {
panic(err)
}
// The read's revision is now out of date.
_, err = e.WriteFile(ctx, "go.mod", []byte("module other\n"), env.WriteOpt{IfRevision: f.Revision})
fmt.Println(errors.Is(err, env.ErrStale), env.NoEffect(err))
f, err = e.ReadFile(ctx, "go.mod", env.ReadOpt{})
if err != nil {
panic(err)
}
fmt.Print(string(f.Data))
// Output:
// true true
// module new

Output:

true true
module new
type Materializing struct {
*Env
// contains filtered or unexported fields
}

Materializing is a local Environment with recorded-skill publication and owned bundle cleanup. Its cache is protected from file mutations and every tool process before any process starts. Calls are concurrency safe. The host owns it; Close joins processes and closes storage, retaining data for resume.

func NewMaterializing(ctx context.Context, dir, cache string, bounds materialize.Bounds, opts ...Option) (*Materializing, error)

NewMaterializing opens a workspace and its existing private publication cache. cache is a canonical proper workspace-relative directory, reserved exclusively for generated artifacts. The caller supplies a ReadOnlyLauncher through opts. The cache is omitted from search and workspace-delta capture, but ReadFile can read published paths. No ignore files or user repository metadata are changed. A process-lifetime lock excludes another host using this same cache; share the returned Environment across sessions or supply separate cache namespaces.

Example

The default unconfined launcher cannot promise a read-only publication cache. Hosts supply bubblewrap or Seatbelt through WithLauncher before opting in.

dir, err := os.MkdirTemp("", "materialized-workspace-")
if err != nil {
return
}
defer os.RemoveAll(dir)
if err := os.Mkdir(filepath.Join(dir, "cache"), 0o700); err != nil {
return
}
_, err = local.NewMaterializing(context.Background(), dir, "cache", materialize.Bounds{})
fmt.Println(errors.Is(err, env.ErrUnenforced))
// Output: true

Output:

true

Example (bwrap)

With a launcher that can protect paths read-only, a host opts in to a private publication cache: the files zelk publishes for the model, such as a skill’s, which the sandboxed commands can read and never change. Nothing runs here: it needs bubblewrap, and cache must exist.

ctx := context.Background()
sandbox, err := launcher.NewBwrap(ctx, launcher.BwrapOptions{Network: launcher.NetworkOff})
if err != nil {
fmt.Println(err)
return
}
// The cache is a directory of the workspace that only zelk writes.
e, err := local.NewMaterializing(ctx, "/srv/workspace", ".zelk-cache", materialize.Bounds{}, local.WithLauncher(sandbox))
if err != nil {
fmt.Println(err)
return
}
defer e.Close()
// Pass e to zelk.WithEnvironment, and to zelk.WithCatalogCleanup so
// that deleting a session releases what it published.
func (e *Materializing) Close() error

Close joins tool processes before releasing the cache’s process lock. It retains publications; neither shutdown nor suspension is session-end cleanup.

func (e *Materializing) MaterializationNamespace() string

MaterializationNamespace identifies the cache and its visible mapping for recorded resume and cleanup compatibility checks.

func (e *Materializing) Materialize(ctx context.Context, b env.MaterializeBundle) (env.Materialization, error)

Materialize publishes a verified recorded bundle without consulting its source.

func (e *Materializing) Release(ctx context.Context, p env.Materialization) error

Release removes an exactly identified complete publication. Durable session cleanup uses ReleaseBundle to include attempts whose receipt was lost.

func (e *Materializing) ReleaseBundle(ctx context.Context, b env.MaterializeBundle) error

ReleaseBundle removes complete and interrupted owned publications using recorded bytes. Unknown/changed files survive; callers coordinate live refs.

type Option func(*Env)

Option configures an Env.

func WithBounds(b Bounds) Option

WithBounds sets the environment’s bounds; zero fields keep their defaults.

func WithHome(dir string) Option

WithHome names the user’s home directory, the absolute path a “/” in git configuration stands for. Without it, sandboxed processes refuse to start in a repository whose configuration names a “/” path, since zelk can’t tell whether that path is in the workspace (docs/design/enforcement.md).

It must be the directory git itself expands “~” to, or a configuration file would be protected in one place and read from another. Git reads HOME first. Git for Windows, where HOME is usually unset, then reads HOMEDRIVE joined with HOMEPATH, if that is a directory, and then USERPROFILE. On Windows it must be drive-absolute.

func WithKillGrace(d time.Duration) Option

WithKillGrace sets how long a process tree has to stop before forced termination; the default is DefaultKillGrace. Zero kills at once. On Windows a process tree is always terminated at once: it runs on a console of its own, which no graceful stop from the host reaches.

func WithLauncher(l launcher.Launcher) Option

WithLauncher confines the processes the environment starts with l, such as a bubblewrap sandbox; its profile becomes the Exec row of Enforcement. The default is launcher.None, which confines nothing. A nil launcher fails New with launcher.ErrNoLauncher rather than fall back to none: a host that asked for confinement never gets less.

func WithReadOnlyDirectories(directories ...string) Option

WithReadOnlyDirectories protects existing canonical workspace-relative directories from file mutations and every subprocess. Configuration is fixed before New returns, so background processes cannot predate protection. New requires launcher.ReadOnlyLauncher; missing or aliased directories fail closed. Hosts keep these namespaces stable until Close has joined their processes.

func WithRequirements(reqs ...env.Requirement) Option

WithRequirements makes New fail, with an error wrapping env.ErrUnenforced, unless the environment meets every requirement: a host that needs a protection learns at construction that it isn’t there, never by a silent downgrade.

Example

A host that needs a protection the environment can’t give finds out when it builds the environment.

dir, err := os.MkdirTemp("", "workspace")
if err != nil {
panic(err)
}
defer os.RemoveAll(dir)
_, err = local.New(context.Background(), dir, local.WithRequirements(env.Requirement{Op: env.Exec, Dim: env.Network, Min: env.Enforced}))
fmt.Println(errors.Is(err, env.ErrUnenforced))
// Output:
// true

Output:

true
func WithRipgrep(path string) Option

WithRipgrep makes Grep use the ripgrep binary at path, an absolute path the host found; the environment never searches for it. The environment opens each file itself and gives ripgrep the checked handle as standard input on Windows or as a descriptor path elsewhere. Files or runs that ripgrep cannot search with identical semantics use the Go backend.