# Enforcement

What zelk enforces about the operations that go through an environment, and the exact profile of each launcher. The escape suite tests each profile: every escape below succeeds without a launcher and fails under it.

## The matrix

`Environment.Enforcement()` reports, for each operation (`Exec`, `FileRead`, `FileWrite`) and dimension (`FSRead`, `FSWrite`, `Network`, `CredentialIsolation`, `ProcessVisibility`, `Resources`), whether it is `enforced`, `advisory` or `none`, with a note. Hosts declare required cells (`local.WithRequirements`, `zelk.WithRequirements`); an environment that can't provide one fails construction rather than downgrade. Custom Go tools, MCP servers and client-hosted tools are outside its scope.

| Operation | Local environment |
|---|---|
| `FileRead`, `FileWrite` × `FSRead`, `FSWrite` | enforced, in-process: the [path jail](https://github.com/barevoidco/zelk/blob/main/core/internal/pathjail/README.md) resolves with `openat2(RESOLVE_BENEATH\|RESOLVE_NO_MAGICLINKS\|RESOLVE_NO_XDEV)` on Linux, `os.Root` elsewhere (on Windows it opens each component from the handle of the one before and refuses every junction and absolute link, so a mount point is never crossed; names that Win32 reads another way, such as `name:stream`, `NUL` or `name.`, are refused); devices and FIFOs are refused. Traversal resistance only. |
| `Exec` × every dimension | the launcher's row, below |

## Launchers

Windows supports `none` and `mxc`. The bubblewrap and seatbelt constructors
return `launcher.ErrUnavailable` on Windows.

A launcher wraps each process the local environment starts (`local.WithLauncher`). Each has a fixed profile; requests outside it (a network allowlist, a relative tool path) are rejected at construction.

### `none` (default)

Confines nothing. Every `Exec` cell is `none`: the process can read the user's files, use the network and inspect host processes.

On Windows the local environment starts every process in a kill-on-close Job
Object. The job lets the host own and stop the tree and leaves the launcher's
execution enforcement cells at `none` when using this launcher.

An opted-in executable name search uses the injected PATH and PATHEXT on
Windows. It skips relative directories and executables in the workspace,
including links that resolve into it. A caller may explicitly name an absolute
workspace executable. The local environment runs `.cmd` and `.bat` files
inside the job using the injected `SystemRoot\System32\cmd.exe`, outside
the workspace, with `/d /s /v:off /c` to disable AutoRun and delayed expansion
and remove the outer quotes around the command.

Batch arguments containing spaces, tabs, commas, semicolons or equals signs
are quoted as single tokens, as is an empty argument. Quotes, percent signs,
exclamation marks, carets, ampersands, pipes, angle brackets and parentheses in
arguments are refused. They can change quoting, expand variables, escape
characters or control execution when cmd parses or a shim substitutes its
parameters. Quoted arguments ending in a backslash are refused because cmd and
native programs interpret a backslash before a quote differently. Invalid
UTF-8, ASCII control characters other than tab, and DEL are refused. Batch
paths may contain quoted punctuation such as parentheses, but cannot contain
quotes, percent signs, exclamation marks or the same invalid text and control
characters. Command lines exceeding 8,191 UTF-16 code units are refused.

### `bwrap` (Linux)

`launcher.NewBwrap` finds `bwrap` (or takes its absolute path) and runs a trivial command in the full profile before returning, so a container where bubblewrap can't create namespaces fails construction with `ErrUnavailable` instead of running processes unconfined.

Every process starts as:

```
bwrap --die-with-parent --new-session --unshare-all [--share-net]
      # each of /usr /bin /sbin /lib /lib32 /lib64 /libx32 /etc /opt that exists:
      --ro-bind <dir> <dir>            # or --symlink <target> <dir> where it is a symbolic link (merged /usr)
      --ro-bind <path> <path>          # each BwrapOptions.ReadOnly path the system directories don't cover
      --ro-bind <file> <file>          # network full only: the file each of /etc/resolv.conf, /etc/hosts and
                                       # /etc/nsswitch.conf leads to when it is a link out of the system directories
      # each credential file under /etc, and each BwrapOptions.Mask path, that exists,
      # resolved to where it leads (binds are resolved too)
      # under a bind above, after every read-only bind so none shows it again:
      --ro-bind /dev/null <file>       # /etc/shadow, /etc/shadow-, /etc/gshadow, /etc/gshadow-, /etc/sudoers,
                                       # /etc/krb5.keytab, /etc/security/opasswd, /etc/containers/auth.json
      --tmpfs <dir> --remount-ro <dir> # /etc/sudoers.d, /etc/ssh, /etc/ssl/private, /etc/docker
      --bind <path> <path>             # each BwrapOptions.Writable directory, such as a sandbox-only build cache
      --tmpfs /tmp --proc /proc --dev /dev
      --bind <workspace> <workspace>
      --bind <extra-writable-root> <extra-writable-root> # each explicit Spec.WritableRoots entry
      --bind <scratch> <scratch>       # Spec.Scratch, the session's scratch directory, when given
      # writable ancestor pins, then read-only Git inputs/publications (see below)
      --chdir <dir>
      --clearenv --setenv <name> <value>...   # only DefaultEnv and BwrapOptions.Env names, then BwrapOptions.Setenv over them
      --setenv HOME /tmp --setenv TMPDIR /tmp
      -- <path> <args>...
```

Before it starts, the launcher marks every descriptor of the host process above standard error close-on-exec (`close_range(3, ~0, CLOSE_RANGE_CLOEXEC)`, or a walk of `/proc/self/fd` on older kernels), because bubblewrap passes inherited descriptors straight through. This changes the host's descriptors, not only the child's: a host that passes descriptors to its own children by inheritance must pass them explicitly instead.

| Dimension | Level | Why |
|---|---|---|
| `FSRead` | enforced | system directories and host-named paths (toolchains) read-only, the workspace, explicitly named extra writable roots and a fresh `/tmp`; no home directory beyond the host-named paths, no `/run`, `/var` or host sockets such as `docker.sock` (with network `full`, only the files that `/etc/resolv.conf`, `/etc/hosts` and `/etc/nsswitch.conf` lead to, when they are links out of `/etc`); credential files masked |
| `FSWrite` | enforced | only the workspace, explicitly named extra writable roots (Git's common directory below), host-named writable directories and the fresh `/tmp` |
| `Network` | enforced (`off`) / none (`full`) | `off` is a new network namespace with only loopback; `full` shares the host's |
| `CredentialIsolation` | enforced | no home directory, host sockets or credential files; the environment reduced to an allowlist; no inherited descriptors |
| `ProcessVisibility` | enforced | a new PID namespace with its own `/proc`: host processes, their command lines and environments are invisible |
| `Resources` | none | no limits; rlimits are applied separately |

**Toolchains under the home directory.** The home directory is hidden, so a toolchain installed there (Go's module cache and downloaded toolchains, rustup and cargo, an nvm Node) is missing inside unless the host binds it. The CLI and TUI hosts find the toolchains by asking them and bind a fixed set read-only: Go's `GOROOT` and `GOMODCACHE`; `RUSTUP_HOME` and cargo's `bin`, `registry` and `git` directories, never the whole cargo home, which keeps `credentials.toml`; and the install directory of the `node` on `PATH`. They set the variables that find them (`GOMODCACHE`, `CARGO_HOME`, `RUSTUP_HOME`), and with the network off `GOPROXY=off` and `CARGO_NET_OFFLINE=true`, so a missing module fails at once with the tool's own message rather than a failed download. `-sandbox-read-only` (`sandbox_read_only` in the saved defaults) adds paths; the home directory's credential files (`~/.ssh`, `~/.aws`, cargo's credentials, zelk's own configuration and state, and the like; configuration directories under both `~/.config` and `XDG_CONFIG_HOME`) are masked under whatever is added, `~` itself included. Binds and masks meet at resolved paths, so a credential directory that is a symbolic link, as `~/.aws` often is under WSL, is masked where it leads. Go's build cache is a writable directory under zelk's state directory, one per workspace, never the user's own `~/.cache/go-build`: a sandboxed command could plant build results there that an unsandboxed build would then use. The same holds for downloads. With the network off the user's module cache and cargo's registry stay read-only, which is all a command that downloads nothing needs. With the network `full` or `allowlist`, a read-only cache would make `go get`, `go mod download` and `cargo fetch` fail on anything not already downloaded, so Go's module cache (`GOMODCACHE`) and cargo's home (`CARGO_HOME`) are directories of the sandbox's own under the state directory, one per workspace, made writable. The user's module cache stays bound read-only and is served to Go as a file proxy ahead of the proxies the user's `go` is set to: `GOPROXY=file:///<user cache>/cache/download,<the user's GOPROXY>`. A module the user already downloaded is then copied into the sandbox's cache without a request, and one they haven't falls through to the proxy they chose, so the user's own cache is never written. The user's effective `GOPROXY` and `GOFLAGS`, as `go env` reports them (the sandbox sees neither their `go env` file nor, unless `-env` names it, the variable), travel in the sandbox's `GOPROXY` and `GOFLAGS`, with `-modcacherw` appended so the sandbox's cache stays removable. A `GOPROXY` can embed credentials (`https://user:token@proxy.corp.example/mod`), and the sandbox hides `~/.netrc` and the home directory so that a command can't read them, so the `GOPROXY` zelk passes on by itself never carries userinfo: any proxy whose URL has a user or a password is dropped, together with the separator after it, and the others keep theirs (`a,https://u:p@b|c` becomes `a,c`; `,` and `|` both separate proxies, and `direct` and `off` are keywords that stay). With nothing left the list is `off`, not empty, which go reads as its default: dropping a private proxy must not send a request to a public one. A private module behind the dropped proxy then fails with go's own message, and the user who wants it fetched from inside the sandbox names `GOPROXY` with `-env`, which hands the sandbox that variable, credentials and all, as it would any other. The launcher applies `Setenv` over the command's own variables, so the `GOPROXY` zelk sets replaces the one `-env` passed, but it holds the same list, whole, with the user's module cache in front: `go env` ran with the command's environment, where the variable wins over go's env file. An entry that merely holds `@` in a path or query is not userinfo and stays; `GOPRIVATE`, `GONOSUMDB` and the like are left to `-env`, as before. Cargo's home is not shared the same way, since cargo has no read-only fallback cache: its registry and git are downloaded afresh into the sandbox's own home, and only the user's `bin` directory, where `PATH` finds `cargo`, is bound. Git's global configuration is hidden with the home directory, so git inside would have no identity and every commit would fail: the hosts write a configuration of the sandbox's own beside that cache, holding only the user's `user.name` and `user.email` read from theirs, bind it read-only and point `GIT_CONFIG_GLOBAL` at it. A repository's own `user.name` still wins over it, as `GIT_AUTHOR_NAME` and the like wouldn't let it; nothing else of the user's configuration comes along, since it can name credential helpers and aliases that run programs.

**Name resolution with network `full`.** `/etc/resolv.conf` is often a symbolic link to a place the sandbox doesn't bind: `/mnt/wsl/resolv.conf` under WSL, `/run/systemd/resolve/stub-resolv.conf` under systemd-resolved, `/run/NetworkManager/resolv.conf` under NetworkManager. Inside, such a link would dangle and no name would resolve. So, with `full`, each of `/etc/resolv.conf`, `/etc/hosts` and `/etc/nsswitch.conf` that is a link leading out of the system directories gets the file it leads to bound read-only: at its real path, and at each link of the chain that the sandbox would read somewhere it has no directory for (a link through `/var/run`, itself a link to `/run`). Only the file is shown, never `/run` or its sockets, so the process list of sockets above is unchanged: nss's `systemd` and `resolve` modules find no socket and fall through to the DNS in `resolv.conf`. systemd-resolved's stub listens on `127.0.0.53` of the host's loopback, and `full` shares the host's network namespace (`--share-net` after `--unshare-all`), so it is reachable. The binds are made when each command starts, not once: bwrap refuses to start with a missing source, and a resolver that comes and goes must not fail every command. A file a mask hides, a credential file or a path the host masks, is not bound, and the masks still follow every bind. With `off` the sandbox has loopback alone and resolves no name, and with `allowlist` the broker outside the sandbox resolves every name for the command, so neither gets the binds and what they show is not widened.

Not covered: resource limits; any other `/etc` file that is a symbolic link out of the system directories still dangles, and `-sandbox-read-only` shows what it leads to.

### `seatbelt` (macOS)

`sandbox-exec -p <profile> -- <path> <args>...`, with the environment reduced to the allowlist and `HOME` and `TMPDIR` set to the private temporary directory the host names (`SeatbeltOptions.TempDir`, required; zelk doesn't read `TMPDIR` for it). That directory is the launcher's, shared by every session the host runs. A process that brings a scratch directory (`Spec.Scratch`, the session's) may write it, as a `WritableRoots` entry; it isn't `TMPDIR`, whose long name would reach every path a test or tool builds from it. When developer tools are selected, their `usr/bin` goes on `PATH` just before `/usr/bin` (an unset `PATH` gets the shell's default, `/usr/bin:/bin:/usr/sbin:/sbin`, the same way). macOS's `/usr/bin/git` and the other developer-tool shims run xcrun, which writes a tool-lookup cache to the user's shared temporary directory whatever `TMPDIR` says; the sandbox must deny that write, since a sandboxed process could otherwise point the host's own tool lookups at a program it chose. Resolving a shim's name to the tool it would run avoids the shim, while a tool earlier on `PATH`, such as Homebrew's `git`, still comes first. A command that names `/usr/bin/git` itself still fails. The profile:

```
(version 1)
(deny default)
(allow process-exec process-fork)
(allow signal (target same-sandbox))
(allow sysctl-read mach-lookup ipc-posix-shm-read-data ipc-posix-shm-write-data)
(deny mach-lookup (global-name "com.apple.SecurityServer") (global-name "com.apple.securityd")
                  (global-name "com.apple.securityd.xpc") (global-name "com.apple.security.agent")
                  (global-name "com.apple.security.authhost"))   ; the keychain's daemons
(allow file-read-metadata)
(allow file-read-data (literal "/"))   ; shells read the root listing as they start
(allow file-read* (subpath "/usr") (subpath "/bin") (subpath "/sbin") (subpath "/System") (subpath "/Library")
                  (subpath "/private/etc") (subpath "/opt/homebrew") (subpath "/dev") (subpath "/private/var/db/timezone")
                  <developer directory> <ReadOnly paths> <WritableRoots paths> (subpath "<workspace>") (subpath "<tmp>"))
(allow file-write* <WritableRoots paths> (subpath "<workspace>") (subpath "<tmp>") (literal "/dev/null") (literal "/dev/tty"))
(deny file-write* (literal "<extra-writable-root>")) ; pin each extra root's name
(allow network*)   ; only with network full
```

The developer directory is the resolved target of `/private/var/db/xcode_select_link`, which `xcode-select` maintains, when one is selected. macOS's `/usr/bin/git` and other developer-tool shims run the tool from there, and an Xcode installation lives outside the system directories, so without it a sandboxed `git` fails.

| Dimension | Level | Why |
|---|---|---|
| `FSRead` | enforced | system directories, the active developer directory, the workspace, explicitly named extra writable roots and the private temporary directory; not the home directory |
| `FSWrite` | enforced | only the workspace, explicitly named extra writable roots, and the private temporary directory |
| `Network` | enforced (`off`) / none (`full`) | the profile allows no network operation unless `full` |
| `CredentialIsolation` | advisory | no home directory, an allowlisted environment and no keychain daemon (securityd), but the user's other processes and other Mach services stay reachable |
| `ProcessVisibility` | none | no process namespace |
| `Resources` | none | no limits |

`sandbox-exec` isn't documented as public API by Apple; the profile is tested on the macOS versions in CI.

### `mxc` (Windows)

The Windows CLI installs Microsoft's pinned `wxc-exec.exe` after showing
the telemetry notice and obtaining agreement. Non-interactive setup needs
`-accept-telemetry`. Setup verifies the npm tarball's size and SHA-256,
extracts only the platform's executor, checks its pinned SHA-256 and
Microsoft Authenticode signature, and atomically publishes it with the
agreement in a private, versioned state directory. `zelk sandbox setup
-verify` checks the install without starting it. Every launcher construction
rechecks the private install, the agreement and the executable's hash before
it can run. An explicit or saved `mxc`, an allowlist request, or a managed
sandbox requirement fails startup if MXC cannot be used. Other unattended
auto runs report an unavailable sandbox and run unconfined when policy
permits that fallback. When a run gets
MXC it says so in one line on stderr, as it does for bwrap on Linux: commands
run in the sandbox, the network is off unless `-network` says otherwise, and
`-sandbox none` runs them unconfined.

`launcher.NewMXC` takes the absolute path to Microsoft's signed
`wxc-exec.exe`, the home directory, read-only toolchain paths, writable
cache directories, trusted toolchain environment entries and network mode
(`off`, `full` or `allowlist`). Allowlist also requires the trusted HTTP
broker's loopback IP and port. The host supplies and verifies the executor
and its install directory and accepts the telemetry before construction. `--probe` must
confirm the base container API, denied paths, drive enumeration and operation
without ACL changes, and for an allowlist also host loopback ingress
(`baseContainerSupportsIngressHostLoopbackAllow`) and the identityless loopback
proxy (`baseContainerSupportsIdentitylessLoopbackProxy`). A trivial command then runs in the full profile.
Construction failures return `launcher.ErrUnavailable`.

The executor starts from its own install directory with only the trusted
Windows `SystemRoot` and a `PATH` containing only `System32`. Writable grants
must stay clear of the executor installation and of the Windows directory: a
grant may neither hold it nor lie inside it. The workload's executable
must be granted, as itself or through a directory that holds it, or be within
the Windows system directories, and its
working directory must exist in a writable root. Grants use absolute local
drive paths.

The MXC policy uses version `1.0.0` and `containment: "processcontainer"`.
zelk's acceptance suite has run only on Windows 11 26H2 build 26300.9974 with
MXC 1.1.0, and support is claimed for that combination. Microsoft lists 24H2
from build 26100.9278 and 25H2 from 26200.9278 as supported hosts, which the
suite hasn't run on.

- `filesystem.readwritePaths` grants the workspace, `Spec.WritableRoots`,
  `Spec.Scratch` and the host's writable cache directories.
  `filesystem.readonlyPaths` grants the host's toolchains and protects Git
  and agent configuration inputs inside writable roots.
  `filesystem.deniedPaths` denies the whole home when it contains no grant.
  With grants under home, it denies the siblings along every path from home
  to a grant. This lets shells traverse the ancestors of the workspace and
  toolchains. The walk lists only those ancestors. It denies sibling reparse
  points by name and refuses a grant chain with a reparse point.
  The list is rebuilt for each command. A new entry created after the scan
  has no explicit deny rule for that command unless an ancestor is denied.
  Files Windows refuses to open for reading because of a sharing lock are
  omitted because including them makes MXC reject the container. If the
  lock is released, that command still has MXC's default file-content boundary.
- `processContainer.filesystem.enumeratePaths` names the root of each drive
  with a grant. Tools need drive enumeration for absolute path lookups.
- `ui` is `{"disable":false,"clipboard":"none","injection":false}`.
  Tools such as Git for Windows need the Windows UI subsystem to initialize.
- `network.egress.default` is `deny` in `off` and `allow` in `full`.
  No ingress rule is supplied, so access to host loopback stays closed in
  both modes. In `allowlist`, egress defaults to `deny` and
  `network.ingress.default` and `network.ingress.hostLoopback` are `allow`.
  The launcher sets `runtimeConfig.networkProxy` to the HTTP broker's
  loopback URL with an explicit port. MXC uses Windows Filtering Platform
  rules to restrict workload connections to that endpoint.
- `process.cwd` and `process.env` belong to the workload. The environment
  preserves the values and spelling of the case-insensitive allowlist
  (`DefaultEnv` plus `SystemRoot`, `ComSpec`, `PATHEXT` and `windir`).
  The launcher also passes the numbered entries that carry the shell command
  to its wrapper, which clears them before running it.
  MXC requires `SystemRoot` and `LOCALAPPDATA`. zelk fills in a missing
  `SystemRoot` and gets the real `LOCALAPPDATA` from Windows for staging.
  MXC supplies its own per-command `TEMP`, `TMP` and `LOCALAPPDATA` in the
  sandbox and removes that temporary directory at exit.

The host discovers the Go toolchain and module cache, Git for Windows, the
selected shells, Node, Python, Rust and ripgrep. The ripgrep grant names
`rg.exe` itself. The discovered paths are read-only. Go's build cache and
npm's cache are writable and isolated per workspace under the state directory. npm receives separate empty user and global
configuration files so it can use the cache without reading host npm
configuration. In network `off`, Go gets `GOPROXY=off`,
`GOSUMDB=off` and `GOTOOLCHAIN=local`. With any network but `off` (`full` or `allowlist`), Go's module
cache is also writable and the sandbox's own, with the user's cache read-only
behind a `file:///C:/...` proxy ahead of the user's `GOPROXY` (MXC's
`GOENV=off` hides their `go env` file, so the host passes the effective
value). Git gets `GIT_CONFIG_GLOBAL` pointing
to a read-only file with only `user.name` and `user.email` from the user's
configuration. PowerShell can start in a workspace under the Windows
profile because its filesystem provider can traverse the grant's ancestors.
When Windows offers the Microsoft Store edition, the host selects a native
unpackaged PowerShell or the inbox Windows PowerShell. MXC cannot launch an
MSIX package inside the host's process job.
Git for Windows' native `git.exe` works in MXC. Git Bash cannot initialize
because MSYS2 needs to create a directory in the global Windows object
namespace. zelk offers PowerShell alone whenever MXC is the selected
launcher. Verify, Watch, and session hooks without a shell choice also
use PowerShell. Session hooks still run on the host. Startup rejects
`-bash`, `-no-powershell`, and trusted hooks that specify `"shell": "bash"`.
The restriction covers every Bash override. Use PowerShell or select
`-sandbox none` to use Bash where policy permits it.
[Microsoft tracks this limitation in MXC #1061](https://github.com/microsoft/mxc/issues/1061).

The executor receives `--config-base64` followed by the policy, then
`-- <path> <args>...`. If the Windows command line would exceed 32,767 UTF-16
code units including the terminator, the policy is passed by file. The file
lives in a directory with a private Windows ACL outside the granted paths.
The launcher includes an explicit deny when it stages that directory under
a traversable profile ancestor.
For a batch workload the local environment prepares the validated
`cmd.exe /d /s /v:off /c` line before wrapping. MXC receives it verbatim in
`process.commandLine` so the quotes around the batch invocation survive.

`WrapReadOnly` keeps a host handle open on each protected path without
`FILE_SHARE_DELETE`. A handle on a descendant prevents Windows from
renaming or removing its ancestors, including its owning root, while
unprotected siblings remain writable. This keeps Git's writable index and
refs usable. The local environment releases the handles and any policy file
on a failed start or once the Windows job is empty, before reporting exit. If
the job can't be terminated or queried, closing it kills the tree
(kill-on-close) and they are released once the leader's exit is confirmed,
never earlier.
A layout it cannot protect returns `env.ErrUnenforced`.
The executor runs in the local environment's kill-on-close job. Stopping on
Windows is a hard kill. Background children inside a workload end with it.

| Exec dimension | Enforcement |
|---|---|
| `FSRead` | Enforced for file contents within grants and system directories. Drive names and metadata can be visible, including entries under traversable home directories. |
| `FSWrite` | Enforced. Writes stay within writable grants and MXC's private temporary directory, with protected inputs read-only. |
| `Network`, `Offline` in `off` | Both enforced. Egress and host loopback are closed. |
| `Network`, `Offline` in `full` | Both none. Egress is allowed and host loopback is closed. |
| `Network`, `Offline` in `allowlist` | Network advisory, Offline none. MXC restricts connections to zelk's egress proxy. The Windows DNS client can resolve arbitrary names, so workloads can send data out in DNS queries. |
| `CredentialIsolation` | Advisory. MXC denies Credential Manager and applies per-command home denials outside grants. A workload can use DPAPI to decrypt blobs it can read. |
| `ProcessVisibility` | Enforced. Host processes are hidden and cannot be opened. |
| `Resources` | None. The profile sets no resource limits. |

#### Telemetry

Microsoft's MXC executor sends **Required telemetry** to Microsoft only on
Windows when zelk runs commands in the `mxc` sandbox. zelk itself sends
nothing. Linux (`bwrap`), macOS (`seatbelt`) and Windows with `-sandbox none`
send no MXC telemetry.

- `MXC.ExecutionStart` and `MXC.ExecutionEnd` report the sandbox kind,
  backend, denial-capture mode, exit code, outcome, duration, failure reason
  and phase.
- `MXC.Error` reports the sandbox kind, backend, error type, exit code and phase.
- `MXC.ProcessExited` reports an opaque process identity, process ID and exit code.

Each event includes a random session ID, version, release channel and privacy
tags. Microsoft documents that these events exclude command lines, environment
values, complete file paths, account names, tokens and sandbox output.

zelk, Windows settings and administrator policy cannot turn this telemetry
off. To avoid it, run without the `mxc` sandbox. Setup shows this notice and
requires agreement before downloading or running the executor. The first
sandboxed session also shows a reminder once per state directory.
[Microsoft's MXC telemetry documentation](https://github.com/microsoft/mxc/blob/main/docs/telemetry.md) · [Microsoft Privacy Statement](https://privacy.microsoft.com/privacystatement)

### Git inputs in the sandbox

Git runs programs its configuration names: hooks, `core.fsmonitor`, filter drivers, pagers. A sandboxed command that writes the repository's configuration or hooks gets code run later by the user's own git, outside any sandbox. So under a launcher that implements `ReadOnlyLauncher` (`bwrap`, `seatbelt`, `mxc`), the local environment protects git's inputs from every process it starts. The commands that spell a configuration write are human-only ([permissions](/internals/permissions/#protected-paths)). This section is what holds when a command doesn't spell one.

**What is protected.** Before each process starts, `internal/gitinput` reads the workspace's layout from disk. Nothing is cached, so a repository created by one command is protected from the next. It finds:

- the git directory: `.git` itself, a `.git` gitdir file and the directory it names, or the workspace root when the workspace is itself a bare repository;
- the common directory, through a `commondir` file, which is protected as well;
- the linked worktrees' administrative directories under `<common>/worktrees`, and the submodule git directories under `<common>/modules`, found recursively.

In each git directory it protects `config`, `hooks` and `config.worktree`. Linked administrative `commondir` and `gitdir` pointer files are protected too, so a command cannot redirect discovery or the worktree used to resolve relative hooks. It reads every one of those configuration files, and every file their `include.path` and `includeIf.*.path` entries name (whatever the condition, up to ten levels deep, as git does). It protects:

- every included file inside the workspace or its granted common Git directory;
- every `core.hooksPath` inside either writable root, resolved against each worktree that configuration applies to;
- the target of a symbolic link in a protected hooks directory, rejecting hard-linked targets just like direct inputs so a writable alias cannot change the hook.

Relative hooks are protected at every configured worktree location, including `core.worktree` overrides from common or worktree configuration and their includes. A relative `core.worktree` is resolved against the Git directory using it: the common directory for the main checkout, each administrative directory for linked worktrees. Discovery conservatively retains all possible roots from conditional includes.

A `.git` gitdir file is protected too, since replacing it with a directory would plant a whole repository.

**Absent paths.** `bwrap` needs a mount point and MXC ignores absent read-only entries, so absent inputs are created first, empty:

- `config`, `config.worktree` and `hooks` inside a git directory: invisible to the project, and an empty file or directory means the same to git as none;
- absent `gitdir`/`commondir` pointers in incomplete administrative entries: empty and read-only, so the sandbox cannot turn a stale entry into a new registration; the active worktree's pointers must already be valid;
- a `core.hooksPath` directory in the work tree: git tracks no empty directory.

All three launchers use the same discovery. An absent included file in the work tree would show up as a new file if created, so startup refuses the layout.

**What refuses.** Sandboxed startup fails with `env.ErrUnenforced` and a message naming the path when the launcher can't protect a layout:

- a protected path that is reached through a symbolic link (`.git/hooks -> ../hooks`; use `core.hooksPath` instead), since the link itself could be replaced;
- an absent included file in the work tree;
- a `~/` path when the host gave no home directory (`local.WithHome`), or on Windows one that isn't drive-absolute;
- a relative `core.hooksPath` whose worktree can't be found;
- configuration the reader can't parse;
- a layout larger than the walk bound.

**Paths on Windows.** Git for Windows reads a path from a file by its own rules, which differ from the host's, and discovery follows git's, checked against `git.exe`. A path with a drive and a separator (`C:/x`, `C:\x`) is absolute. A relative path starts at the directory of the file that holds it, and `..` is lexical: Windows removes it before it looks at the filesystem, so `link\..\x` is next to `link`, not next to what it points at. Any case, and any 8.3 short name, reaches the same file, so every component that exists is spelled as the filesystem stores it before it is compared with the workspace or protected. A junction inside a writable root refuses like a symbolic link, since a command can make one without privilege. A backslash in a gitdir or commondir file is a separator; in configuration it starts an escape, so it is written `\\` or as a slash.

Three forms don't name one place, so they refuse:

- a path with a drive and no separator (`C:x`), which git calls absolute but the system reads against the drive's current directory;
- a share or device path (`\\server\share`, `//localhost/c$/...`, `\\?\`), which git reads and which can spell any local file;
- a path rooted on the current drive (`/x`, `\x`) whose drive isn't settled. It means the drive git's working directory is on. A hook runs in its worktree, so that is the worktree's drive and the path resolves there. For a path in an include, a pointer file or `core.worktree`, no file says where git runs, so it resolves on the one drive that the file and the workspace share, and refuses if they differ.

A nested include reached through a symbolic link also refuses on Windows: git forms a relative include from the path it opened, and goes up from the link, not from its target. `~/` is HOME as git sees it (`HOME`, else `HOMEDRIVE` and `HOMEPATH`, else `USERPROFILE`); the host gives it to `local.WithHome`, and it refuses unless it is drive-absolute.

**Agent configuration in the sandbox.** `.zelk`, `.agents`, `.claude` and `.codex` at the workspace root, and the names listed below if present, are held read-only the same way, because what they hold (rules, hooks, skills, MCP servers) sets what a later run does, and the permission rules only read a command's text. An absent directory is made empty first and removed when the environment closes if it is still empty; and `.mcp.json`, `.vscode`, `.idea`, `.envrc`, `.bashrc`, `.zshrc` and `.gitconfig` are held only if they exist, since an empty stand-in would show up as a new file. Only the permission rule covers creating one, so a command the reviewer allows, or one whose text hides the name, can. That is accepted because zelk loads none of these names, the tools that do have gates of their own (`direnv allow`, approval of a project's MCP servers, workspace trust), and `zelk sessions report` lists them among the files that run later, unless git ignores them, since the report reads what git can see. If zelk ever loads one of them, it must be held while absent, as the directories are. Generated directories like `.yarn` stay writable because ordinary builds write there. A symbolic link at one of these names refuses, as for git's inputs; on Windows so does a junction or other reparse point, and the error names it. Only the workspace root is covered, so such a directory deeper in the tree relies on the permission rules. Commands that write these paths fail in the sandbox even after a person approves them; the file tools, which run in the host, still work. While a run is going, `git clean -d` reports the empty directories as busy and exits 1, after removing everything else. Ordinary project files such as a Makefile can't be protected this way: anything the agent changes there runs for whoever runs it later, and a person must review it.

**Linked worktrees and the writable grant.** For a workspace whose `.git` file names a linked administrative directory, the local environment supplies the common Git directory as an explicit `launcher.Spec.WritableRoots` entry. The launcher never discovers Git paths itself. Discovery validates the `commondir` target as a Git directory (`HEAD`, `objects`, `refs`), checks that the admin directory is `<common>/worktrees/<id>` and its `gitdir` backlink names this workspace's `.git`, and refuses a common/admin path reached through a symbolic link, even outside the workspace. Use the real path in the registration instead. A missing or invalid common directory refuses startup; it is never created or granted speculatively.

The grant is the **common directory only**, not its parent or the main checkout. Shared objects, refs, reflogs and all linked worktrees' administrative data under `<common>/worktrees` are writable, except the protected inputs above in **every** admin directory, not just the active one. This deliberately does not isolate branches, indexes or `HEAD` of other worktrees. The grant works for worktrees created by any tool, zelk's own included. Submodule Git directories and included files/hooks within the common directory receive the same protections as inputs in the workspace. Inputs outside both writable roots stay unwritable without a grant, but their configuration is still read to find includes pointing back into a writable root. A separate external gitdir without a linked-worktree `commondir` does not receive this grant. Bare common directories and nonstandard common-directory names work too. Relative custom hooks are resolved for every known worktree and for the main checkout (a conventional `.git` parent or an explicit `core.worktree`); a custom non-bare layout with no identifiable main checkout refuses relative custom hooks rather than guessing. Overlapping workspace/extra-root grants are refused by the launcher.

The host must keep the discovered root and input identities stable while sandboxed processes use them, as with the workspace's own Git inputs. This is not protection against concurrent mutation by an unsandboxed host process.

**Mount order and renames (`bwrap`).** The protected paths are bound read-only after the writable workspace and extra-root binds, so those binds can't shadow them. Renaming or removing a mountpoint fails with `EBUSY`, but renaming an ancestor carries the mount along: `mv .git .g2; mkdir .git` would plant a fresh repository. So every directory between the owning writable root and a protected path (`.git`, the directory of an included file) is first bound writable onto itself. That makes it a mountpoint the sandbox can't rename or remove, while what's inside stays writable. The cost: `rename` from such a directory to elsewhere in the workspace fails with `EXDEV`. `mv` falls back to copying, and git never renames across these directories.

**Paths, not files (`seatbelt`).** The profile denies `file-write*` on each protected path as a `subpath`, whether or not it exists, and on each ancestor as a `literal`, up to and including an extra writable root itself, so none can be renamed or removed either.

**Top-level repository files.** A command can make the workspace root itself look like a git directory (`git init --bare .`), with a `config` the user's git would read. When the local environment is created, it records which of `HEAD`, `objects`, `refs` and `config` exist at the root. After each process exits, if the root has a `HEAD`, `objects` and `refs`, it removes those of the four that weren't there before: files, and directories only when they are empty, so a project directory with contents is never touched. Without `HEAD` the root is no repository. This differs from the plan in one point: a new top-level `config` isn't blocked while the command runs, because a placeholder file at the root would show up in `git status` and `git add -A` inside the sandbox. The window is the life of the command that made it.

**Concurrency and crashes.** Each process has its own mount namespace, or its own profile, built from the layout at its start. Configuration can't change inside the sandbox, so a concurrent command can't widen what another one may write. What a crash leaves behind is the empty inputs created above (harmless, and reused next time) and, after a command that made the root a repository, the files cleanup would have removed. The bwrap mounts die with the namespace.

**What still writes.** `git status`, `add`, `commit`, `gc`, branch creation and merges work. A command that writes configuration fails: `git config`, `git remote add`, `git branch -u` and `git push -u`. Git doesn't always say so; `git branch -u` reports success without writing. Such commands are human-only actions, and the user runs them outside the sandbox. Not covered: git configuration outside the repository (the user's global and system files are outside the workspace and unwritable anyway); repositories nested in the work tree other than submodules; and `.gitattributes`, which choose among the drivers configuration defines but can't define one.

## Recorded skill caches in the sandbox

A materializing local environment protects the entire cache on every command
launch, including commands that start before the first publication. Bwrap
and seatbelt apply the same read-only protection as for Git inputs. MXC grants
the cache read-only and holds a handle without delete sharing so the cache
and its ancestors cannot be moved. The host can publish or release owned files
through its private NTFS ACL. The local file tools also guard writes through
aliases of the cache.

## Host git inspections

Review, working-tree Diff and default-review-base lookup use one injected
hardened runner (`cmd/zelk/internal/host/git_runner.go`), through an unconfined
`env.Environment` and `process.Run`. This is host-side command policy, separate
from the model's sandbox. It constructs the environment, disables system Git
config, hooks, fsmonitor, pagers and optional locks, sets
`safe.bareRepository=explicit`, and disables external diff/textconv where they
apply. The only global config is a trusted, injected absolute location; the
user's filters can still run. The trusted home for `~/` includes is injected as
well, not read from the process. Submodules are displayed as gitlink changes
only: dirty checks and recursive diff rendering are disabled, so child
repositories cannot evade the parent's config preflight. Every other configuration key
that would make an allowed subcommand start a program (signature verifiers,
external diff, textconv and merge drivers, configured hooks, which ignore
`core.hooksPath`, pagers, the submodule summary) is overridden on the command
line; the host README lists them per subcommand, and a new subcommand is
audited the same way before it is allowed.

A bounded config-only preflight enumerates scopes and names from effective
local/worktree config with includes followed. Repository-defined filters are
neutralized with empty clean/smudge/process commands and `required=false`.
Conditional includes, repository-local LFS program settings, filter names that
cannot be safely overridden, and config read/parse/bound failures refuse before
object inspection. The runner supports Git 2.43.0 and later. On 2.45+ it sets
`GIT_NO_LAZY_FETCH=1`; missing objects fail offline. On 2.43–2.44 it refuses any
partial-clone/promisor configuration, since these versions cannot reliably
switch lazy fetching off. Unknown or older Git versions refuse. A hook that configuration names (Git 2.54 and later) ignores `core.hooksPath`; Git 2.55 and later can switch off an event whatever hooks name it, which the runner does for every event, and Git 2.54 can only switch a hook off by its name, so the preflight does that too for every hook name configuration defines.

This does not protect the inputs against concurrent mutation, make shell git
safe, or guarantee safety of the user's later terminal commands. Sandbox
read-only Git inputs are described [above](#git-inputs-in-the-sandbox), and
configuration writes are human-only ([permissions](/internals/permissions/#protected-paths)).
The one fetch host git makes, a pull request's head for its worktree, runs
under this inspection policy, without prompting and refusing repository
configuration that names a program or redirects the remote. See the
[host README](https://github.com/barevoidco/zelk/blob/main/cmd/zelk/internal/host/README.md#host-git) for injection,
global-file selection, cancellation/ownership and regression tests.

**On Windows** the policy is the same and what it names differs. git runs as `git.exe`, directly with no shell, from the Git for Windows install that holds the `bash.exe` the Bash tool uses (found as that tool's is, never inside the workspace), with a `PATH` of that install's `mingw64\bin` and `usr\bin` only. `NUL` replaces `/dev/null`, and `false` replaces `/usr/bin/false`: git starts some configured programs through its sh, where `false` is a builtin, and others itself, where it is the install's `false.exe`, and it doesn't look in the repository for it. These were checked against Git for Windows 2.53 (`git.exe` of `C:\Program Files\Git`), natively: `GIT_CONFIG_NOSYSTEM` and `GIT_CONFIG_GLOBAL=NUL` are honoured, so the system `core.autocrlf=true`, credential manager and LFS filters stay out; the hook, signature-verifier, alternate-refs, external-diff, textconv and askpass settings each stop a program the repository names (each with a control showing git runs it otherwise); `GIT_NO_LAZY_FETCH=1` keeps a partial clone's missing blob unfetched; and the pull-request fetch runs without prompting. The `~/` the policy expands is the home git expands: `HOME`, else `HOMEDRIVE` and `HOMEPATH` if that is a directory, else `USERPROFILE`.

## Host assertions

Inside gVisor or another container, a host may run `none` and declare the outer isolation itself; such a declaration is a host assertion, not a zelk guarantee, and is recorded as one.

## Escape suite

On Windows, `go test -tags=integration ./env/launcher/ ./env/local/` in `core` requires
`ZELK_MXC_EXEC` set to the absolute path to the signed executor, and fails without it
rather than skipping. The PowerShell 7 test needs
`ZELK_POWERSHELL_TEST_ARCHIVE`, a local copy of the pinned
`PowerShell-7.7.0-win-x64.zip` (the Store edition can't run under MXC), and
the setup test in `cmd/zelk` needs `ZELK_MXC_TEST_ARCHIVE`, the pinned MXC SDK
tarball. Each attack runs first without a launcher, where it must succeed, then under MXC,
where it must reach the operation and be refused. The launcher tests cover a
read outside the workspace, listing and metadata under the home stand-in
(with and without a grant inside it), a sibling write, a Credential Manager
entry the test wrote, IPv4 and IPv6 host loopback over TCP and UDP, opening the
host process and the workload's parent, and a controlled inheritable handle.
They also run native argv, Windows PowerShell 5.1, unpackaged PowerShell 7,
`.cmd` and `.bat` files from a nested directory, and a policy long enough to go
by file. The local suite compares Git input mutations, including hard-link,
junction and symbolic-link aliases, linked worktrees' administrative
directories and the rename of `.git`, with the pins off as the control; checks
the layouts startup refuses; and verifies that Git status, add and commit still
work. It also ends a command by normal exit, `Kill`, `Close`, killing only the
executor and killing the host that owns the job, and requires the executor, the
command and its child to be gone each time.

On Linux and macOS, `go test -tags=integration ./env/launcher/` (from `core/`) runs scripts that try to read a file outside the workspace, list a home directory stand-in, write outside the workspace and into `/usr`, read `/etc/shadow`, connect to a host TCP listener, reach a host UNIX socket, read a credential from the environment, read an inherited descriptor, and see or read the host process through `/proc`. Each runs first without a launcher, where it must succeed, then under the launcher, where it must fail. The Linux suite requires a working `bwrap`; the macOS suite `sandbox-exec`. `go test -tags=integration -run TestSandbox ./env/local/` adds the git-input attacks of [Git inputs in the sandbox](#git-inputs-in-the-sandbox), each run first without a sandbox as a control, with `git status`, `add` and `commit` as positive controls.

## Browser profile (bwrap)

`Bwrap.WrapBrowser` starts a browser for the agent ([browser design](/internals/browser/#confinement)) in a profile that differs from a command's in three ways.

- **Sockets.** Chrome needs UNIX sockets, socket pairs and netlink between its own processes, so its filter allows `socket` for AF_INET, AF_INET6, AF_UNIX and AF_NETLINK and allows `socketpair`; it denies every other family, `io_uring_setup`, `ptrace` and `process_vm_writev`, with the same architecture checks as the command filter. The filter applies in every network mode, `full` included, where commands run without one. A UNIX socket reaches only socket files the profile binds and abstract sockets of the browser's own network namespace, new in `off` and allowlist modes.
- **Binds.** The system directories (credential files masked), the browser's install and its libraries read-only, the workspace read-only, the browser's data directory (profile, downloads, captures) writable, a fresh `/tmp`, and nothing of the launcher's own read-only or writable paths. With network `full`, the files that `/etc/resolv.conf`, `/etc/hosts` and `/etc/nsswitch.conf` lead to, when they are links out of the system directories, are bound read-only as for a command (Name resolution with network `full`, above), after the read-only binds and before the masks; without them Chrome would see a dangling `/etc/resolv.conf` under WSL or systemd-resolved. `off` and allowlist get none. The data directory may not overlap the workspace. Every socket file in the workspace is covered with `/dev/null`: `WrapBrowser` walks the workspace first, without following symbolic links, and fails with `ErrWorkspaceUnchecked` if the walk passes 200,000 entries or two seconds or meets a directory it can't list, which could hold a socket the browser reaches by name. The host may then start the browser without the workspace. A socket created in the workspace after the browser starts is not covered.
- **Descriptors 3 and 4** reach the browser for the DevTools pipe. The launcher marks the host's other descriptors close-on-exec first, as for a command.

The sandbox's first process is a helper (`launcher.BrowserHelper`, dispatched by the host's own executable, bound at `/zelk-browser/helper`). It disables dumpability as the command relay does, relays loopback ports to host sockets, then starts itself again to install the filter and exec the browser, passing descriptors 3 and 4 on and closing its own, so the host's end of the pipe sees the browser exit.

- **Allowlist.** The egress broker's socket is bound at `/zelk-browser/proxy.sock`; the helper relays a loopback port to it and gives the browser `--proxy-server` for that port with `--proxy-bypass-list=<-loopback>`, so loopback goes through the broker too, which refuses it. The namespace has nothing else.
- **Local ports** (`Browser.Local`, decision D3 of the browser design). In `off` and allowlist modes, each port the user names is relayed from 127.0.0.1 and ::1 inside the sandbox to a host UNIX socket bound at `/zelk-browser/local/PORT.sock`, which the host serves with `launcher.Forward` to that port on the host's loopback. The bypass list names exactly these ports. Nothing else on the host is reachable. `full` shares the host's network and refuses them.

## Browser profile (seatbelt)

`(*Seatbelt).WrapBrowser` runs Chrome under `sandbox-exec` with a profile of its own ([browser](/internals/browser/)). Chrome's own sandbox can't nest inside seatbelt: Chrome starts, but its first renderer dies with a trap. So the browser runs with `--no-sandbox` and the seatbelt profile is its only confinement, renderers included. A renderer exploit reaches what the profile allows, not less; under bwrap Chrome's own sandbox still isolates each renderer.

- **Reads:** the system directories, the app bundle, `Browser.ReadOnly`, the workspace and the data directory. Not the home directory or any other file; macOS's metadata reads stay allowed, as for commands.
- **Writes:** the data directory, `/dev/null`, `/dev/dtracehelper`, and Chrome's singleton: a directory and socket named `com.google.chrome.for.testing.*` in the per-user temporary directory, which Chrome uses whatever `TMPDIR` says.
- **Network:** `full` allows everything. `off` allows none but Chrome's own UNIX sockets, and each local port (`Browser.Local`) as `remote ip "localhost:PORT"`; seatbelt shares the host's network, so no relay is needed. Allowlists are refused for seatbelt, as for commands.
- **Processes:** fork and exec, Mach lookups and registration, POSIX shared memory and semaphores, IOKit and preferences, which Chrome's processes need between them, and read extensions on what it may read anyway.
- **Environment:** the commands' allowlist, with `HOME` and `TMPDIR` set to the data directory.

The Mac job (`make test-chrome-mac`, CI's `macos-browser`) starts the pinned Chrome under this profile in each mode and checks that a workspace file loads, a file outside it doesn't, and the host's service is reached only with `full` or a local port.

## Browser profile (mxc)

`(*MXC).WrapBrowser` starts Chrome inside Microsoft's Windows process container ([browser](/internals/browser/)). Chrome's own Windows sandbox crashes inside MXC (`STATUS_BREAKPOINT`), so the browser runs with `--no-sandbox` and MXC's process container is its sole confinement, renderers included: a renderer exploit reaches what the MXC policy grants, not less.

- **Helper and transport.** `wxc-exec.exe` does not inherit host pipe handles into the container, so it starts `Browser.Helper` (`zelk --zelk-browser`), which creates local DevTools pipes inside MXC, launches Chrome with `--remote-debugging-io-pipes`, and relays `stdin` and `stdout` across them. `zelk`'s Windows setup grants `ALL APPLICATION PACKAGES` (`S-1-15-2-1`) read and execute access to Chrome's runtime files so Chrome can start inside the container while keeping the manifest, profile, and captures private.
- **Filesystem:** `Browser.Data` is `readwritePaths`; Chrome's install directory, the helper file itself (never its directory, which may be Downloads or a home directory; MXC accepts a file in `readonlyPaths`, as for a command's executable), `Browser.ReadOnly`, and `Browser.Workspace` (when set) are `readonlyPaths`, and a read-only grant, Chrome's directory or the workspace that covers the denied home directory is refused as it is for commands; nothing of the command launcher's own toolchain grants or writable caches is included. `deniedPaths` hides home entries outside grants while leaving grant ancestors traversable, and drive enumeration covers the granted drive roots, as for commands.
- **Network:** `off` sets `egress.default: "deny"` and `full` sets `egress.default: "allow"`. Host loopback stays closed in both modes, so `Browser.Local` ports are refused; `allowlist` is refused for the browser under MXC.
- **UI and environment:** `ui` uses `{"disable":false,"clipboard":"none","injection":false}`, `cwd` is `Browser.Data`, and the environment uses the MXC allowlist without command toolchain overrides (`LOCALAPPDATA`, `TMP`, and `TEMP` belong to MXC's per-run private directory).

`TestWindowsMXCChrome` in `core/browser` runs the pinned Windows Chrome unsandboxed as the control (reading workspace files, a `Config.Files` file outside the workspace, and a host HTTP listener) and under MXC in `off` and `full` modes, verifying the outside file and host loopback are refused and `chrome://sandbox` reports `Not Sandboxed`.

**What pages may load.** In every mode, unsandboxed too, the driver keeps pages to the files the session may read (`Config.Files`): `file:` URLs load only inside the workspace, the browser's data directory and the session's scratch directory, with symbolic links resolved. Every tab and followed iframe intercepts `file:` requests, and a refused file fails before any route sees it. A popup showing a refused file is sent to `about:blank`. `Navigate` refuses `javascript:` URLs and `chrome:` pages other than version, gpu and sandbox. This is the driver's rule, not the sandbox's: unsandboxed, Chrome itself could read any file the user can, and only the driver's interception stands in the way.

**The browser and `Enforcement()`.** The browser is a host tool, so the Environment's matrix doesn't describe it. Its confinement is the bwrap profile under bwrap, the seatbelt profile without Chrome's own sandbox under seatbelt, and the MXC browser profile without Chrome's own sandbox under mxc. Unsandboxed, it is Chrome's own sandbox and the driver's URL policy. The hosts run it in the commands' network mode, give it its own egress broker in allowlist mode, and say in their startup line when Chrome's own sandbox is off.

`TestBrowserProfile` in `cmd/zelk/internal/host` runs the test binary as the browser in each network mode. It must get UNIX sockets, socket pairs, netlink, the pipe on descriptors 3 and 4, workspace reads and data-directory writes; it must be refused `io_uring_setup`, `ptrace`, `process_vm_writev`, AF_ALG and AF_VSOCK sockets (EPERM), workspace writes (EROFS), a socket listening in the workspace (ECONNREFUSED, it is covered), a host socket outside the binds and a file outside them, and a host TCP port in `off` and allowlist modes; it must reach a named local port over IPv4 and IPv6 in those modes, and in allowlist mode an allowed host but not a refused one or loopback through the proxy. Without the filter the same test fails on each denied call.

## The user's browser

`-user-browser` drives the user's own browser through zelk's extension
([user-browser.md](/internals/user-browser/)). No launcher confines it: it is the
user's, running as them, outside the sandbox, and it is not in
`Enforcement()`. What holds instead, in layers that don't trust each other:

- **The extension** (`core/browser/extension/policy.js`) answers only a
  paired zelk, over loopback, attaches only to tabs in zelk's tab group,
  allows a fixed list of CDP methods (none that read cookies or storage
  or change requests; `Runtime.addBinding` only for a watch's own world),
  starts traces only with zelk's categories, reads only the trace streams
  it handed out, and shows credential headers as `[removed]`. A site's
  cookies leave it only after the user's Allow in its panel, read by the
  extension itself (`Zelk.exportSession`). The user's Stop refuses every
  call until they resume.
- **The driver** (`Attach`'s browser) never types into password,
  one-time-code or card fields nor while one has focus, refuses a page
  script's value that holds one, blanks credential fields in post bodies,
  fetches and downloads only the page's own site, writes files only beside
  its captures (an exported sign-in mode 0600), and emulates only in tabs
  zelk opened ([browser-automation.md](/internals/browser-automation/)).
- **Permissions**: every tool carries `tool.WithPersonDecides`, so a
  person or a rule decides, never the classifier, and
  `tool.WithTrustedTab`: a call in a tab of zelk's group, which the user
  shared or approved opening, runs without asking while a person attends,
  and only opening a new tab is decided per call (A13). A rule is the
  user's trusted site (`user_browser_*(domain:SITE)`), and in a headless
  session only an allow rule or one of the user's hooks (a `PreToolUse` allow or a `PermissionRequest` approval) lets a call that acts go ahead, in bypass mode too. The session
  export names no URL, so no rule covers it headless; the panel decides
  it every time.

The pairing key, which drives the user's browser, lives with the other
credentials in the config directory, which the sandboxes hide from
commands.

## Subprocess egress allowlist

On Linux amd64/arm64, `bwrap` supports `network=allowlist` with a trusted injected
HTTP/CONNECT broker on a private UNIX socket and an executable relay. The CLI
and TUI own both. The ordinary profile explicitly includes `--cap-drop ALL`.
Allowlist mode never uses `--share-net`. It additionally read-only binds the
relay at `/zelk-egress/relay` and the broker socket at `/zelk-egress/proxy.sock`,
then invokes `relay --zelk-network-relay socket -- command args...` inside the
isolated namespace. The full constructor probe follows this path before startup.

The relay creates a loopback TCP endpoint, forwards it to the private UNIX
broker, overrides HTTP(S)/ALL proxy variables and clears NO_PROXY. It disables
dumpability so child processes cannot inspect its descriptors or replace its
code through ptrace/procfs. Descendants execute through a dedicated helper that
locks the OS thread, sets `PR_SET_NO_NEW_PRIVS`, installs a seccomp BPF filter,
and execs the requested command. The filter verifies the native audit
architecture, denies x32/high syscall numbers, permits `socket` only for
AF_INET/AF_INET6, and denies `socketpair`, `io_uring_setup`, `ptrace` and
`process_vm_writev`. Both parent and child helpers must be trusted implementations
of this protocol; embedding hosts inject their helper executable explicitly.

Blocking UNIX socket creation is not sufficient: a connected UNIX datagram pair
can reconnect to a host socket inside a bound workspace. The socketpair denial
closes that bypass. The relay alone
retains UNIX socket access, while the command sees only the namespace's
loopback network. Closing a relay joins all connection pumps and its child;
closing the host stops/joins its HTTP broker and all tunnels. Socketpairs,
UNIX-socket IPC, io_uring and debugger use are intentionally unavailable in this
mode. It is a network policy, not a general CPU/memory resource limit.

On Windows, `mxc` uses the same HTTP/CONNECT broker directly. The host binds
an ephemeral TCP port on `127.0.0.1` and the launcher sets both spellings of
`HTTP_PROXY` and `HTTPS_PROXY` and clears both spellings of `NO_PROXY`.
Direct outbound TCP, other host loopback TCP/UDP and the host's LAN address
are denied, but a Windows DNS lookup can leave without passing through the
broker. zelk prints a DNS
notice on the first MXC allowlist run for the state directory. The managed
browser refuses this network mode under MXC.

Broker rules authorize exact ASCII domains/IP literals, or wildcard subdomains
excluding the apex. Ports are explicit or default to 80/443. Each HTTP authority
or CONNECT destination is checked, every DNS address must pass `fetch.Blocked`,
and the connector receives a pinned numeric address. Proxy/hop headers are
removed. Redirect requests are checked again; CONNECT permits a TCP tunnel to
its authorized authority without decrypting application traffic. Private,
loopback, link-local and metadata destinations are always refused. The host's
provider transport retains its independent policy: a run can't work without it, and the user chose that endpoint for the session. The CLI and TUI apply the network setting to what they reach on the agent's behalf from the host: with `off` there is no WebFetch or WebSearch and no HTTP MCP server, and with `allowlist` WebFetch and HTTP MCP servers admit only the listed hosts, redirects included, and there is no WebSearch, since a search backend receives whatever the query says. An MCP server's OAuth renewals are held to the same list, so an authorization server on another host must be listed too. A listed loopback address is reachable by an HTTP MCP server, unlike a sandboxed command, because the user named both the server and the host. An allowlist limits where data can go, not what is sent.

`TestBwrapNetworkAllowlist` in `cmd/zelk/internal/host` verifies actual namespace,
relay and command-filter composition with local fixtures and no external DNS or
network. Broker unit tests cover host/port matching, mixed DNS answers, pinned
addresses, redirects, CONNECT half-close and shutdown. The existing escape suite
continues to apply to off/full profiles. Allowlists are not yet implemented
on macOS: a seatbelt host refuses them at startup.
