# Local worker and sandbox

Scope: the hub-native local worker, its tools, path guard, denylist and seatbelt sandbox. Read before editing `src/adapters/local-worker.ts`, `src/local/`, `src/memory/capture.ts` (reads the denylist), `src/hub/facts.ts` (denylist and large-file stamps), `src/hub/git.ts`, the grant filter in `src/hub/permission-mode.ts`, or the sandbox root in `src/hub/instance-execution.ts`.

- Before editing a probe-only lifecycle, capability or sandbox branch, read `docs/design/guidance-probes.md` (T2 confined adapter contract).
- Nothing the local worker executes may run outside `sandboxedExec`; a new tool that spawns a process goes through it, and a tool that touches a path goes through `guardPath`.
- Use `sandboxCommandEnvironment` for the per-command `TMPDIR` and package-manager cache defaults in both `sandboxedExec` and the sandboxed host shell wrapper; explicit cache values win, and the owned temp directory is removed after the command.
- The headless Claude host wrapper (#845, `HostShellWrapper` in `src/hub/claude-shell-wrapper.ts`) runs its read-only and check/test/build grants under this same `profile()` plus a deny-only refinement (`src/hub/task-shell-sandbox.ts`, and the hub state dir): it repeats `sandboxedExec`'s own-temp allow suffix and its `readOnlyData` broad-write guard, so change both places together, and keep the refinement deny-only. The wrapper and the read-only shell proof take their fixed environment from `hostShellEnvironment` (`src/local/shell-environment.ts`), which must equal the baseline `sandboxedExec` builds inline (`test/claude-shell-wrapper.test.ts` compares them); never inherit a native agent's environment there.
- A timeout or abort in `sandboxedExec` marks the result `(killed: <signal>, timeout?)` from its own `killRequested` flag, never only from the exit signal: a shell may report its killed child as a normal exit 137.
- The sandbox denies home reads by default (toolchain dirs, the project and its real git dir excepted) and all network, loopback included: claude-mem and the Codex app-server listen on loopback without auth. Tests that bind a local port therefore fail when the worker runs them, also with `local.bash_network: true` (the egress proxy keeps loopback closed, and the proxy variables send a test's plain-HTTP `fetch` to the proxy, which refuses it); that is the intended trade-off, and `"direct"` is the switch until a later release removes it.
- The seatbelt profile refuses the `.git` name itself at any depth (creation, rename, symlink, gitfile), `config`, `config.worktree` and `hooks` directly under it, `commondir` at any depth below it or below an external git dir, and `.agenthub` anywhere in the project, every name folded against the 16 code points HFS+ ignores (#270). Every `modules/` tree the project can reach (the common dir's, the worktree's own, every linked worktree's under `<common>/worktrees/<wt>/modules/` as a pattern so a tree or worktree that does not exist yet is covered, #518, and each discovered submodule's own `modules/`) refuses EVERY write that is not inside a discovered submodule git dir (#520): nothing is exempt by name, so a fake git dir called `refs`, `logs` or anything else cannot be planted for a later unsandboxed `git submodule update --init` to reuse. Inside each discovered git dir `D` the refusals are anchored to `D`: `D/config`, `D/config.worktree` (folded in both halves), `D/hooks` and what is below it, and `D/worktrees/*/config.worktree`, with `D/worktrees`, each `D/worktrees/<name>` and `D/hooks` refused as directory entries too, so none can be moved out, edited and put back; a submodule's own linked worktrees keep a `modules/` of their own at `D/worktrees/<name>/modules`, which gets the same everything-not-discovered refusal by pattern (so one that does not exist yet is covered) and has its `modules` entry refused as a target; `D/logs`, `D/objects` and `D/index` stay writable, and since #1123 `D/refs`, `D/packed-refs`, `D/HEAD` and `D/worktrees` are refused like the project's own (`gitRefRules` gets the discovered dirs), so commit, branch, tag and rebase fail in a submodule too, and a submodule really named `refs` or `logs` is protected like any other. `hooks` is anchored by path depth (`hooksUnder`), never by an unanchored any-prefix name, which also matched a project under a directory named `hooks`. The worktrees container and each worktree git dir are refused as directory entries too (otherwise an ancestor can be moved out of the protected path, edited and moved back), and so are the discovered git dirs, the modules root and the components in between (rename, replace, symlink, recreate). Keep every regex literal under 1024 bytes (UTF-8 bytes, not characters), and never put the git path and a folded name in one literal: the root is its own `require-all` filter, so the folded literals are the same size at any path length (`test/sandbox.test.ts` asserts it). Known residuals: a nested repository in bare layout (the hub never runs git there; docs/security.md), folded spellings of the components between `.git` and a submodule's git dir on a volume that folds names (the 1024-byte SBPL literal cannot hold a folded path; external git dirs carry the same residual since #270), and the submodules of a repository nested inside the project (only the project's own common dir is discovered). An external git dir's `config`/`config.worktree`/`hooks` rules, and the pattern rules for every linked worktree git dir under `<common>/worktrees/`, cover only its own children plus the hooks directory's contents: at any depth they would deny refs named `config` or `hooks` in a worktree or submodule project. The fold is a group alternation, never a character class (the seatbelt regex engine is byte-oriented and a quantifier after a multi-byte class member binds to its last byte), and every pattern keeps its `^` anchor (an unanchored starred alternation does not match). Folded literals never contain the project root: an SBPL string literal dies at 1024 bytes. The cost: `git init`, `git clone` and `git worktree add` do not run inside the sandbox, and neither do `git worktree remove`, `git worktree prune` of a stale record, `git clean -ffd` with a nested repository, `git submodule update --init` (its git dir's `config` write is refused), or `rm -rf` of a directory holding a `.git`.
- The shared object store `<common>/objects` takes only NEW loose objects from a sandboxed command (`objectStoreRules` in `src/local/deny.ts`, #864): every write under `objects/info` (alternates, http-alternates, commit-graph) and `objects/pack` is refused, so are the `objects`, `objects/info` and `objects/pack` entries, the unlink or rename of a fan-out directory, and data, unlink, mode and flags writes to an existing loose object. Keep loose-object creation allowed (sandboxed `git add`, `commit`, `stash` need it) and never reopen packs or `objects/info` for a sandboxed command: git reads packs before loose objects and never rehashes on read, so either one replaces content that every checkout and the #845 host add/commit/push trust. `test/sandbox.test.ts` "(#864)" proves it with the real sandbox-exec. The cost: `git gc`, `repack`, `fetch`, `maintenance` and `commit-graph write` run outside the sandbox. A hardlink to an existing loose object is refused too (into the project and into the command's own temp dir); keep that case in the test. Residual: an object id that does not exist yet can be planted before git writes it; a local checkout then shows the planted bytes, and a push of that commit is rejected by the receiving side, which rehashes what it receives ("missing necessary objects"). The upgrade path is host-side git writes as in #845.
- Build every git invocation outside the sandbox through the single implementation exported by the first-party `@staix/agent-mem/platform` entry (`memoryGitArgv`/`memoryGitEnv`/`memoryGitSync`), re-exported as `hubGitArgv`/`hubGitEnv`/`hubGitSync` by `src/hub/git.ts`. Keep the git export identity, behavior and direct-spawn tripwire checks in `test/hub-git.test.ts` passing; retain home compatibility and Node-safe process-entry checks in `test/memory-parity.test.ts`. The sandboxed git tool in `src/local/tools.ts` retains its own behavior. Use `{ credentials: true }` only for the memory repository the hub creates itself, never a project's repository. Use the core deny policy re-exported by `src/local/deny.ts` for guards, sandbox rules and capture; do not add another denylist.
- SBPL strings go through `sbplString` (the plain `"..."` form). In the raw `#"..."` form a backslash escapes nothing, so a `"` in a path ends the literal and the whole profile fails to parse.
- Seatbelt sees absolute paths, so `local.deny` entries are anchored under the project root.
- `guardPath` walks with `lstat`, never `existsSync`, which follows symlinks.
- `guardPath` judges the denylist and the hub-owned names (`.git`, `.agenthub`) on two names, the resolved one and the one the caller typed (#541): Bun's realpath sometimes names another hardlink of the same file, so the resolved name alone let a denied `.env` hardlink through about 1 call in 100 on macOS. A refusal on either name stands; the typed name only adds refusals, and only a typed name INSIDE the project is judged (`insideRoot`, #555, the same bound `Facts.rel` and the deliverable vetting use: a name like `../o/.env` that links into the project is no project path, and judging it made main red after #943 and #944 met); containment, the `data.readonly` hardlink refusal and `matchesPolicy` are unchanged. `test/path-policy.test.ts` runs 5000 iterations per layout, because a single call passes the unfixed guard 99 times in 100; keep the loop counts.
- git arguments never pass through `guardPath`; `gitArgsProblem` refuses absolute paths, `..`, `--no-index` and denylisted `rev:path` forms.
- A worker turn builds its messages in a local array and joins the history only as a whole. Never push to `history` mid-turn: one tool call without its result poisons every later request.
- After a tool with side effects ran, a failed turn is reported, never redelivered.
- A turn with any remote envelope (`remoteEnvelope(env)`: `from` containing `@`, or a hub `invocation`/`invocation_result` carrying `refs.invocationRemote`; rooms #941, #992; never test `from` alone) never joins `history` and never reaches `capture.observe`, like a PII turn, and every failure it reports (answer, delivery reason, log line) says only `remote turn failed`. Keep all three when you touch the turn's settlement or the tool loop.
- A review turn (any envelope `isReviewObserverExcluded` accepts, or an anchored `hub_review` call, which latches the exclusion for the rest of the turn; both in `src/hub/memory-policy.ts`; any `hub_evidence_read` call latches it the same way, #931) is handled like a remote turn: it never joins `history`, never reaches `capture.observe`, `capture.summarize` or `observeTool`, and every failure it reports (answer, delivery reason, log line) says only `review turn failed`. While latched, `hub_remember` and `hub_task_propose` are refused before they reach `taskTool`. A throwing `beforeInput` settles the delivery `failed_safe` (`review input provenance unavailable`) before the turn starts. Keep all of these when you touch the turn's settlement or the tool loop.
- `ctx.permit` answers a `ToolApproval` (`true`, `false`, `"expired"`, `"aborted"`, #253): only `true` permits an effect, so never test it for truthiness. A tool returns `approvalError`'s text for the rest: a denial, the expiry (which tells the model not to retry) or the withdrawal. A turn that two unanswered approvals ended (`ApprovalWaitStop`; counting rule: `adapters.md`) completes its missing tool results, settles its delivery `completed` with the reason and is never handed back for replay, also when no tool had a side effect.
- `Facts` (`src/hub/facts.ts`, #428) names a large file whose ctime is under `RACY_MS` by its git blob id: in `load()` and `observe()` only through `racyBlob()` (per-file `RACY_HASH_MAX_BYTES`, per-store `RACY_BURST_BYTES` per event-loop turn, memo cleared at `boundary()`), past which it keeps the stat-only stamp and makes no claim; `atHead()` keeps its own `HASHED_BYTES` bound, `tree()` reads large files by stat only, and `largeBlob()` caches only settled stamps.
- Hub tool calls (`hub_send`, `TASK_TOOL_NAMES`, `CONDUCTOR_TOOL_NAMES`) are never passed to `capture.observe`; `Tasks` alone decides what hub tool text reaches memory (#230). Keep `hub_ask_answer` explicitly excluded from `observeTool` too: its question and answer are not capture evidence (authority and read-view rules: `daemon.md` and `tasks.md`). Every live `capture.observe` passes a host `sourceId` (`<session>.<turn>.<step>.<n>`, #752); a new host caller supplies one too. Capture stores `paths` only for `read`/`write`/`edit` and only project-relative ones: command argv is never path metadata.
- A tool that asks for approval passes its name to `ctx.permit`, and `write`/`edit` also the `guardPath` result, never the model's path string: also pass the original path separately through every permit wrapper, and every tool its parsed arguments as `input` (the always-ask classifier reads it, #750; rule: `adapters.md`); `ask-when-needed` grants only when both the original project-relative spelling and the real path avoid protected names through `grantablePath` (`src/hub/permission-mode.ts`). `bash` and mutating `git` pass no path. After the awaited approval `write`/`edit` run `guardPath` again and refuse a target that changed (#242).

- Honor the live `protect_instruction_files` policy in scoped grants for the instruction names in `INSTRUCTION_FILES` (`src/hub/permission-mode.ts`: `AGENTS.md`, `CLAUDE.md`, `QWEN.md`, `GEMINI.md`); keep reads, explicit approval and never-ask unchanged. Only the settings registry writes this machine-local policy (#323).

- Bounded task wait (#1454): the daemon passes `taskWait` to `LocalPeer`; `profileTaskTools` includes `hub_task_wait` only when the idle sweep is enabled. Do not infer or read that setting in the worker; the authority and wait rules live in `tasks.md`.

- For sandboxed task checks, use the opt-in hub-owned bounded container runner; never widen Seatbelt, expose credentials, mount host paths or fall back to a host command. Keep spec/check arguments and results out of capture.
- The `bash` tool asks `ctx.permit` with the frozen input, then `ctx.shellExecutionCheck` right before the sandbox spawns (#816): `valid` runs, `ask` repeats the permit once with `{ forceAsk: true }`, `aborted` or a cancelled signal returns "turn cancelled before shell execution". `LocalWorker` binds the check to its turn generation, so a stale turn cannot spawn. A fake `ctx` in a test supplies `shellExecutionCheck` or accepts the `valid` default; never make it return `valid` for an aborted turn.
- `web_fetch` (#515b, `src/local/web-fetch.ts`) is opt-in like `doc_read` (never in `TOOL_SCHEMAS`; offered only when `local.web_fetch.allow` names a host) and carries the owner's PII rule: it is refused for the WHOLE turn of a PII task, whatever the host, and that refusal is the first thing `webFetch` does, before the URL, the list or the proxy is read, so the answer and the timing do not depend on the request. Never move another check in front of it, and never give it a way to accept a PII turn "for a clean URL": the URL or a query could carry PII to the web, which `pii.paths` and `sanitize()` do not cover. It runs only through its OWN `startEgressProxy` (`webEgress` in `daemon.ts`, list `local.web_fetch.allow`), never the bash proxy: do not merge the two lists or reuse the bash proxy for it. The model sets only `url`, `offset` and `limit`; keep the request a bare GET with no model-chosen header, body or method, keep redirects manual and re-checked, and keep the result and the URL out of `capture.observe` and the research observation on every turn. The pure host checks live in `src/local/web-fetch-config.ts` because the config schema reaches the Claude channel bundle: keep that file free of file-system and process imports.
- `doc_read` (#515a, `src/local/doc-read.ts`) is an opt-in tool, never part of `TOOL_SCHEMAS`: the worker offers `DOC_READ_SCHEMA` only when the daemon passes `tools.docRead` (`local.doc_read`, machine-local, never editable from settings), and `runTool` refuses it without the port. It goes through `guardPath` (read), then `pii.paths` by path, then the converter (`TextProjections`, the person's `text_projection`), then `signals.pii_patterns` by text, then `sanitize()` and the output cap; a PII task turn passes the first two screens, an ordinary turn does not. Its result is never passed to `capture.observe` or `onTool`: keep both exclusions when you touch the tool loop in `src/adapters/local-worker.ts`.
- Hub-made task worktree (#1115, 2026-11-02, `src/hub/task-worktree.ts`; rules for `Tasks`: `tasks.md`): the sandbox profile is NOT widened for it. Since #1123 a sandboxed command can no longer write `.git/refs/**` or `.git/worktrees/<name>/**` (next line), but the hub does not rely on the profile and still treats the worktree admin dir and the branch ref as peer-writable: it records the base commit at creation (in `<state>/task-worktrees.json`, outside every sandbox root) and commits only when the worktree is still registered at its path, HEAD is the task branch and the tip is the recorded base or the hub's own last commit. `test/task-worktree-sandbox.test.ts` pins both halves with the real profile, and fails if the profile text changes when the hub makes a worktree. Never say in docs or errors that the sandbox cannot write `.git`: say what it cannot (gitfile, config, hooks, commondir, packs, and since #1123 refs, packed-refs, HEAD and worktree admin files); the main index, logs and new loose objects stay writable.
- Refs, HEAD and worktree admin writes (#1123, 2026-11-03, `gitRefRules` in `src/local/deny.ts`): the profile refuses `refs/**`, `packed-refs*`, `HEAD*` and `worktrees/**` directly under a `.git` and under each external git dir, so a sandboxed commit, branch, tag, stash, switch and `git add` inside a linked worktree fail by design, and the hub commits instead (#1115). Keep every rule adjacent to its git dir: an unanchored `refs` or `worktrees` filter would match a project under `~/worktrees/` (`test/sandbox-git-refs.test.ts` runs projects below directories named `refs`, `worktrees`, `HEAD` and `packed-refs`). `.git` + `packed-refs` and `.git` + `worktrees` do not fit one 1024-byte literal (803 and 669 bytes folded), so they use a front literal plus a back literal, and the external-dir depth anchor falls back to the unanchored name past about 1000 bytes. A submodule's own git dir gets the same refusals (person's ruling 2026-11-03: deny `.git` writes, submodules included): `gitRefRules(gitDirs, subDirs)` takes the discovered submodule git dirs, so `test/sandbox-git-refs.test.ts` covers a submodule, a nested one and a linked worktree's. A submodule change by a sandboxed peer cannot be committed by the sandbox, and the hub's commit records a submodule only as a commit id: edits inside a submodule's working tree stay uncommitted there, and a changed gitlink refuses the whole hub commit (#1115), so that part needs a person or a vendor agent. A new test that needs a commit under the real profile makes it with the hub's git outside the sandbox, as `test/sandbox.test.ts` now does.
