Skip to content

feat(sbx): SBX0 1c, usable by the cohort (sandbox-client, sbx up/pull/mcp, agent config, janitor, audit, docs) - #554

Merged
pdettori merged 95 commits into
mainfrom
feat/sbx0-1c-usable
Oct 20, 2026
Merged

pdettori merged 95 commits into
mainfrom
feat/sbx0-1c-usable

Conversation

@pdettori

@pdettori pdettori commented Oct 19, 2026 •

Copy link
Copy Markdown
Member

Increment 1c of SBX0: usable by the cohort. Spec docs/specs/2026-10-15-sbx0-internal-sandbox-service-design.md (v1.1, amended here), ADR-0042.

A new user installs mocactl, runs mocactl sbx up in a repository, and gets a working loop. Claude Code or OpenCode works through a local MCP server, and every tool call runs in a fresh microVM. mocactl sbx pull --apply brings the result back as a patch. Operators can see who ran what, disk is reclaimed, and a user guide and a runbook exist. There is no proto change and no worker change.

Based on main: #546 (spec), #547 (1a) and #550 (1b) are merged.

@moca/sandbox-client (new package)

  • Exec client. The generated sandbox/v1 stubs (a second buf generate output) and SandboxExecConn:
    • TLS, and keepalive every 20 s;
    • token freshness: a timeout is capped at the token's life minus 60 s;
    • a started command is never re-run: only a refusal that arrives before the first event is retried, once, under the same req_id;
    • typed errors: machinery, busy, template-busy, token-expired, refused, and timeout as a result.
  • The seven sandbox tools, with Pi's names and input schemas but no Pi dependency (a contract test pins the schemas):
    • atomic writes (temp file, then rename), which keep the file's mode and symlinks;
    • edit refuses a truncated read before it writes, and follows Pi's CRLF and BOM handling;
    • a 14 MiB stdin cap.
  • createSandboxMcpServer.
    • A call that would wait more than 30 s behind this server's own call is refused as "sandbox busy" without being sent.
    • Every failure becomes a tool error that says so; none is ever shown as command output.

mocactl sbx

  • run, put, mcp.
    • run -- CMD… quotes each word and writes the output byte-exact. Exit 124 means a timeout, 125 a sandbox failure.
    • mcp finds its sandbox and control plane from .sbx/sandbox.json, so the agent launches it with no arguments.
    • A flight recorder keeps metadata only.
  • up, push, pull [--apply].
    • A tar writer with no dependencies. The baseline is kept at refs/sbx/baseline, and pushed files under ignored directories round-trip.
    • The unpulled check and the emptying of /workspace run in one Exec.
    • pull --apply tries a plain apply, then a dry-run 3-way merge in a scratch index; it never applies half a patch.
    • pull --apply refuses any patch that writes the laptop's agent configuration or local hooks, on either side of a rename, under case and Unicode folding. That covers .mcp.json, .claude/, opencode.json(c), .opencode/, .vscode/{tasks,settings}.json, .husky/, .envrc, .git and .sbx. Without this, an agent in the sandbox could plant a hook that runs on the laptop.
    • Each worktree gets its own sandbox.
  • Agent configuration.
    • up merges entries into .mcp.json, .claude/settings.json, opencode.json and marked blocks in CLAUDE.md/AGENTS.md. It never overwrites; a conflict stops it and names the file and key.
    • rm takes back exactly what up added, byte for byte. A cut-only guard refuses any removal that would change anything else.
  • doctor, logout, and rm, which refuses while work is unpulled unless --force.

Relay

  • One audit line per sandbox Exec: who, which sandbox, outcome, timing and output size. Never the command text unless a debug flag is set, never output, never tokens.
  • The sandbox caller is moved out of main.ts. A failing audit write can never skip enforcement.

Deploy

  • The janitor. A systemd timer on the KVM host frees the workspaces of terminated sandboxes once the wait has passed. It also reclaims unknown directories once they have been idle past SH_WORKSPACE_IDLE.
    • It is fail-closed: it does nothing if the control plane is unreachable, never follows a symlink out of the root, parses numbers in decimal only, and keeps its token in a 0600 file.
  • status.sh shows attached workers, sandbox counts, disk use, the janitor's last run, and Exec p50/p95 and error rate from the audit lines. It also warns when a host's janitor wait has gone stale.
  • Size budget: mocactl.mjs is held to 7.7 MB (6.9 MB today). ripgrep is now installed in CI.

Docs

docs/sbx/user-guide.md (from install to pull --apply), deploy/sbx/RUNBOOK.md, and docs/sbx/security-review.md, the spec §9 gate as a checklist. The checklist marks each item as tested, true by construction, or waiting on the live run.

Live smoke

SBX_LIVE_SMOKE=1 deploy/sbx/smoke.sh runs the six §10.6 checks against a deployed service. Without that variable it prints one SKIP line and exits 0. RUNBOOK §13 covers its inputs. smoke.test.sh runs it against fakes, inside make test-deploy. Step 6's janitor uses the host's own wait (never a shorter one), so it never frees a workspace that a valid token can still reach.

Review fixes (review of 2026-10-20)

All 11 comments are addressed, and each thread has a reply naming its commit.

  • Must-fix (1e28091): pull --apply now reads a patch's old side through git apply -R --numstat, with the --- and diff --git headers as a backstop. A deletion with no header, or a ---/+++ mismatch, can no longer remove .claude/settings.json. Guarded paths also fold the way Windows resolves them.
  • mocactl (2e89428):
    • a .sbx/ that is a symlink or is tracked by git is refused;
    • an agent-config link into .git is refused;
    • a binding that names a different control plane gets a warning;
    • older tool names are added to the deny lists.
  • sandbox-client (566d00b, 390649a, ca0d315):
    • an error after the Exec was accepted is reported as "may have partly run";
    • a token with no time left past the 60 s margin is refused as expiring;
    • edit writes only if the file's sha256 is unchanged since it was read, and refuses mixed line endings.
  • Relay (e32d25e): a throw while building an audit line can no longer skip enforcement.
  • Deploy (280876b): status.sh shows a janitor run that failed on its own settings; skipped lines carry ts; the timer's no-op Persistent= is gone.
  • Carried from feat(sbx): SBX0 1b, sandbox identity and lifecycle (sandbox profile, sandbox tokens, relay verification, mocactl sbx) #550's review: the expiry-abort, drain-grace and keyed-req_id fixes are ported into sandbox-caller.ts. The drain release logs audit: "sandbox_release".

Follow-up review fixes (2026-10-20)

  • Must-fix (8a6f93d): the smoke's janitor step runs with the host's own SBX_JANITOR_AGE and refuses a shorter one. Its earlier 930 s override could free other users' workspaces on a host with tokens longer than 15 minutes.
  • smoke.sh (8a6f93d):
    • long waits and commands run as background jobs that the script waits on, so a TERM is handled at once and cleanup runs;
    • cleanup also deletes any live sandbox named with the run's prefix;
    • a failed sbx rm fails its step;
    • the RUNBOOK lists exit 2.
  • mocactl (ac29fe4): a tracked .sbx/ is detected case-insensitively, so a committed .SBX/ is caught. The 8.3 short-name refusal now matches only the shape Windows generates.

Verification

  • After the review fixes, on top of main: make lint, make typecheck, every package's tests, go test ./..., make test-deploy, the Python examples and the doc-link check all pass, as does setup.test.sh with MOCA_REQUIRE_WORKSPACE=1. The janitor tests also pass under GNU coreutils.
  • Every task had its own review, plus fix rounds with adversarial probes: tar round-trips, JSONC layouts, deletion attacks on the janitor, and attempts to bypass the pull guard. A whole-branch final review then ran, and its fix wave was re-reviewed.
  • Two known load-only flakes appear under full-parallel runs on a heavily loaded host: a supervisor shutdown-grace test and the mocactl Ink overlay tests. They are not in code this PR touches.

Before the cohort opens

  • The live acceptance with deploy/sbx/smoke.sh: the image, the deploy, the KVM host, two users, delete timing, a silent 5-minute command, and real Claude Code and OpenCode runs (spec §10.6).
  • A mocactl release that includes sbx. Until then, the user guide installs the edge channel.

🤖 Generated with Claude Code

…ADR-0042)

A new package, Pi-free and server-free, with its own generated stubs (a second
buf output, byte-identical to k8s-sandbox's). The new gen dir is excluded from
prettier and the whitespace hooks, and CI's codegen drift check covers it.

SandboxExecConn speaks TLS (an extra CA beside the system roots), pings every
20 s, draws req_ids below 2^53, and retries a token refusal once with a fresh
token only when no event has arrived: a started command is never run twice,
pinned by a test that cuts the connection after one chunk.

Spec v1.1 §6.5: before each Exec the token source is asked for timeout_s + 60 s
of life; timeout_s defaults to, and is capped at, the token lifetime minus
60 s, and a capped result says so. ExecError "timeout:<n>" is a result
(timedOutS), not a failure. ExecMachineryError carries a kind: busy
(RESOURCE_EXHAUSTED "sandbox busy"), template_busy (busy: queue full,
memory-budget:, max-runs:), token_expired (DEADLINE_EXCEEDED at exp) or
machinery. Refusals are ExecRefusedError.

The lockfile change is additive only, so CI's pnpm 9 accepts it frozen.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>
…etry fit, backstop

- An extra CA no longer drops the default roots: caBundle() takes
  tls.getCACertificates('default') where it exists (Node >= 22.15: extra
  and OS roots too), else tls.rootCertificates, then the CA PEM.
- A token lifetime under 121 s is a clear machinery error instead of a
  1 s timeout; a defaulted timeout is capped:true when it was actually cut.
- The UNAUTHENTICATED retry fits the timeout to the fresh token (its cap
  and remaining life), still under the same req_id.
- Each Exec carries a client-side backstop deadline of timeout_s + 90 s;
  its DEADLINE_EXCEEDED is machinery, kept apart from the relay's
  token-expiry DEADLINE_EXCEEDED by its details text.
- Comment why only "sandbox busy" RESOURCE_EXHAUSTED is busy.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>
…i (SBX0 §6.4)

bash, read, write, edit, grep, find and ls keep Pi's names, input schemas
(verbatim, held equal by a contract test that imports Pi as a dev dependency
only) and error wording, over an Exec with no Pi dependency. One Exec each, two
for edit, using the command shapes the prototype measured; plus sandbox_info,
which costs no VM.

- bash: no timeout of its own (the conn's cap); a timeout is Pi's "Command
  timed out after N seconds", and a capped timeout says so.
- The file tools send a 60 s timeout, so the held token serves them.
- edit refuses BEFORE writing when its read was truncated at 8 MiB, or the
  file is not UTF-8 (no silent data loss).
- grep passes -H, so a single-file search keeps the file name.
- Machinery failures and refusals are thrown, never returned as output.
- writeFileCommand(path) is exported for mocactl sbx put.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>
…, stdin cap, CRLF/BOM

- grep/find: --glob '!.git' goes last, since ripgrep's later glob wins; a user
  '*' or '**/*' no longer lists .git.
- writeFileCommand is atomic: a temp file beside the target, the target's mode
  copied, then mv; a symlink is written through and kept, and on any failure
  the temp file is removed and the original stays intact. write, edit's
  write-back and mocactl sbx put share it.
- MAX_STDIN_BYTES (14 MiB): write refuses larger content before sending, and
  edit refuses a larger result before its write.
- edit follows Pi's CRLF and BOM handling (without the fuzzy pass, which
  rewrites the whole file).
- NUL in model strings is an input error; read's sed hints quote the path.
- CI installs ripgrep; the real-rg tests skip only off CI.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>
…ames an unresolvable link

The rename-over write would replace a read-only file in a writable directory, which a plain write refuses; it now refuses too. A symlink that readlink cannot resolve (a loop, a missing parent) now says so instead of a bare exit 1. Root-only tests skip under uid 0.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>
Transport-free: the eight tools over one sandbox's Exec, on the SDK's
low-level Server so Pi's JSON Schemas pass through verbatim (no zod).
Its own calls run one at a time in arrival order; a call that would
wait more than 30 s behind the running one is refused as 'sandbox
busy', naming the running call and its elapsed time, and is never sent,
since sandbox/v1 has no busy frame. A cancelled queued call leaves the
line unsent.

Busy, template busy, token expiry, refusals, a terminated sandbox
(structural sandbox_terminated check, no mocactl import) and machinery
failures each come back as their own tool error, never as command
output (plan 1c R4). One record per call; a failing recorder never
fails the call.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>
…rds hold no command text

An abort listener never fires for a signal that is already aborted, so such a call waited out its turn; the queue now refuses it at once. The flight record of a client-side busy refusal no longer copies the running call's command line, which can hold a secret; the agent still sees it.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>
… logout (SBX0 1c R5i)

Settles the mocactl items carried from 1b before sbx grows:

- devicePrompt(io) and deviceLoginEnd() are shared by `mocactl login` and
  `mocactl sbx login`.
- buildRuntime takes a client factory, so the sbx runtime's control-plane
  client IS the SandboxApiClient. Its refresh-and-retry wiring records what a
  failed retry refresh hit in rt.lastRefreshFailure, which `failed()` reports;
  the duplicate onTokenRejected closure in sbx/cli.ts is gone.
- harness: false: the sbx runtime reads neither SH_HARNESS_URL nor
  config.harnessUrl, and builds no harness client or transcript store.
- `mocactl sbx logout` revokes the refresh token (best effort) and deletes
  sbx-auth.json; MOCA's auth.json is untouched.
- --json on login, logout and env is refused with exit 2.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>
… ADR-0042)

mocactl takes @moca/sandbox-client as its second allow-listed workspace
dependency. run passes output and the exit code through: 124 for a timeout
(ExecError "timeout:<n>") or a killed command, 125 for a sandbox failure. Its
timeout defaults to, and is clamped at, the sandbox token's lifetime minus
60 s, with a note. put writes stdin byte for byte through the atomic
writeFileCommand, refusing stdin over MAX_STDIN_BYTES. mcp serves the tools on
stdio with the token minted through the control plane and refreshed in
process, records each call to a 0600 flight-recorder file (never command
text, output or tokens), and exits when stdin closes.

Every sandbox id, from --sandbox or .sbx/sandbox.json, is checked before any
use. A bound sandbox's controlPlaneUrl is used when no flag or
MOCACTL_SBX_URL names one. Control-plane errors keep 1b's refresh-cause
reporting, and ApiError now carries the body's reason (deleted/expired).

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>
…e for byte; one Exec-failure text

Review round 1 of SBX0 1c Task 4.

- `sbx run -- CMD...` quotes every word (sandbox-client's q), so
  `grep 'a b' f` and a literal `$HOME` run as typed; shell syntax goes
  through stdin or `-- sh -c`. SBX_USAGE says so.
- The command's stdout and stderr go out as raw bytes (Io.outBytes and
  Io.errBytes, wired in main.ts): non-UTF-8 output is intact, and no newline
  is added; mocactl's own notes start on a line of their own.
- sandbox-client exports execFailureText(err, {audience}), used by the MCP
  server ('model') and by mocactl ('cli', without "not your command's
  output"), replacing mocactl's copy of the mapping.
- Pi stays out: the bundle test greps mocactl.mjs, and a layering test checks
  that sandbox-client/src has no @earendil-works import.
- Text from repo files is sanitized before printing; a binding URL must be
  printable ASCII; the exit-3 hint names .sbx/sandbox.json as the source.
- `sbx logout` leaves another control plane's login in place and names it.
- `sbx put` reads stdin only to MAX_STDIN_BYTES + 1 and refuses a TTY.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>
…ents match the code

A failed put printed the sandbox's stderr raw, so remote text could carry terminal escapes; it now goes through sanitizeRemote like every other remote string. The logout comments said it deletes any login, which the re-review's change made untrue.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>
…BX0 §6.2)

tarEntries writes regular files and symlinks with their mode, and adds a PAX
record for a path or link target that is over 100 bytes or not printable
ASCII. Each record's self-counting length is right across a digit boundary.
Paths that cannot be a relative tar member are refused. The round-trip test
extracts with tar and with Python's tarfile (the sandbox fallback, whose
command is shared); under CI neither reader may be skipped.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>
… (SBX0 §6.2)

planPush lists tracked files (even under an ignored directory) and untracked
ones that are not ignored, never .sbx/ and never secrets unless asked. It
refuses a file over 12 MiB by name and a tree over --max-push. The tree goes
in gzip tar chunks of about 8 MiB, each under the 14 MiB stdin ceiling, and
is extracted with tar or Python's tarfile. The baseline commits exactly the
pushed list (R6b) under refs/sbx/baseline, so work an agent commits in the
sandbox still counts as not yet pulled.

capture diffs the baseline against the workspace's tree and refuses a cut
patch. advanceBaseline commits exactly the tree that was pulled.
applyPatch first applies plainly, touching the working tree only. If a
touched file has uncommitted local changes it refuses with nothing changed;
otherwise it falls back to --3way and puts the index back. A patch that
writes .sbx/ is refused. writeBinding refuses an id or URL later commands
would ignore, and excludes .sbx/ via info/exclude.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>
…, §6.2)

up runs in a git repository. It plans the push and checks the binding URL
before any request. Then it reuses the bound sandbox if it is ready, or the
newest ready one labelled project=<repo id>, or creates one (template
"default" unless given). It binds the repository in .sbx/sandbox.json and
pushes, unless a reused sandbox holds changes not yet pulled: those are
left untouched, with a warning.

push is refused while changes are not yet pulled, unless --force. pull
prints the patch, or writes it with -o FILE. pull --apply applies it locally
and advances the sandbox's baseline only after a clean apply. sbx create's
template also defaults to "default" (spec §6.1). Each new flag is refused on
a command it does not belong to.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>
…tput is pulled (review C1)

BUILD_EXCLUDES match at any depth, so a new file beside a tracked
src/main/java/acme/build/Old.java was invisible to pull and hasUnpulled, and
a plain push discarded it. Every build-named directory holding a pushed path
(a placeholder such as .gitkeep aside) is now re-included: an anchored
negation goes in the sandbox's info/exclude, and the state check passes it
as -x, so it beats the repository's own .gitignore as the push did. Real
output (an unpushed build/, a node_modules/ inside the package) stays
excluded. The state check's scratch index is now a mktemp directory,
removed on exit.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>
…directory (review I2)

A tracked conf/settings.py whose conf/ was replaced locally by a link to
../outside was read through the link, sending a file from outside the
repository. Any path with a symlink ancestor is now skipped with a note; the
symlink itself is pushed as a symlink.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>
…(review I3)

On a case-insensitive filesystem a patch writing .SBX/sandbox.json
overwrote the binding, because the guard compared the path as-is. The push
list and applyPatch now share isBindingPath, which compares the first
segment lowercased and NFC-normalized. Tested with .SBX/ and .Sbx/.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>
…w I4)

The 3-way fallback ran git apply --3way for real. A conflict then left
markers, applied the clean files and staged them in the user's index, so
R6c was not met. The merge is now dry-run first with --cached, in a
throwaway index read from HEAD. A conflict is refused, naming the files and
pointing to pull -o FILE, and the tree, the index and the rerere state stay
byte-identical. Only a clean dry run is applied for real. A patch that
creates a file which exists locally but is ignored is now refused too,
instead of being merged over it.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>
…t's staging (review minor)

Given the captured tree, the advance no longer re-hashes the workspace. It
no longer runs a bare git reset over the agent's whole index either: only
the pulled paths' entries are reset to the new HEAD, so the agent's own git
status shows no reverse diff for them, and anything it staged since stays
staged.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>
…the workspace (review minor)

The unpulled check and the emptying used to be two Execs, so a change the
agent made between them was discarded. Without --force, push (and up, on a
reused sandbox) now runs the check in chunk 1's own command. A sandbox
holding changes is then refused with UnpulledError and nothing changed.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>
…nd refusal texts (review minors)

- repoId hashes the origin normalized to host/path: https, ssh and scp
  forms alike, with no .git suffix, no trailing slash and no userinfo, so a
  token in the URL never reaches the hash.
- .sbx/sandbox.json is written 0600.
- --template '' is refused instead of silently becoming "default".
- A file just over 12 MiB is refused with its exact byte count.
- SBX_USAGE says up leaves a reused sandbox with unpulled work unpushed,
  and exits 0.
- The --max-push test asserts the largest directories and their order.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>
…op-level or node_modules (re-review)

Round 1's re-include took in a whole top-level build/, dist/ or target/ (and
node_modules/) as soon as it held one tracked file. A build or an npm install
in the sandbox then flooded the patch, refused every plain push, and could
push the patch over 8 MiB. Now only a nested build-named directory is
re-included (src/main/java/acme/build/), and never node_modules or anything
under a top-level output directory. Tracked files there are still in the
baseline by name, so the agent's edits to them come back; new files there
count as output.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>
…ot replace the binding (re-review)

APFS folds U+017F (ſ) to s, so a patch writing .ſbx/sandbox.json replaced
the binding: toLowerCase leaves ſ as it is. isBindingPath, used by both
planPush and applyPatch, now folds with NFKC and lowercases both directly
and through uppercase. A patch path with any component that folds to .git
is refused too, before git is asked (git lets .git through). The tests
cover new-file and modify patches for .ſbx/ and .ſBX/, and pi3b end to
end.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>
…n the reset fails (re-review minor)

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>
Without a captured tree the advance hashes the workspace first (its scratch index's trap), then sets a second EXIT trap for the reset's scratch dir, which replaced the first and leaked the index dir on every call. One trap now removes both.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>
…SBX0 §6.3)

One module holds the spec's lists: Claude Code's denied built-ins, OpenCode's
disabled tools, the sandbox MCP server entries and the CLAUDE.md/AGENTS.md
rules block. writeAgentConfig merges them into .mcp.json, .claude/settings.json
(with enabledMcpjsonServers, R7), opencode.json(c) and the marked blocks:
adding only, in place via jsonc-parser so formatting, key order and OpenCode's
comments survive, atomically and keeping the file mode. A conflicting value,
a file that is not valid JSON, or a link out of the repository stops it,
naming the file and key, with nothing written. What was added is recorded in
.sbx/agent-config.json so removeAgentConfig takes back exactly that.
checkAgentConfig is what sbx doctor re-checks.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>
…hem byte for byte

jsonc-parser's modify reformats the lines around an edit (expanding a
developer's inline server entry) and corrupts a compact array when removing
its last item. json-edit.ts appends and removes one member using only the
parser and scanner, in the container's own style (multi-line, inline or
minified; spaces, tabs or CRLF; comments and trailing commas kept), so an
append followed by a remove gives back the original bytes.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>
… back

up checks the agent configuration (a dry run) before it creates, binds or
pushes anything, so a conflict stops it with nothing done and names the file
and key; it writes it after the push, so the sandbox gets the developer's
tree. rm of the bound sandbox removes what up added and .sbx/, saying what it
removed, unless --keep-config; a file it can no longer read stops it with the
record kept, so a second rm finishes. The up/push/pull harness moves to
test/helpers/sbx.ts, with a DELETE route, for the doctor tests.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>
Checks the login (its own check, so it can fail: doctor opens without
openSbx's exit 3, R7), the bound sandbox and its expiry (under 24 h fails,
naming sbx up), the agent configuration against agent-config.ts's lists, one
`true` Exec and its latency, changes not yet pulled (a warning), and the
flight recorder's last 24 h (calls, p50/p95 ms, errors). One line per check
with a fix for each failure, or --json; exit 0 only when every check passes.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>
Its package main is a UMD build with a dynamic require('./impl/format') that
esbuild leaves in place, so the release bundle died at startup (bundle.test.ts).

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>
@pdettori pdettori added the ready-for-ai-review Request automated AI code review from clawgenti label Oct 19, 2026

@ingpaolodettori-dev ingpaolodettori-dev left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed the 1c commits only (63750cf..f55323b, 82 files, about 20k lines). GitHub won't serve this diff, so I read it from a local checkout. The design is careful: quoting into the sandbox shell, the tar writer, the retry-once-only-before-start rule, TLS verification, the janitor's fail-closed and symlink handling, token-file hygiene, and the relay refactor (it keeps every base check) all hold up. The constants that up writes (only mocactl sbx mcp, allow mcp__sandbox__*, a deny list, and no hooks) can't be steered by a repo or the control plane.

One must-fix: the pull --apply agent-config/hook guard can be bypassed by deletions and renames written without rename from headers (see the inline comment, reproduced with git 2.47.3). This is the guard the PR describes as the protection against a sandboxed agent planting a laptop hook or removing the deny list.

The other comments are suggestions: Windows path aliases, a repo-supplied control-plane URL, an unchecked .sbx/ symlink, missing older-version tool names in the deny lists, may-have-run reporting, the edit read/write race, audit-before-cleanup ordering, and janitor status after a refused run.

Author: pdettori (MEMBER — maintainer)
Areas reviewed: TypeScript (mocactl sbx, sandbox-client, sandbox-relay, control-plane token), Shell/systemd (janitor, install-host, setup, status), CI, k8s overlay, docs
Agent/IDE config (.claude/.vscode): none changed in this repo (the code writes .claude/settings.json into users' repos; reviewed above)
Commits: 75 commits, all signed-off: yes
CI status: passing (DCO, check, deploy-scripts, docs, k8s-kind-e2e, lint, microvm-gates, proto)

}

/** The paths a patch touches (both sides of a rename), from `git apply --numstat -z`. */
async function patchPaths(root: string, file: string): Promise<string[]> {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

must-fix — The pull --apply guard misses a patch's old side unless the patch has explicit rename from/copy from lines, so a patch from the sandbox can still delete or rename away .claude/settings.json (which removes the deny list), .envrc and the rest. git apply --numstat lists only the new path, and patchSourcePaths scans only rename|copy from. I reproduced this with git 2.47.3 in a scratch repo:

diff --git a/.claude/settings.json b/.claude/settings.json
--- a/.claude/settings.json
+++ /dev/null
@@ -1 +0,0 @@
-{"permissions":{"deny":["Bash"]}}

numstat prints dev/null, git apply succeeds, and .claude/settings.json is deleted. A patch with --- a/.claude/settings.json / +++ b/x and no rename headers does the same thing: numstat prints only x, and the apply deletes the guarded file and creates x. This also happens when diff --git a/x b/x disagrees with ---.

Fix: let git report the old side too. Union the forward set with git apply -R --numstat -z <file>, which reports .claude/settings.json in all of these cases. Keep the regex only as a backstop, and add tests for headerless deletion, ---/+++ mismatch, and a header that disagrees with diff --git. This also fixes uncommitted() (L816) and the post-3-way index reset (L989-995), which see the same incomplete list. Until it's fixed, the user guide's promise (docs/sbx/user-guide.md:135) that a patch that touches these paths "is refused whole" doesn't hold.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 1e28091. Thanks for the reproduction. patchPaths now unions git's forward --numstat with git apply -R --numstat, which is git's own reading of the old side, and drops the dev/null placeholder. A header backstop (patchSourcePaths) also reads ---, the a/ side of diff --git, and rename/copy sources. That covers all three cases you found: the headerless deletion, the ---/+++ mismatch, and a diff --git that disagrees with ---. Each now has a test that fails without the fix. uncommitted() and the post-3-way index reset take the same list, so they're covered too.

Comment thread packages/mocactl/src/sbx/push.ts Outdated
* APFS folds `.ſbx` and `.SBX` to `.sbx`. Erring wide is safe: a look-alike is only refused.
*/
function folds(seg: string): string[] {
const k = seg.normalize('NFKC');

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion — folds covers NFKC and case only. On Windows/NTFS, trailing dots/spaces (.claude., .envrc ), 8.3 short names and \ separators also resolve to the guarded paths, and git's core.protectNTFS protects only .git. Either strip trailing [. ] and split on \ here, or state in the guide that Windows laptops are out of scope. I haven't verified this on Windows.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 1e28091 rather than scoped out. folds now drops trailing dots and spaces, guarded-path matching also splits on \, and any component that looks like an 8.3 short name (~<digit>) is refused outright, since on NTFS it can stand for anything. Tests cover .claude./…, .envrc , .mcp.json., .vscode\tasks.json, CLAUDE~1/… and MCPJSO~1.JSO. Not verified on a real Windows machine.

// A sandbox bound by .sbx/sandbox.json lives on the control plane `sbx up` used, which may not be
// the one remembered at login (a `sbx mcp` started by an agent has no MOCACTL_SBX_URL): the flag
// and the environment still win (R5j).
const flagUrl = values['control-plane-url'] || (env.MOCACTL_SBX_URL ? undefined : boundUrl);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion — boundUrl comes from .sbx/sandbox.json, and a repo can commit that file. Tokens don't leak (loadAuth requires the URL to match), but up then says "not logged in … at (from .sbx/sandbox.json)". That nudges the user to log in to that control plane, which would then receive the pushed working tree. Consider warning or refusing when the bound URL differs from the remembered or default one, or when .sbx/ is tracked.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Addressed in 2e89428. When the binding names a control plane other than the remembered one, the login hint now says so, and warns that logging in there would hand it this repository's files. A .sbx/ tracked by git is no longer read as a binding at all (see the .sbx thread), so a repo can't supply one by committing it.

...mdRecs.filter((r) => !prev?.markdown.some((p) => p.file === r.file)),
],
};
mkdirSync(join(root, '.sbx'), { recursive: true });

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion — .sbx/ and the record file are written without the target() symlink check that every other agent-config target gets. A repo that commits .sbx as a symlink makes up write (and rm delete) agent-config.json outside the repo. A committed .sbx/agent-config.json is also trusted as the record (for example a forged markdown previous). The impact is low, but please refuse a symlinked or tracked .sbx/. Relatedly, target() (L229) accepts links into .git/, which isRelPath later rejects, so the record ends up permanently malformed. Refuse targets that resolve under .git there too.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 2e89428. A new sbxDirProblem refuses a .sbx that is a symlink, isn't a directory, or is tracked by git. When it trips, up and writeBinding refuse, rm takes nothing back and says why, and the binding lookup ignores it. target() also refuses a file that resolves into .git. Tests cover the symlinked .sbx, the tracked .sbx with its forged record, and a .mcp.json linked to .git/config.

*/

/** Claude Code's built-ins that act on the laptop: denied (spec §6.3). */
export const CLAUDE_DENY: readonly string[] = Object.freeze([

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion — CLAUDE_DENY / OPENCODE_OFF (L64) leave out local tools from older or adjacent versions: Claude Code MultiEdit, LS, NotebookRead, and OpenCode multiedit. By the comment at L77's own argument, denying a tool that doesn't exist costs nothing, so add them and close the gap for users on older CLIs. Doctor reads the same list. I haven't checked these against the current tool lists.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added in 2e89428: MultiEdit, LS and NotebookRead for Claude Code, and multiedit for OpenCode. Doctor checks the same lists. The spec §6.3 and the user guide are updated, and the test that pins the lists now includes them.

// result says so -- a defaulted timeout included, since it was cut below the default.
const left = this.left(grant);
if (left !== undefined && t.timeoutS + TOKEN_MARGIN_S > left) {
// ceil: a token minted this instant keeps its full cap.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion — When left - 60 < 1 (clock skew, or an unreadable lifetime near exp), the command quietly runs with timeout_s=1, and the model sees "timed out after 1 seconds". Refuse it as expiring instead.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done in 390649a. When even the token just asked for (after the fresh mint prepare already does) has no more than the 60 s margin left, the Exec is refused before anything is sent, as the existing expiring kind, instead of running under timeout_s=1.

Comment thread packages/sandbox-client/src/tools.ts Outdated
`${formatSize(MAX_STDIN_BYTES)} one call can carry; use bash (sed -i) instead.`,
);
}
const w = await exec(writeFileCommand(path), { stdin: out, ...fileOpts(signal) });

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion — edit reads (L365) and writes back in separate Execs, with no check that the file is unchanged in between. A concurrent write from another client is silently overwritten, and so is a cancelled call that is still running remotely (mcp-server releases its slot as soon as onAbort fires). A size+mtime or sha256 check in the write command would make this safe. Also, normalizeToLF and restoreLineEndings (L111/L435) rewrite every line of a mixed-ending file. Consider refusing such files, as you do for fuzzy matching.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done in ca0d315. edit's write-back is now conditional: the write command checks the file's sha256 against the bytes edit read, just before the atomic rename, and on a mismatch it removes its temp and exits 3. That surfaces as 'It changed since it was read, so nothing was written'. Files with mixed line endings (CRLF beside LF, or a bare CR) are now refused, as fuzzy matching is, rather than having every line's ending rewritten. The hash check and the rename are one shell step apart, so a write landing in exactly that instant isn't caught; one landing anywhere between the read and the write is. That limit is documented on writeFileCommand.

} finally {
// After the drain; a no-op when expiry or a cancel already wrote this Exec's line. Here, so a
// throw out of the pump still leaves one (as `error`: it has no End).
log(finished(result, entry.aborted === true), result.outBytes);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion — The "a failing audit write never skips enforcement" guarantee is partial. emit wraps only write(), while the record is built (toISOString, utf8Prefix, commandPreview) outside the try. Here log(...) runs before disarm(), owned.delete and the inflight decrement, and in the expiry path (L277) it runs before routeAbort. Wrap the whole audit.exec body, or log after the cleanup.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done in e32d25e. emit now takes a builder and runs it inside the try, so a throw while building any line (exec, released, abortRefused) is reported and swallowed like a failed write. A new test with a claims object whose getter throws checks that the expiry abort is still sent and the slot and ownership are still freed.

Comment thread deploy/sbx/status.sh

host_janitor() {
local last ttl="$1" env="$SBX_ENV_DIR/janitor.env" age
last="$(journalctl -u sbx-janitor -o cat -n 200 --no-pager </dev/null 2>/dev/null |

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion — When janitor.sh exits via refuse() (bad token mode, bad URL, failed mv probe), it writes no summary/skipped line. This check then shows the previous good run, and the timer still reads active. Also show systemctl show sbx-janitor.service -p Result -p ExecMainStartTimestamp, and add ts to skipped. RUNBOOK §7's "each run logs one JSON line" should allow for this case.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 280876b. status.sh now also reads systemctl show sbx-janitor.service -p Result -p ExecMainStartTimestamp, and reports latest run at … FAILED (<result>) when the result isn't success, even if the journal's last summary is a good one. That case has a test. The skipped line now carries ts. RUNBOOK §7 now says that a refusal of the janitor's own settings exits 2 with no JSON line.

Comment thread deploy/sbx/sbx-janitor.timer Outdated
[Timer]
OnBootSec=5min
OnUnitActiveSec=15min
Persistent=true

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit — Persistent=true affects only OnCalendar=, so it does nothing alongside OnBootSec/OnUnitActiveSec.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Right. Dropped in 280876b.

SBX_LIVE_SMOKE=1 deploy/sbx/smoke.sh runs §10.6's six checks against a
deployed sandbox service; without it, one SKIP line and exit 0. Inputs
come from the environment only: the control-plane URL, two HOMEs already
logged in with `mocactl sbx login` (two different users), the template,
SBX_SMOKE_STEPS, SBX_SMOKE_AGENTS and an optional KVM-host ssh target.
mocactl is installed from the edge channel the user guide names, or
MOCACTL points at a local build; `mocactl sbx --help` is checked first.

Per pre-flight R10: B's mint is `no such sandbox`; Claude runs with
--mcp-config .mcp.json --strict-mcp-config; `git status --porcelain` is
snapshotted after `sbx up` and must be unchanged after the agent; the
janitor runs as `sudo env SBX_JANITOR_AGE=... sbx-janitor.sh` with
janitor.env sourced; the same-req_id and exp-cancel checks use
docs/api/examples/sandbox_v1_client.py with an explicit req_id and a
static, near-expiry token.

Each step prints `ok N` or `not ok N - ...: why`, and any failure exits
1. It deletes only the sandboxes it created this run, as their owner,
in an EXIT trap, and never prints a token (tokens live in 0600 files
in its temp dir). smoke.test.sh runs it against fakes (mocactl, the
client, ssh, the janitor, claude, and a fake clock for the minutes-long
steps); make test-deploy picks it up through its deploy/sbx/tests glob.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>
RUNBOOK §13: how to prepare the two logins (a second HOME for user B),
how to run deploy/sbx/smoke.sh, every input, what each step checks,
and what it cannot check (an agent's route to the fix; no network in
the guest).

security-review.md: the Live (Task 10) rows say which ones
deploy/sbx/smoke.sh checks when run (§1.3's deployed row, §2's
reach-only-your-own and access-ends claims), and which stay by hand
(§1.2's deployed profile, §1.4's tokenless Exec and attach refusal).
No status changes: a row is verified only once the run is recorded.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>
The relay fixes are carried into sandbox-caller.ts, where 1c moved the sandbox caller: the
expiry Abort on any call, nothing routed for a call already cancelled (audited 'cancelled'),
the 60 s drain grace (its own audit marker, sandbox_release), and the keyed req_id mapping, with
the key pinned in the shared test helper. setup.sh keeps 1c's janitor token beside 1b's foreign
moca-mu1 refusal.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>
…cument sandbox_release

SBX_SMOKE_JANITOR_AGE now defaults to 930 (the token lifetime + 30 s), so step 6 never frees another user's just-terminated workspace on a shared host; 0 stays available for a host nobody else uses. RUNBOOK names the relay's sandbox_release line.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>
Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>
… headers; Windows aliases

#554 review (must-fix). The guard read only git apply --numstat, which names a patch's new side:
a deletion (+++ /dev/null) or a --- that names another file than +++ carried a guarded path such
as .claude/settings.json past it. The touched paths now also come from git apply -R --numstat,
git's own reading of the old side, with the --- and diff --git a/ headers kept as a backstop;
uncommitted() and the post-3-way index reset use the same list. Path components also fold as
Windows resolves them: trailing dots and spaces dropped, backslash as a separator, and any 8.3
short name refused.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>
…git, a foreign binding URL; older tool names

#554 review.
- A .sbx that is a symlink, not a directory, or tracked by git is never read as this laptop's
  binding or record: up and the binding write refuse it, rm takes nothing back and says why.
- target() refuses an agent-config file linked into .git.
- A login hint for a bound sandbox on another control plane than the remembered one says so,
  and that logging in there hands it the repository's files.
- Claude Code's MultiEdit, LS and NotebookRead and OpenCode's multiedit are denied too (older
  versions); doctor checks the same lists.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>
…e run the command

The note "the command may have partly run" was set only once a chunk had
arrived, so the relay's in-stream "worker disconnected" after a silent
command (which may have changed files) was reported without it. Any
in-stream ExecError now counts as may-have-run, except the worker's known
refusals before the start (vmpool refusals and key checks, workspace and
spawn failures, req_id collision). The retry-once-before-first-event rule
is unchanged: it applies only to UNAUTHENTICATED with no event.

Review: PR #554.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>
… time past the margin

When what the token had left minus the 60 s margin was below 1 s (clock
skew, or an exp all but here), the command was sent with timeout_s=1 and
the model saw "timed out after 1 seconds". It is now refused before
anything is sent, as the existing ExecMachineryError kind 'expiring',
after the fresh mint prepare() already asks for when the held token falls
short.

Review: PR #554.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>
…; skipped lines carry ts

#554 review. A janitor run that exits 2 on its own settings writes no JSON line, so status.sh
showed the last good summary as if all were well: it now also reads the service's Result and
last start, and reports a failed latest run. The skipped line carries ts; the RUNBOOK says when
no line is written. Persistent=true is dropped from the timer: it applies only to OnCalendar=.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>
…refuses mixed endings

edit read the file in one Exec and wrote it back in another with no check
in between, so a concurrent write (another client, or a cancelled call
still running remotely) was silently overwritten. writeFileCommand takes an
optional expectSha256: after the temp file is complete and just before the
rename, the target's sha256 (sha256sum, shasum -a 256 as a fallback) must
equal the hash of the bytes edit read, or the temp is removed and the
command exits 3. edit reports that as "It changed since it was read, so
nothing was written".

A file with mixed line endings (CRLF beside LF, or a bare CR) is now
refused, as fuzzy matching is, instead of normalising and restoring one
ending onto every line.

Review: PR #554.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>
…enforcement

makeAudit's emit wrapped only write(); the record (toISOString, utf8Prefix,
commandPreview, the claims reads) was built outside the try. A throw there
escaped audit.exec before routeAbort on the expiry path, and before
disarm, the owned delete and the inflight decrement in the finally.
emit now takes a builder and runs it inside the try, so the whole body of
audit.exec, released and abortRefused is covered.

The new test drives makeSandboxCaller with claims whose sub getter throws:
the expiry still sends the abort and DEADLINE_EXCEEDED, the drain grace
still frees the slot (a cap of 1 admits the next Exec), and an Exec that
ends gives back its ownership and slot.

Review: PR #554.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>
Comment thread packages/mocactl/src/sbx/push.ts Fixed
Comment thread packages/mocactl/src/sbx/sync.ts Fixed
Comment on lines +181 to +195
const child = execFile(
'bash',
['-c', command.replaceAll('/workspace', ws)],
{ encoding: 'buffer', maxBuffer: 512 << 20, env },
(err, stdout, stderr) => {
const code = err ? (err as { code?: unknown }).code : 0;
const cut = o.capBytes !== undefined && stdout.length > o.capBytes;
resolve({
stdout: cut ? stdout.subarray(0, o.capBytes) : stdout,
stderr,
exitCode: typeof code === 'number' ? code : -1,
truncated: cut,
});
},
);
…l -o file, a quoted hash

- writeBinding reads info/exclude directly, treating only ENOENT as empty, instead of existsSync then readFileSync.
- pull -o creates the patch file 0600: it is the repository's code.
- Tests read a file before checking its mode, and the tree snapshot opens with O_NOFOLLOW and stats through the descriptor.
- edit's expected sha256 goes into the write command through q(), though it is already checked as 64 hex digits.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>

@ingpaolodettori-dev ingpaolodettori-dev left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Follow-up review at f3c5dcf, covering f55323b..f3c5dcf. All 11 items from the previous review are fixed. I checked each fix against the code:

  • the pull --apply guard now takes the old side from git apply -R --numstat and the headers, with tests for all three bypasses
  • the Windows aliases
  • the .sbx symlink/tracked/.git-link checks
  • the foreign-URL hint
  • the older tool names
  • may-have-run on in-stream ExecErrors (unknown messages fail safe)
  • the expiring refusal
  • the conditional edit write-back and the mixed-ending refusal
  • audit emit(build)
  • the janitor status and the timer

The merges (2ed184a, ab84107) are clean, and no tests were lost in the helper move. f3c5dcf resolves the CodeQL alerts, and CodeQL is now green:

  • the ENOENT-only read of info/exclude
  • pull -o created 0600
  • the O_NOFOLLOW snapshot in tests
  • q() around the hash, which was already validated as hex

One must-fix, in the new live smoke: its janitor run defaults to SBX_JANITOR_AGE=930 and overrides the host's janitor.env. On a host with token lifetimes over 15 min, that frees other users' workspaces that a still-valid token can still reach. The RUNBOOK calls this default safe on a shared host.

k8s-kind-e2e failed at "Live smoke" on this head. It passed at e32d25e, and f3c5dcf doesn't touch deploy/k8s, but the same job also failed on main at 12536a6 (#553, docs-only). That looks like flakiness or an environment problem rather than this change. Please re-run it.

Also inline: a case-sensitivity gap in the tracked-.sbx check (macOS/Windows), two cleanup-robustness suggestions for smoke.sh, and nits.

Comment thread deploy/sbx/smoke.sh Outdated
[[ -z "$HOST" || "$HOST" =~ ^[A-Za-z0-9_][A-Za-z0-9_.@-]*$ ]] || die "SBX_SMOKE_HOST='$HOST' must be an ssh target, [user@]host"
H_ENV="${SBX_SMOKE_HOST_ENV_DIR:-/etc/sbx}" H_SRV="${SBX_SMOKE_HOST_SRV:-/srv/sbx}" H_LIBEXEC="${SBX_SMOKE_HOST_LIBEXEC:-/usr/local/libexec}"
for v in H_ENV H_SRV H_LIBEXEC; do [[ "${!v}" =~ $PATH_RE ]] || die "the host paths must be plain absolute paths (got '${!v}')"; done
JANITOR_AGE="${SBX_SMOKE_JANITOR_AGE:-930}"

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

must-fix — JANITOR_AGE defaults to 930 s (a 15 min token + 30 s), and REMOTE_JANITOR (L524-526) sources janitor.env, then overrides its SBX_JANITOR_AGE with that value. setup.sh allows SBX_TOKEN_TTL_MINUTES up to 60 and refuses a janitor wait at or below lifetime+30 s (setup.sh:122). The smoke's one janitor run applies to every terminated sandbox on the host, not just its own. So on a host with 60-min tokens, it frees another user's workspace 15.5 min after they deleted it, while their last token can still reach it for about 45 min. That is exactly what setup.sh refuses.

Please default to the host's own SBX_JANITOR_AGE from janitor.env (don't override it unless asked), and refuse an explicit value below it, or below the minted token's exp - iat + 30.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 8a6f93d. Step 6 now probes the host first and reads its own SBX_JANITOR_AGE from janitor.env. It runs the janitor with that wait, with no override, and waits until its own deletion is that old. SBX_SMOKE_JANITOR_AGE can only lengthen the wait: a value below the host's is refused as not ok 6, before the janitor runs. The test covers this with a host wait of 3630 and SBX_SMOKE_JANITOR_AGE=930. The value 0 is refused as a settings error (exit 2).

Comment thread deploy/sbx/RUNBOOK.md Outdated
| `SBX_SMOKE_AGENTS` | `claude,opencode` | the agents step 5 runs, headless; one not on `PATH` is a SKIP. Each needs its own login and model configured |
| `SBX_SMOKE_HOST` | (unset: step 6 is a SKIP) | an ssh target (`[user@]host`) for the template's KVM host, with passwordless `sudo` |
| `SBX_SMOKE_HOST_ENV_DIR`, `SBX_SMOKE_HOST_SRV`, `SBX_SMOKE_HOST_LIBEXEC` | `/etc/sbx`, `/srv/sbx`, `/usr/local/libexec` | that host's `SBX_ENV_DIR`, `SBX_SRV` and `SBX_LIBEXEC_DIR`, if `install-host.sh` was given others |
| `SBX_SMOKE_JANITOR_AGE` | `930` | the janitor wait for step 6's one run: only workspaces terminated that long ago are freed, so the default (the token lifetime + 30 s) is safe on a shared host. `0` frees **every** terminated sandbox's workspace at once: only on a host nobody else uses |

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

must-fix (same issue as smoke.sh:128) — "the default (the token lifetime + 30 s) is safe on a shared host" is true only for 15-minute tokens. Please update it together with the smoke's default.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 8a6f93d together with the smoke. The row now says the default is the host's own wait, that the run frees every workspace older than it (other users' too), that a shorter value is refused, and that the wait can be up to an hour with 60-minute tokens. Step 6's description in the list of steps is updated to match.

Comment thread packages/mocactl/src/sbx/state.ts Outdated
if (!st.isDirectory()) return 'is not a directory';
let tracked = '';
try {
tracked = execFileSync('git', ['ls-files', '-z', '--', '.sbx'], {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion — git ls-files -- .sbx is a case-sensitive pathspec even with core.ignorecase=true. I checked with git 2.47.3: a committed .SBX/sandbox.json lists nothing for .sbx and lists the file for :(icase).sbx. On macOS/Windows, join(root, '.sbx', …) then opens the tracked .SBX/, so a repo can still ship a binding and a forged agent-config.json record (which rm acts on). Use ':(icase).sbx', or list git ls-files -z and test each path with isBindingPath, which already folds case and NFKC.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in ac29fe4. Good catch. sbxDirProblem now lists the whole index (git ls-files -z) and folds each path's first component the way isBindingPath does (NFKC, case), so a committed .SBX/sandbox.json counts as tracked. folds/segments moved to state.ts so both use the one definition. Test: a committed .SBX/ makes up refuse.

Comment thread deploy/sbx/smoke.sh
upper() { printf '%s' "$1" | tr '[:lower:]' '[:upper:]'; }
trap cleanup EXIT
trap 'exit 130' INT
trap 'exit 143' TERM

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion — trap 'exit 143' TERM only runs after the foreground command returns. sleep_until (L262, up to about 16 min), the 300 s sbx run and step 5's wait therefore hold off a TERM. A timeout that escalates to SIGKILL skips the EXIT cleanup and leaks this run's sandboxes. sleep "$d" & wait $! (and background + wait for the long calls) keeps TERM prompt.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 8a6f93d. Every logged command (x/xin), every sleep_until, and the janitor's ssh now run as a background job that the script waits on, which keeps stdin through <&0. So a TERM interrupts the wait, the trap runs, and the EXIT cleanup finishes before any later SIGKILL. New test: a TERM during the 5-minute silent run exits 143 within seconds and deletes the sandbox.

Comment thread deploy/sbx/smoke.sh
}
create() { # create a|b TAG: a new sandbox from TEMPLATE; its id in SBX
N=$((N + 1))
x "create-$1-$N" as "$1" create --template "$TEMPLATE" --name "$RUN-$N-$2"

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion — A sandbox is recorded only after create exits 0. An interrupt after the server created it, but before mocactl printed the id, leaves it untracked, so cleanup won't delete it. Every name carries $RUN-, so cleanup could also run sbx ls and delete leftovers with this run's prefix.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 8a6f93d. On top of the recorded ids, cleanup now runs sbx ls --json for each user and deletes every live sandbox whose name starts with this run's $RUN- prefix. New test: a create whose answer is lost (the server made it, mocactl failed) is found by its prefix and deleted by its owner.

Comment thread packages/mocactl/src/sbx/push.ts Outdated
* An 8.3 short name (`CLAUDE~1`, `MCPJSO~1.JSO`) can stand for any long name on NTFS, guarded ones
* included, and which one depends on the volume: a pull refuses every such component.
*/
const isShortName = (seg: string): boolean => /~\d/.test(seg);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit — /~\d/ matches any segment that contains ~<digit> anywhere (notes~2.md, cp --backup=numbered's file.~1~, v~1/). Such a path refuses the whole pull as "an 8.3 short name". That fails safe, but an 8.3 alias has a tighter shape, roughly ^[^.~]{1,6}~\d+(\.[^.]{0,3})?$ after folding to uppercase.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in ac29fe4. isShortName now matches only the generated shape, ^[^.~]{1,6}~\d+(\.[^.]{0,3})?$, on the NFKC-and-uppercase form. So notes~2.markdown, file.~1~ and version~one/ pass, while CLAUDE~1, claude~1 (Windows resolves it case-insensitively) and full-width look-alikes are refused. notes~2.md really is a valid 8.3 shape, so it is still refused: that is the safe side.

Comment thread deploy/sbx/smoke.sh
local l
if [[ "$1" == a ]]; then l=" $CREATED_A "; CREATED_A="${l/ $2 / }"; else l=" $CREATED_B "; CREATED_B="${l/ $2 / }"; fi
}
release() { # release a|b ID: delete a sandbox this run created, now its step is done with it

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit — release returns 0 when rm fails, so the step prints ok. The EXIT trap retries and the run exits 1, but the TAP line is misleading.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 8a6f93d. release fails its step with the sbx rm reason when the rm fails, and the trap's retry still deletes the sandbox. Tested with an rm that fails once.

Comment thread deploy/sbx/RUNBOOK.md Outdated
ok 6 - the janitor frees a deleted sandbox's directory
```

It exits 0 when every step is `ok` or skipped, and 1 when any step is `not ok`; the line gives the

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit — It lists exit codes 0 and 1, but smoke.sh also exits 2 on a usage or settings error (L64, L81).

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 8a6f93d. The RUNBOOK now lists exit 2 for a usage or settings error, which happens before any sandbox is touched.

…mes by their shape

#554 follow-up review. git ls-files -- .sbx is a case-sensitive pathspec, so a committed .SBX/
(which macOS and Windows open as .sbx/) passed as untracked: the tracked check now lists the
index and folds each path's first component as isBindingPath does. The 8.3 short-name refusal
matches only the shape NTFS generates (up to six characters, ~N, up to a three-character
extension, case-folded), not any ~<digit> in a name.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>
…trays deleted by name

#554 follow-up review.
- must-fix: step 6 no longer overrides the host's SBX_JANITOR_AGE with 930 s. It reads the host's
  wait from janitor.env, runs the janitor with it, and refuses an SBX_SMOKE_JANITOR_AGE below it:
  the one run frees every workspace on the host older than its wait, other users' too, so on a
  host with 60-minute tokens 930 s freed workspaces a valid token still reached. RUNBOOK updated.
- Long commands and waits run as background jobs that are waited on, so a TERM is acted on at
  once and the EXIT cleanup runs before a timeout's SIGKILL.
- Cleanup also deletes any live sandbox named with this run's prefix (a create whose answer was
  lost), from sbx ls --json.
- release fails its step when sbx rm fails; RUNBOOK lists exit 2.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>
…rom the fake exec

CI on 8a6f93d: the smoke's background sleeps (now jobs, so they can overlap) both advanced the
fake clock, and one read the other's half-written file, so step 4 read a torn time. The fake
sleep now updates the clock under a lock, by rename. The sandbox-client and mocactl fake execs
ignore EPIPE on stdin: a command that exits without reading it (a refused write) closes the pipe,
which vitest reported as an unhandled error.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>

@ingpaolodettori-dev ingpaolodettori-dev left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks — all 8 items from the f3c5dcf round are verified fixed in ac29fe4 / 8a6f93d (the janitor wait now defaults to the host's own and can only be lengthened; .SBX/ is found case-insensitively; TERM is prompt; stray creates are deleted by their run prefix; release reports a failed rm; exit 2 is documented). d7fa2f4's test fixes turned check and deploy-scripts green.

Approving. Two non-blocking follow-ups inline: the tighter 8.3 regex lost the trailing-dot/space Windows aliases (CLAUDE~1 , MCPJSO~1.JSO.) that the old one refused, and the RUNBOOK run-time estimate now that step 6 waits for the host's own janitor wait.

Comment thread packages/mocactl/src/sbx/push.ts Outdated
*/
const isShortName = (seg: string): boolean =>
// Windows resolves a short name case-insensitively, so `claude~1` is `CLAUDE~1`: fold first.
/^[^.~]{1,6}~\d+(\.[^.]{0,3})?$/.test(seg.normalize('NFKC').toUpperCase());

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion — The tighter shape no longer matches a short name with a trailing dot or space: CLAUDE~1 , CLAUDE~1.., MCPJSO~1.JSO., MCPJSO~1.JSO all return false (the old /~\d/ refused them). Windows strips trailing dots and spaces when it resolves a name, which is why folds() strips them, so CLAUDE~1 /settings.json can still reach .claude/settings.json there. Stripping the same way before matching keeps notes~2.markdown and file.~1~ allowed:

/^[^.~]{1,6}~\d+(\.[^.]{0,3})?$/.test(seg.normalize('NFKC').replace(/[. ]+$/, '').toUpperCase())

Worth adding 'CLAUDE~1 /x' and 'MCPJSO~1.JSO.' to refused. (CLAUDE~1. is still caught today, but only through the empty optional extension.)

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done in 71cf126. isShortName strips a trailing [. ]+ after NFKC, the same normalization folds applies, before the shape test, so CLAUDE~1 , CLAUDE~1.., MCPJSO~1.JSO. and MCPJSO~1.JSO are refused again while notes~2.markdown and file.~1~ stay allowed. All four aliases (the first, third and fourth named, plus CLAUDE~1 /settings.json) are in the refused tests; each fails without the fix.

Comment thread deploy/sbx/RUNBOOK.md Outdated
```

It exits 0 when every step is `ok` or skipped, 1 when any step is `not ok` (the line gives the
reason), and 2 on a usage or settings error, before any sandbox is touched. On a failure it keeps its logs and prints their path. A full run takes about 25 minutes:

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit — "A full run takes about 25 minutes" no longer holds when step 6 runs: it now waits for the host's own janitor wait, and setup.sh's default is at least 60 min (max(60, ttl+5), so 65 min with 60-minute tokens). The run is closer to 70–90 min. For the same reason, L435's "up to an hour with 60-minute tokens" would be more accurate as "the host's wait (65 min by default with 60-minute tokens)".

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done in 05ed7d4. The estimate now reads "about 25 minutes without step 6 … with step 6 closer to 70-90 minutes, because step 6 waits out the host's own janitor wait (setup.sh keeps it at max(60, SBX_TOKEN_TTL_MINUTES + 5) minutes, so 65 min with 60-minute tokens)", and the table entry says "the host's wait, 65 min by default with 60-minute tokens" instead of "up to an hour".

…d again

#554 follow-up review. The tighter 8.3 shape from the last round matches only a name that
ends cleanly, so `CLAUDE~1 ` and `MCPJSO~1.JSO.` passed: Windows drops a trailing dot or
space when it resolves a name (which is why folds() strips one), so on NTFS they still
reach `.claude/` and `.mcp.json`. isShortName now strips the same way before matching;
`notes~2.markdown` and `file.~1~` stay allowed, and the trailing-dot and -space aliases
are in the refused tests.

Signed-off-by: Paolo Dettori <[email protected]>
#554 follow-up review. Step 6 now waits out the host's own SBX_JANITOR_AGE (setup.sh keeps
it at max(60, SBX_TOKEN_TTL_MINUTES + 5) minutes, so 65 with 60-minute tokens), so a full
run is 70-90 minutes rather than 25; the table entry says the host's wait instead of an
hour.

Signed-off-by: Paolo Dettori <[email protected]>
…'s 429

k8s-kind-e2e failed intermittently at claim 12 with "first '', then
'moca-sandbox-N'": the run's artifact shows the turn's whole SSE body was
{"error":"subject_quota_exceeded"}, and the supervisor log shows why --
over_admission up to an actual 3 in flight on one worker. The where1
burst is four turns of ONE subject on a pool whose trial size fits them
exactly (W=2, S=4, so the per-subject cap is 2 per worker), and
leastInFlight's optimistic estimate can be lowered by a worker's stale
load report after the next hand-off -- over-admission that section 3.9
accepts by design and counts -- so a burst can hand one worker a third
turn, which the quota refuses.

The quota's own contract (spec section 13, #542) is that
subject_quota_exceeded is a distinct code sent with Retry-After so a
client can tell "you are over your share" from "the host is full" and
back off: the smoke now retries that code alone, twice with a 2 s
backoff (a lease frees in 2 s). Any other failure, or a third refusal,
fails the claim as before. The same signature also failed on main at
983dae6 and 12536a6, so this is not this branch's doing.

Signed-off-by: Paolo Dettori <[email protected]>
@pdettori

Copy link
Copy Markdown
Member Author

The intermittent k8s-kind-e2e failure at "Live smoke" (this head, and main at 983dae6/12536a6) has a root cause, not just flakiness.

Failing claim: 12 (sandbox affinity) — session …: first '', then moca-sandbox-1.

Evidence (from the run's k8s-kind-e2e-logs artifact): the turn's entire SSE body is {"error":"subject_quota_exceeded"} — the first turn never ran. The supervisor log in the same artifact shows over_admission up to an actual 3 turns in flight on one worker:

{"event":"over_admission","id":1,"estimate":0,"actual":1}
{"event":"over_admission","id":0,"estimate":1,"actual":2}
{"event":"over_admission","id":0,"estimate":2,"actual":3}

Mechanism: claim 12 fires four turns of ONE subject concurrently. The stack's trial sizing fits them exactly: W=2, S=4, so the per-subject cap (#542) is ⌊S/2⌋ = 2 per worker — 4 slots total, zero headroom. leastInFlight's estimate is optimistic and a worker's stale load report can lower it after the next hand-off (over-admission §3.9 accepts by design and counts), so a burst can hand one worker a third turn, which the quota refuses with 429.

Fix (565436a): the quota's contract is that subject_quota_exceeded is a distinct code sent with Retry-After so a client can back off — the smoke now does exactly that: it retries that one code, twice with a 2 s backoff (a lease frees in 2 s). Any other failure, or a third refusal, still fails the claim. Verified the retry's exit semantics against faked turn responses (recovers from up to two refusals, fails on three or on any other error).

The quota-retry commit (565436a) put `ask K8S-SMOKE-WHERE-1` on two
lines, and tests/smoke.test.sh syncs EVERY ask line in smoke.sh with the
one step mock-anthropic.mjs scripts, so its `asked` capture held both
lines and deploy-scripts failed at that check. The subshell now asks
once, into a variable both attempts send; the sync check reads the one
line again, and the whole deploy suite passes locally.

Signed-off-by: Paolo Dettori <[email protected]>
@pdettori
pdettori merged commit a9fbc9e into main Oct 20, 2026
15 checks passed
@pdettori
pdettori deleted the feat/sbx0-1c-usable branch October 20, 2026 17:10
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ready-for-ai-review Request automated AI code review from clawgenti

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants