Workspaces: snapshots, forks, and split lineage
Status: implemented. The user guide covers usage; the acceptance scenarios cover observable behavior. The model is docs/model/Workspace.tla.
Sections 1–8 describe the implementation. Section 9 records the model scope, section 10 non-goals and v1 limits, section 11 the acceptance requirements, section 12 creator identity and JSON shapes, section 13 implementation bounds and process integration, and section 14 open lanes, checkpoints, and storage.
1. Concepts and trust
The host daemon snapshots the caller's tree, creates forks, runs branches, captures results, and records lineage. The CLI, Brush syntax, and in-job client send requests and render replies.
- Snapshot (
S): a frozen filesystem copy in<id>/base, plus the caller's HEAD (H) and index bytes when it is a Git repository. The daemon does not hash the whole snapshot into Git objects.store.gitreceives pre- and post-image blobs for changed paths during capture. The source is the user's tree for a session, or the creator branch's fork for a nested split. - Fork: a private filesystem copy of the base per branch,
<root>/.marsh/split/<id>/<label>. All splits, nested ones included, are siblings under<root>/.marsh/split/, inside the existing project mount. No new stock mount is needed. The journal records the parent. - Result: after every writer is gone and the fork has been verified, the daemon writes the
out/artifacts (section 5). Consumers readout/, never live Git admin directories. Split machinery writes only its.marshstate, leaving source files and the original.gitunchanged; the consumer chooses which patches to apply. - Two kinds of branch, two trust levels.
- Shell branch (
-b LABEL='string') is trusted code, with the same authority as the user's shell: it runs in the shell VM, as the user's uid, and sees the whole project at its natural path. Its cwd is its fork, but nothing confines its own code (assumption C1). Use it for your own commands (make test,rg). A registered Kit command that a shell branch starts is an ordinary Kit job whose cwd is in the fork, so it is confined like an argv branch (split_confinement.rs); that is howsplit { fix: claude -p "..." }keeps the agent in its fork. - Argv branch (
::: LABEL CMD ARGS...) is one registered Kit command. It runs in a fresh container that mounts, of the project, only its fork and the fork's Git metadata (section 8), plus the selected home read-write like every Kit job (agents keep settings and session state there). Use it when the branch is exactly one command, or from inside a job, where shell branches are not available.
- Shell branch (
- Lineage: session -> split -> branch -> job -> child split, journaled before each effect. Split, branch, capability, job, attempt, VM, and container identities stay distinct.
2. CLI (primary)
git diff | marsh split -b tests='make test' \
::: review codex exec "review this diff" \
::: sec claude -p "review security" \
| marsh join -- claude -p "apply valid feedback"
h=$(marsh split ::: a codex exec "x" ::: b pi -p "y" </dev/null) # two-step
marsh join <<<"$h" -- ./apply.sh
-b LABEL=STRING: a fresh guestmarsh -c STRINGsession using Brush, including when the caller uses the bash or zsh frontend. It runs as its own supervisor attempt (its own cgroup) with cwd = the fork's matching subdirectory and the caller's exported environment. It does not inherit unexported variables, aliases, functions,setoptions, traps, or the job table; Brush sugar loses these too.::: LABEL CMD [ARG...]: argv taken verbatim (the outer shell has already quoted it).CMDmust be a registered command. A job argument cannot be the literal:::.- stdin is read to EOF into the daemon spool (64 MiB) before the snapshot, and every branch reads the spool. A terminal stdin, or
-n, means empty. marsh splitwaits until every branch is captured. It exits with the first nonzero branch status in declaration order (130 on cancel, 2 on setup). On completion it prints one handle line{"marsh_split":1,"id":"…"}, including when stdout is a terminal.marsh join [--json] [--keep] [-- CMD ARGS...]reads a handle and is accepted only from the split's creator: the same session, the same job, or a host caller holding a host-created split's handle (section 12). It works on awaiting and kept splits.- With
-- CMD, CMD runs even if branches failed. It gets the rendering on stdin (statuses included) andSPLIT_ID,SPLIT_DIR(theout/dir),SPLIT_MANIFEST, andSPLIT_OBJECTS(root splits only, forgit apply --3waypreimages). join then releases (remove on CMD status 0, otherwise keep) and exits with CMD's status. - Bare
| marsh join | cmdreleases once the rendering is written: remove if every branch succeeded and--keepis not given, otherwise keep. - With
pipefail,marsh split … | marsh join -- CMDreturns CMD's status when nonzero, otherwise split's.
- With
marsh splits [--json] [ID],marsh splits cancel ID, andmarsh splits rm ID(the creator's own kept splits; operator authority for any). These are not available from a Kit job, whose capability admits onlySplitCreateandSplitJoin(section 3).- Host CLI (a plain Mac terminal):
marsh splitopens a temporary ordinary session without a TTY so shell branches have a shell VM.SplitCreatecarries the exported environment, minusMARSH_*,SBX_*,DOCKER_*, and relay or bearer tokens. - Splits created by any Kit job or split branch take argv branches only, including when the creator is a top-level job. Every Kit container gets the
marsh-localclient asmarshonPATH, so it can create and join its own splits.
Brush sugar. P | split { a: X; b: Y } | join | C1 | C2 is SplitCreate with shell branches X and Y (the spool is P's output), a wait, then C1 | C2 with SPLIT_* pushed, then SplitRelease(consumed(last status)). Every sugar branch is a shell branch (a ::: CMD ARGS line is not recognized; use the CLI for argv branches). Branches are label-led (Brush 0041; split.md): ; starts a branch only before a LABEL: word, so a: cd x; make is one branch cd x; make. Labels, PIPESTATUS, and Ctrl-C are preserved; Brush does not fork split branches.
Terminal and signals. Branches have no controlling terminal (/dev/tty gives ENXIO) and their stdin is the spool. Ctrl-C at the client sends SplitCancel. Ctrl-Z stops only the client while branches keep running, and fg resumes the wait. Client death or SIGHUP before capture drops the stream, and a dropped stream cancels the split, unless it was created with marsh split -d (SplitCreateSpec.detach): then the create stream ends after SplitStarted and only an explicit signal or SplitCancel cancels it. SplitJoin on a running split waits for it to finish.
3. Daemon requests
| Request | From | Payload -> reply |
|---|---|---|
SplitCreate | relay, socket | cwd, branches: [{label, shell(string) | argv([..])}], env, keep, spawn? (the caller's MARSH_SPAWN, narrowing every argv branch job), label? (also each argv branch job's label), streamed stdin -> split, events, manifest. Dropping the stream before capture cancels |
SplitJoin | relay, socket | split, then consumed(status) | keep -> manifest and out/ contents (streamed to callers that cannot see the dir). Creator only; this is also the release |
SplitCancel | relay | split -> ack once the subtree is revoked and signalled. The session may cancel any of its splits; a shell branch may cancel splits below it |
SplitShow | relay | split? -> manifest + subtree, or every split in scope |
SplitRemove | relay | split -> removes a kept split (creator or operator) |
SplitClose | relay, socket | split -> closes an open lane split: manifest (s14) |
Checkpoint | relay, socket | root? (a relay's is its session project), create {label} / create_lane {lane, label} (relay or host only: a job's socket never reaches it) / list {label} / remove {id} (s14) |
Storage | relay, socket | root? -> per-project checkpoints, kept splits, free space (s14) |
For splits, the job capability socket admits SplitCreate and SplitJoin, not show, cancel, or remove. Every Kit job now has the socket; the complete request allowlist is in processes. Frames are credited per attempt.
4. Budgets and capability
- Split branch pool: 16 concurrent branches per creating session, with nested splits using the same pool and all host CLI splits sharing
host. Kit jobs also pass the daemon-wide process admission inprocesses.md; the split pool does not count Kit jobs started by a shell branch. Admission happens at launch. When the pool is full, the branch fails visibly (failed: capacity) and join still runs (BudgetBound). A slot frees only when its process's end is confirmed (captured, rejected, or reaped). Uncertain and unreaped slots stay held untilmarsh workers reset. - Caps: depth 3, 16 branches per split, and the job wall limit per split (
MARSH_JOB_WALL_SECONDS, 24 h by default; it was 1 h before 0.2.1). Spool (64 MiB) and captured output (16 MiB) are hard limits; crossing either cancels the split. There are no per-branch reservations or byte quotas in v1. - Capability: a daemon record per branch
{split, creator, live|revoked}, never a bearer secret. It is revoked at the branch's exit or crash, and that cancels everything below it (LiveUnderLive,CancelPropagates). Every daemon restart revokes all of them. - Delivery to a Kit job: the worker binds a per-attempt Unix socket at
/run/marsh/cap.sockand forwards its frames, tagged with the attempt id and credited per attempt, over the existing worker transport. The socket has no token and dies with the container. Its split verbs areSplitCreate(creator = this job) andSplitJoin(only for splits this job created), alongside the process requests. Jobs get no Docker, containerd, or SBX socket and cannot use the shell's relay. Ending the job or restarting the daemon revokes its capability.
5. Results: out/ layout and lineage
<root>/.marsh/split/<id>/out/manifest.json version 2; lineage, placement per branch
<root>/.marsh/split/<id>/out/<label>/stdout
<root>/.marsh/split/<id>/out/<label>/stderr
<root>/.marsh/split/<id>/out/<label>/status "exited 0" | "failed: capacity" | "rejected: <why>" | "cancelled"
<root>/.marsh/split/<id>/out/<label>/diff.patch git-apply compatible, from S to R (absent when no change)
<root>/.marsh/split/<id>/out/<label>/files "<A|M|D|T>\t<path>\n" per changed path
The journal (owner-only, host control dir) holds split{id, creator, cap, snapshot, dir identity, state} and branch{label, run, placement (shell-vm | kit:<command>), state, status, R}. Receipts gain lineage. marsh splits prints the tree (split, branch state, placement, job id, changed-file count, and the reason a split was kept or cancelled). marsh status (text and --json) counts active, awaiting, and kept splits; its text counts only attached shells.
6. Lifecycle and cleanup
Split states: run -> await -> joined | kept, or run -> cancelled. An argv branch whose job admission refused it (a limit, the spawn set) is failed: <reason>: no job ran, so there is nothing to verify. Unfinished work becomes uncertain on daemon restart. Section 12 lists the public state strings.
- Capture happens once every writer is confirmed gone: the shell branch's cgroup is empty, every Kit job under it is cleaned up, and an argv branch's container is verified deleted (
CaptureStable). Verification follows (section 8). A fork that fails it is rejected and removed, and its status says why (ExposedClean). - Lease: an awaiting split is held by the create stream, then by a join. If it stays unheld for 60 s it becomes kept: forks retained, reported, and still joinable by the creator. Its creator can remove it.
- Release:
consumed(0)without keep removes the forks, admin dirs, store, spool, andout/. Anything else keeps them, and the message says why and givesmarsh splits rm ID. Nothing is removed while a process of its branch may live (NoRemoveWhileLive). Removal goes through directory fds opened at create, never by re-resolving a path. - Daemon restart: the journal survives. Unfinished splits become uncertain. Launched branches become uncertain; their recorded unfinished jobs retain held process slots. Restart does not restore the adapter's in-memory quarantine set (
results.md). Unlaunched branches never start. Capabilities are revoked. Forks are retained, reported, and flagged untrusted (no verification ran), and the same goes for unreaped forks after a cancel. Nothing is resumed or replayed (NoReplay,WorkspaceRecorded). git clean -xfdhazard:.marsh/is git-ignored, so the user'sgit clean -xfd(orrm -rf) deletes live forks. Before capture and release, the daemon re-checks the(dev, ino)of the split dir and each fork against the journal. On a mismatch the branch fails withworkspace replacedand nothing is removed by path.
7. Failure semantics
- Setup failure (snapshot, fork, or a caller not entitled to create) is all-or-nothing: status 2 and nothing runs.
- Cancel (Ctrl-C, a client signal, stream drop, deadline, output limit, or creator branch exit; the message names which) revokes and signals the whole subtree in one step: SIGINT, 10 s, SIGKILL. When every branch's end is confirmed the whole split directory is removed (the record stays as
cancelleduntilsplits rm); otherwise everything is kept and the message names the unconfirmed branches. Status 130; join does not run. - Kit transport loss makes the branch uncertain and quarantines the VM. It is never re-run.
8. Snapshot, fork, and confinement
Git dirs come from the journal (resolved once at create, through no-follow fds, and required to lie inside the project). The daemon never follows branch-written
alternatesor gitfiles. It copies the user's index bytes under a 64 MiB bound. A project root with a gitfile instead of a.gitdirectory is refused; nested splits use the creator's journaled admin directory.No gix or host Git execution.
split_fs.rsreads Git metadata and ignore rules as data. Theignorecrate supplies global excludes; local.git/info/excludeand.gitignorerules also apply. Repository hooks, attributes, clean/smudge filters, and external diff commands never run. Snapshot files retain their raw bytes, including LFS pointer files.Snapshot (M2): clone admitted top-level entries into
<id>/base, then walk the clone through no-follow directory descriptors. Prune ignored entries, special files, and nested.gitentries. Ignore rules also exclude tracked files. If a copied file's size, mtime, or mode differs from its source, re-clone with a before/after stat check, up to three times; continued changes fail withfile kept changing: <path>. The source of a nested split is its creator's fork (ChildFromParent).Forks: copy the frozen base once per branch (
OneBase), using macOSclonefileat(..., CLONE_NOFOLLOW). OnlyUnsupportedfalls back to descriptor-based copying. The base is never mounted into a job.Git metadata per fork: a gitfile
<fork>/.gitpointing at<id>/.admin/<label>/, which holds:HEADnamesrefs/heads/marsh-split, initially holding H;- a daemon-written config with no hooks;
info/;- a copy of
packed-refs; index(the caller's index bytes);objects/, whose alternates arestore.gitand the user's.git/objects.
It is not a worktree of the user's repo, and the user's
.gitis never written.Kit mounts for an argv branch:
Path Access fork worktree read-write .admin/<label>/(so Git can createindex.lock, objects, refs)read-write gitfile, config,HEAD,info/,packed-refsread-only binds over the read-write fork and admin dir ( AdminReadOnly)store.gitand the user's.git/objectsread-only ( SnapshotImmutable)The selected guest home is also mounted read-write. No other project path is mounted (
NoWriteToUserTree,ForkIsolation).HEADnamesrefs/heads/marsh-split, sogit commitupdates a writable ref and neverHEAD. Capture also rejects any admin entry outside Git's own state files (commondir,gitdir,config.worktree,hooks, ...). An ordinary (unconfined) Kit job gets<root>/.marshas a read-only bind; the backend creates.marshbefore the job starts, so a split or checkpoint made while it runs is never writable to it, and a.marshthat isn't a directory marsh can make refuses the job. It also gets.git/config,config.worktree,hooks/,info/,modules/,worktrees/andcommondir(made, as./, when missing; acommondirnaming another directory, a symlinked control or a symlinked.gitrefuses the job; a.gitfile's Git directory directly in the project is guarded the same way, and one deeper, or a path to it through an in-project symlink, refuses the job) as read-only binds, under.gitbound onto itself (project_guardsinmarsh-backend;docs/security.mdGit in jobs). A Kit job whose project root itself lies inside a.marshdirectory (a shell opened in a fork) is refused: it would mount the fork as a project without its Git metadata and with a writable gitfile. A host command run in a fork (marsh run,split) instead takes the split's root as its project and the fork as its working directory, so it is confined.Capture verification: the gitfile and admin files must be byte-identical to what the daemon wrote, and the fork may contain no nested
.gitentry at any depth. If either check fails, the branch is rejected. The admin dir'scommondir(./; libgit2 can't open.) and emptyhooks/,modules/andworktrees/are read-only binds, so a branch can't move host Git's config or hooks there even before capture. A fork whose admin dir lacks them (a lane kept open across an upgrade), or has them changed, admits no job: close it and open a new one. Anuncertain(untrusted) branch's admin dir is renamed to.admin/.untrusted-<label>, so host Git finds no repository in its kept copy. So a hostgit -C <fork> statusor IDE never meets a branch-writtencore.fsmonitororhooksPathin a captured or uncertain fork. Not covered: a live lane's copy, beforeclosecaptures it. A lane job can create a nestedsub/.gitthere (only capture rejects it), and a hostgit -C <fork>/subwould run what it names. The lane shell banner andsplit.mdsay not to run Git or an IDE on an open lane's copy from the Mac.Patch writer: text hunks use
similarin unified format with full blob IDs onindexlines. Binary changes use Git'sGIT binary patch/literalforward and reverse hunks (zlib + base85, no delta). Capture writes the changed blobs tostore.git. The daemon never executesgit, includinggit diff --binary, because:- stock macOS may have no
git; - every exec of git keeps a config, attribute, and environment surface to audit;
- literal hunks are enough for
git apply.
Renames show as delete + add.
- stock macOS may have no
9. Model scope
model/Workspace.tla covers nested splits created by any branch (nested ones argv-only), snapshots from the caller's tree, trusted shell branches (C1) and adversarial Kit branches (they write anything mounted, including a nested .git), the session pool, creator-only join, ancestor and session cancel, exit cascade, capture after confirmed exit with verification, the lease with kept-and-joinable, open lanes (any number of Kit jobs per lane, admitted only while open, close before capture), a checkpoint as an immutable snapshot source, and one daemon crash between any two steps. It checks 17 invariants plus EventuallySettled, split across five positive configs to stay tractable (model/README.md). Each negative control removes one guard in a real action. Not modeled: C1 itself, Git, bytes, and dir identity.
10. Non-goals and v1 limits
Non-goals: confining shell branches, join --apply, replay or resume, Brush functions in branches, cross-daemon lineage, and Cloud execution. Placement is recorded per branch (shell-vm or kit:<command>); only local placements exist.
v1 limits: no nested shell branches, no --with-ignored, no --shell; the job capability's split operations are SplitCreate and SplitJoin; one split pool per creating session, with no finer-grained shares; no per-branch uid or per-branch byte quotas.
The git clean -xfd hazard (section 6) is reported, not prevented. Moving .marsh/split outside git clean's reach would need a new stock mount; the daemon instead re-checks directory identity before capture and release.
11. Acceptance requirements
These requirements are maintained as scenarios in workspaces-acceptance.md; that page and its harness are authoritative.
- A plain-bash pipeline with
-band:::, and the two-step handle. join -- CMDafter a failed branch.- A kept split joined after 60 s.
- A Kit branch writes
core.fsmonitorandcore.hooksPathinto its admin config and createssub/.git/config. The writes fail (read-only binds) or the branch is rejected. Then hostgit -C <fork> statusruns nothing (verified with a marker file). - A repo whose own config sets
core.fsmonitorand filters: nothing runs on the host. - A nested split from a Kit job, cancelled when the parent exits.
- A join attempt from a non-creator, refused.
- A background process delaying capture.
git clean -xfdmid-split givesworkspace replaced.- A restart mid-split gives uncertain and untrusted, with no replay.
12. Decisions and JSON shapes
- Host creator identity. A host
marsh splitattaches a temporary session only so shell branches have a shell VM. Its creator ishost: the handle is the join capability for host-level callers, so two host processes that hold the same handle are the same creator. A session (session:<id>, from its relay token) or a Kit job (job:<id>) can join only splits it created. The host is the operator forsplits rmandsplits cancel. - Depth. A root split is depth 1; creating depth 4 is refused (status 2,
depth limit 3 reached). - State strings. Split
stateis one ofrun,await,joined,kept,cancelled,uncertain. A cancelled branch's status iscancelled.
Selected JSON fields follow. The complete serialized fields are defined by SplitRecord, BranchRecord, and SplitRecord::manifest in crates/marsh-daemon/src/split.rs; Git source fields come from GitSource in split_fs.rs. (optional) fields may be absent, rather than null.
handle (split stdout, one line) {"marsh_split":1,"id":"<id>"}
out/manifest.json, join --json, and each element of `splits --json`:
{"version":2,"id":"<id>","state":"await","status":3 (optional until settled),
"creator":{"kind":"host"} | {"kind":"session","id":"<sid>"} | {"kind":"job","id":"<job>"},
"session":"<pool session id>","parent":null | {"split":"<id>","label":"<label>"},
"depth":1,"root":"<project>","dir":"<root>/.marsh/split/<id>","out":"<dir>/out",
"objects":"<dir>/store.git/objects","cwd":"<relative cwd>","created_unix_ms":0,
"reason":"workspace replaced" (optional),
"git":{"head":"<H>","objects":["<object directory>",...]} (optional),
"identity":[dev,ino],"timing_ms":{"snapshot":0,"forks":0,"run":0,"capture:<label>":0,"consumer":0},
"finished_unix_ms":0 (optional, all branches captured),
"branches":[{"label":"a","kind":"shell"|"argv","placement":"shell-vm"|"kit:<command>",
"state":"pending"|"running"|"captured"|"rejected"|"failed"|"cancelled"|"uncertain",
"status":"exited 0"|"failed: capacity"|"failed: <why>"|"rejected: <why>"|"cancelled" (optional),
"code":0 (optional),"job_id":"<job>" (optional),"files":2,
"trust":"untrusted" (optional),"fork":"<dir>/<label>",
"started_unix_ms":0 (optional),"finished_unix_ms":0 (optional)}]}
marsh splits --json [ID] {"splits":[<manifest>...]} (host: all; session: its own tree)
marsh status --json ... "splits":{"active":0,"awaiting":0,"kept":0}
marsh jobs show JOB --json ... "lineage":{"split":"<id>","label":"<label>"} (split jobs only)
Branch codes: exited N is N, failed:/rejected: are 125, cancelled is 130. split exits with the first nonzero code in declaration order.
13. Implementation bounds and process integration
- Descriptor-based I/O.
split_fs::Direnforces the no-follow operations used in section 8:- every directory is opened one
O_NOFOLLOWcomponent at a time from an open directory (split_fs::Dir); - files are created
O_CREAT | O_EXCL | O_NOFOLLOW, and read only after anO_NOFOLLOW | O_NONBLOCKopen and anfstatthat says the file is regular (so a FIFO cannot block the daemon); - a planted symlink at
.marsh,.marsh/split,<id>,out/<label>, or anyout/file makes that step fail; it is never followed.out/that cannot be written is reported asrejected: out/<label> was tampered with.
- every directory is opened one
- Capture. Same-size files whose mtime matches are still compared byte for byte when their ctime is at or after the fork's creation; a branch cannot set ctime, so an edit that restores the mtime is still seen. The limits are 32 MiB per file, 256 MiB of changed bytes (file contents and link targets), 256 MiB for the listing and patch (every byte they hold, C-quoting included), and 100,000 changed paths (
rejected: capture limit), with a 5 s deadline per text diff. Each walked tree holds at most 1,000,000 entries (directories included) and 256 MiB of path names, 256 levels deep; a directory is listed only while its entries fit, every name listed counts (an ignored one too, as it stays in memory while the walk is below it), and the plain walk holds one directory descriptor at a time. Each refusal names the limit and what to do, for the kind of project: list the directories that hold generated files in.gitignore(a plain project is told to make itself a Git project first), or have the branch change fewer files (or, in a Git project, ignore what it generates). A fork with more new entries, not counting the ones a Git project ignores, than the change bound is refused while it is walked; ignored names count only toward the tree's bounds; edits are refused at the change bound. Paths infilesare C-quoted when they contain control characters,", or\. - Writers before capture. After a shell branch exits, capture waits up to 30 s until no Kit job of the branch's session is queued or running. Otherwise, or when the branch's transport is lost, the branch is
uncertainanduntrusted. Its fork is never verified or removed, and its pool slot stays held untilmarsh workers reset. A split with an uncertain branch is never removed byjoin; it is kept. - Rendering. The text rendering replaces each binary hunk with
binary file changed: PATH (N bytes; full patch in $SPLIT_DIR/<label>/diff.patch);diff.patchkeeps the literal hunks. - Ignored output. In a Git project, capture skips each path the fork holds but the snapshot does not when the ignore rules exclude it (
core.excludesFile, the fork'sinfo/exclude, and the fork's.gitignorefiles, deepest first; an excluded new directory is skipped whole). A path present in the snapshot is always compared..marsh/.gitignoreis written only inside a Git worktree. - Environment filtering. Shell branches receive only forwardable exported variables. The filter excludes: -
MARSH_*,SBX_*, orDOCKER_*; - placement-bound or host-only variables; - credential-shaped names (*KEY*,*SECRET*,*PASS*,*TOKEN*,*CREDENTIAL*,*COOKIE*,AWS_*,*_PAT). The match is deliberately by substring, ignoring case: it also drops ordinary names such asKEYMAPorBYPASS_PROXY. A dropped variable is one the branch must be given another way; a credential that slipped through would sit in an agent's VM. Host-only values (TMPDIR,PWD,SHELL, ...) name Mac paths and are wrong in a VM. - Capability socket.
- The worker admits at most 132 open connections per attempt (
FAN_OUT_MAX + 4), including idle ones; an excess connection receives a refusal frame. - Each connection's queue is bounded in both directions (64 chunks), so a job that stops reading is disconnected instead of stalling the worker transport.
- Until a connection has a daemon slot, the host holds the first request it is sending: at most 4 MiB for all of one attempt's connections together. Past that, the connection gets a refusal frame and never reaches the daemon.
- On the host, the data and openings of an attempt's
cap.sockconnections that the daemon has not yet taken are bounded at 8 MiB. Past it, the connection that sent the data is closed on both sides, and the job's caller reads why on stderr; an opening past it is refused. The attempt and its output go on. - A connection reaches the daemon only once its first request arrived, and only with a slot from the daemon's connection budget. The daemon's own connections on a job's behalf (a
ProcessRunchild's start, the argv branches of a job's split) take one of the job's slots too. A job holds at most twice its livejob-children, plus 4, and all jobs together three quarters of the daemon's connection cap. A refused connection gets a refusal frame. - So jobs cannot take the last quarter of the cap. It is left to host
marshcommands, relays, shells, and host and session splits with their branches; only the host's own load can fill it. - The daemon serves at most 1024 connections, or more for a larger job pool: enough that the jobs' share holds two connections for every job of
daemon-jobs(1371 at its maximum, 512, so about 510 nested children run at once). It raises its descriptor soft limit (up to 16384, falling back to 4096) and serves no more connections than that limit affords at 7 descriptors each (a split branch's) with 512 to spare: 512 at 4096. Past the cap a connection gets a refusal frame. When descriptors still run out,acceptwaits and retries; the daemon never stops serving for it. - A shell's relay has two halves, the guest's in the shell VM and the host's in the daemon, and each enforces the same two caps. Daemon connections (
marshclients, links and splits reaching the daemon) are at most2 * POOL_LIMIT(128) open at once, idle ones included; the Docker endpoint's and the forwarded ports' connections are counted apart, at most 32. A services connection never takes a daemon slot. - A daemon connection past the cap, or one the host half cannot open to the daemon, reads one refusal frame (
marsh: this shell holds 128 daemon connections, its most; try again, ormarsh: this shell's relay could not open a connection to the daemon; try again), not a bare close, which a caller that had already written its request would see asConnection reset by peer. The guest half writes it when it accepts; the host half sends it as the connection's data and ordered end. The client reads it even when its own write failed first (a caller that wrote late, or a request larger than the socket buffers): a write that ends in a broken pipe or a reset takes the refusal queued on that socket instead (write_request; the ACP prompt, which frames its own bytes, calls the sameafter_failed_write). A source-level test (every_client_request_write_goes_through_the_refusal_recovery) fails if aClientmethod writes its request any other way. A refusal that says to try again (this one, the daemon's own cap, the job socket's cap) is what a link retries (is_retryable_refusal,job.rsretry_refusals: 30 attempts, 100 ms apart), and only a refusal that came before the daemon admitted the run:run_process_with_io_attemptreportsProcessRunError::NotAdmittedfor a failed connect or request write or a refusal in place ofExecutionAccepted, andMaybeAdmittedfor a reply lost after a whole request and for every failure afterExecutionAccepted, whatever its text. OnlyNotAdmittedis retried, so a run that may have started is never submitted twice (a_run_that_started_is_never_retried_whatever_its_failure_says). Unit tests inrelay.rs:guest_relay_past_its_capacity_refuses_with_a_frame_not_a_reset,a_client_that_writes_after_the_refusal_reads_the_reason_not_a_broken_pipe,a_real_client_with_a_large_request_reads_the_capacity_refusal,a_real_client_reads_the_refusal_when_the_host_cannot_reach_the_daemon,host_relay_rejects_the_connection_after_its_bounded_capacityanda_services_connection_does_not_take_a_daemon_slot_on_the_host,a_large_acp_prompt_at_capacity_reads_the_refusalandevery_relay_refusal_a_real_client_reads_is_retryable. The Docker endpoint answers past its cap with its own 429 (unchanged). - A relay half says so when it refuses a daemon connection: one line, then at most one more every 10 s that counts the refusals left unsaid. The guest's line (on its stderr) gives the open daemon connections against the cap and the services connections against theirs; the host half's, in the daemon's log, gives the daemon connections or that the daemon socket did not accept. The host passes the guest's refusal lines (and only those) on to the daemon's log, so a refusal in the VM is visible there: as plain one-line text (
sanitize_vm_text) of at most 300 characters, and at most 3 per 10 s, the lines left out counted on the next one. A prefix does not authenticate a line: whatever can write the relay's stderr in the VM can write a false one. The lines are for diagnosis. Tested:the_guest_says_once_how_full_it_was_when_it_refuses,refusal_lines_are_rate_limited_and_count_what_they_skip,only_the_guests_refusal_lines_reach_the_daemon_log,forwarded_guest_text_is_one_line_of_plain_text,a_long_guest_line_is_cut_and_an_endless_one_is_not_kept,a_flood_of_guest_refusal_lines_is_limited_per_window_and_countedand, in the backend,drain_tests::the_guest_relays_refusal_lines_reach_the_daemons_log_and_its_head_is_kept. Diagnostics are written with a write that ignores failure, so a closed stderr never panics a relay thread (not tested). - Split input that spooling and running splits hold is bounded: 64 MiB for one job's splits, 192 MiB for all jobs' splits, and, apart, 256 MiB for the host's and sessions' splits (a session shell is the user's), so no job can refuse them. Each job of a tree has its own 64 MiB, so one tree can fill the jobs' pool and refuse other jobs' splits.
- The worker admits at most 132 open connections per attempt (
- Nested splits from a shell branch.
marsh splitrun inside a shell branch arrives on that branch's session relay. The daemon maps the session to the branch, so the split is a child: argv-only, depth + 1, and cancelled when the branch exits. - Join and release. If the join reply cannot be written or no release arrives, the split returns to
kept. A released split is renamed into.marsh/.trashthrough descriptors, after the identity check, and deleted in the background. Barejoinescapes control bytes when its stdout is a terminal. - Retention. A kept split is removed 7 days after it was kept (
kept_unix_ms), unless a branch is uncertain.marsh splitslists kept splits with their state and times, andmarsh splits rm IDremoves one now (the host can remove any). Removals go through.marsh/.trash, which the daemon sweeps at startup for every project it has journaled. - Kit VM limit. Splits add no Kit VM cap of their own. Process admission caps distinct live Kit VMs per job tree (
processes.md, section 6).
14. Open lanes, checkpoints, and storage
Checkpoints. marsh checkpoint [--label TEXT] [--json] snapshots the project exactly as a split's base/ is made (section 8) into <root>/.marsh/checkpoints/<id>/tree, and saves the Git metadata a fork needs (resolved HEAD, index, packed-refs, info/exclude) in <id>/git. The daemon journals each checkpoint (checkpoints.json in the control directory, with the directory's identity) and reaches its files only by descriptor.
- At daemon start a record is forgotten only when its project opens and its directory is missing. One it can't reach now (an unmounted volume, access denied) or whose directory isn't the recorded one is kept, and the orphan collector skips that project while any of its checkpoints can't be opened, so their Docker snapshots stay. A checkpoint is recognised by its directory's
(dev, ino), or, where the volume guarantees persistent file IDs (APFS; recorded at create), by volume UUID and file ID, so an external volume mounted again (a new device number) keeps its checkpoints.marsh checkpoints rmand retention remove only a checkpoint so recognised, or verifiably gone; any other is kept with its snapshots, andrmsays why. - An unreadable
checkpoints.jsonis renamed tocheckpoints.json.unreadable-<ms>(copied, if it can't be renamed; left alone and never written if neither works). While any such file is in the control directory, across restarts, no services snapshot is dropped (by the orphan collector,rmor retention) and the backend's lane protection is not reconciled: restore it ascheckpoints.json, or remove it, to collect again. - Retention runs on every create and at daemon start: the newest 20 per label (unlabeled checkpoints are one label), none older than 7 days, at most 200 per project. A retired checkpoint goes to
.marsh/.trash. - A create is refused with exit 75 when the volume has less than 5 GiB or less than 5% free.
- Creating anything under
.marshmarks it excluded from Time Machine (the stickycom.apple.metadata:com_apple_backup_excludeItemattribute) and adds.metadata_never_index. - A checkpoint is immutable: no job mounts it (
CheckpointImmutable), and a Kit job whose cwd is in one is refused like any non-fork path under.marsh. marsh checkpoints [--json] [--label TEXT]lists them newest first ({"checkpoints":[{"checkpoint","label","created_unix_ms","root","dir","bytes","lane","services","ignored"}]};servicesis the project's services snapshot,docs/design/services.md"Snapshots in checkpoints";ignoredis the folder local data (git-ignored files) saved besidetree/inignored/, "Folder local data in checkpoints");marsh checkpoints rm IDremoves one.- A split being made
--froma checkpoint leases it until itsbase/is cloned: retention passes over a leased checkpoint (the next pass retires it), andrmof one fails with "in use by a split being made from it; retry". - Every project that gets a
.marsharea is journaled (project-roots.json) before the area is made; at daemon start each one's.marsh/.trashis emptied, and a project with no splits, no checkpoints, and an empty trash is forgotten.
Lane checkpoints (feature lane-checkpoints-v1). marsh checkpoint --lane SPLIT_ID/LABEL [--label TEXT] [--json], run from the project's root, snapshots an open lane's copy (or the copy of a captured lane of a kept split) as a checkpoint of the project, so a later marsh split --open --from CKPT starts from that lane's state. It is made exactly like a project checkpoint (section 8's pruning and the lane's own ignore rules, .git and .marsh left out), stored under the project's .marsh/checkpoints, and listed, retained, leased, labelled and removed like any other; checkpoint and checkpoints --json carry "lane" (SPLIT_ID/LABEL, null for a project checkpoint). Its git/ holds the lane's resolved HEAD, index, packed-refs and info/exclude, read from the lane's .admin directory by descriptor (a lane job can write the admin index, objects and refs, so they are data and never followed), and git/objects, the objects the lane's jobs and the split's store.git hold that the project's repository lacks. A split --from it clones those into its own store.git/objects, so it does not depend on the checkpoint staying.
- Authority. Only the split's creator (the host for a host split, as for
close) or the host may; another session is refused ("only its creator can checkpoint its lanes"). A job has no way: its capability socket admits onlyProcessRun,ProcessShow, jobs,SplitCreate,SplitJoinandOpenUrl, and the engine refuses aJobcaller as well. This keeps the rule that a lane job never snapshots outside its copy: the daemon reads the copy, the job asks for nothing. - State. Open means the split is
run, not closing, and the lanerunning; kept means the split iskeptand the lanecaptured. Anything else (closing,uncertain, cancelled, joined) is refused. The copy is read while the lane's jobs may still write, as a project checkpoint is of a live project; the daemon rechecks the record before recording the checkpoint, and discards the copy if the lane was closed, cancelled or removed meanwhile (a removal takes the record before any file). - The request must name a split of this project (
root), a lane that exists, and pass the same label and free-space checks asmarsh checkpoint(exit 75).
--from CHECKPOINT. A root split may start from a checkpoint of its project: the daemon clones the checkpoint's tree into base/ and builds every fork's .admin from the checkpoint's saved Git metadata, with the project's .git/objects as alternates. The manifest records from. A checkpoint that holds ignored/ (docs/design/services.md, "Folder local data in checkpoints") has it copied into each lane's folder right after the fork is made and before any Docker restore; the lane's base/ does not have those files, so split apply never carries them back. A split --json reply gains restore per lane with the restore (C3).
Open lanes. marsh split --open [--from C] LABEL... (host or session shell only; not from a job or a branch) makes a split whose branches have no command: each is a lane (kind and placement lane, state running). It replies at once with {"marsh_split":1,"id":ID,"lanes":{LABEL:FORK}} (with "restore":{LABEL:…} after the app data restore when --from names a checkpoint that holds some, services.md "App data in lanes"; a lane's close, cancel or removal also drops its services objects by workspace, and split apply leaves the generated lane files compose.fork.yaml and .env out of the patch). The split stays run, with no lease and no deadline, until it is closed or cancelled.
- Lane jobs. A Kit job whose cwd is in a lane's fork is confined to it (section 8). The daemon admits it only while the split is
run, not closing, the lane is still open, and the caller is the split's creator (hostfor a host split, the session for a session split); otherwise it is refused (exit 125) before any effect. The admitted job is counted live in the journal (liveon the lane) until itsExecuteends, and recorded with lineagesplit:<id>/<label>. A lane runs any number of jobs, long and interactive ones included (marsh run --acp NAME). Their children are admitted with them. Admission comes before the Kit is prepared, so a close or cancel, in the same locked step that setsclosing, also fences the split: from then on no job whose mounts name one of its forks is recorded or submitted. The step is then journaled. It is never undone: if that write fails, the split stays fenced andclosingin memory, the error says so, and repeatingmarsh split close IDormarsh splits cancel IDresumes it and writes the journal again. A restart before that retry depends on what reached disk: onceclosingis insplits.json(the second journal file, the lineage, failed) the split iskeptand its lanesuncertain; if the first write failed before its rename, disk still says open and the split is preserved as open. A close or cancel already running refuses a second one. - No split from a lane job. A job's split is planned from the job's recorded mounts, never its cwd: a job (or any descendant, which inherits its parent's mounts) whose mounts name a branch fork nests in that fork, and one whose mounts name a lane is refused ("a job in a lane cannot start a split; split from the host or a session shell"), whatever path it passes. A job whose recorded fork's split is gone is refused, never given the project.
- Several agents in one lane. Jobs of any Kit run in a lane at once (a checkpoint's copy shared by N agents): every Kit VM mounts the same project root (identical sources are shared) and each job's container sees only the fork. The per-tree Kit VM cap, depth, and launch rate bound a job's descendants, not sibling lane jobs, which are separate trees. Host
marsh fanoutin a lane's copy runs each branch asmarsh run NAME ARG...from the copy (a confined lane job, counted live like any other), registered names only; a-bshell branch is refused, since a shell would see the whole project. - A shell in a lane's copy. An interactive
marsh(ormarsh -c) started from the host with its cwd in a lane's copy takes the split's root as its project and starts in the copy, as a hostmarsh runthere does (a shell project of the fork itself would overlap the Kit jobs' mounts of the root, which the overlap rule refuses and keeps refusing). It is trusted user code in the shell VM, which mounts the whole root, as a split's shell branches are. It is not a lane job: it is not counted live, close does not wait for it or fence it (so the capture's stability,CaptureStable, holds for lane jobs only;docs/model/README.md), and Kit commands started from it are refused for a host split ("only its creator"). An interactive one prints "changes you make here are captured only if made before Finish" when it starts. - Cloud lane jobs.
marsh cloud [-d [--label L] [--json]] -c SCRIPT | -- PROGRAM ARGSwith its cwd in a lane's copy is a lane job: it is admitted and fenced as above (refused after a close or cancel, exit 125), recorded with lineagesplit:<id>/<label>and the copy as its mount, uploads the copy (its Git view is the fork's), and writes its changes back into the copy, never the live project, so the lane's capture andapplyinclude them. Submission is fenced: the store marks the job running (the step after which the sandbox bills) under the lock a close or cancel sets the split's fence with, so a job still uploading when either begins never starts, and its sandbox is retired. The setup observes a cancel (the caller's or a lane split's, through the store) before the sandbox is created, right after (the sandbox is then deleted), and around the upload, so a cancelled lane does not provision. The sandbox id is journaled on the job as soon as the create returns; a sandbox whose job was still being set up when the daemon went away is retired by the next collector pass; its id is kept incloud-setup-orphans.jsonacross any number of restarts until the retirement is verified (an ownership read that fails is retried, never taken as "not owned"). A detached run stays live for its lane until collection settles it (kept as a patch, collected, failed, lost, or discarded):closecollects it every 3 s while it waits (30 s), so a run that has finished writes back before capture; one still running makes the laneuncertain.splits cancelis journaled with the split (cancelled) and discards every detached run of the split: at once, and again on every collector pass and after a restart until its sandbox is verified gone, and collection of such a run discards it instead of writing back (the last cancel check and the import are one step under the root's import lock).splits rmrefuses while one is live. marsh split close ID [--json](creator, or the host): stops admitting lane jobs, waits up to 30 s for the lane's live jobs (and any job whose mounts name its fork) to end, then captures each open lane exactly as a branch is captured. A lane whose jobs did not end, or ended with cleanup uncertain, isuncertainanduntrusted, never verified or removed. A captured lane's status isclosed(code 0). The split becomeskeptand the reply is the manifest;out/<label>/{diff.patch,files,status}hold the results.marsh split apply ID LABEL [--3way] [--json](the split's creator) applies a captured lane'sdiff.patchto the project withgit applyinside the shell VM (from the host, throughmarsh -c), with the split'sstore.git/objectsasGIT_ALTERNATE_OBJECT_DIRECTORIES. It is a join that keeps the split: while it runs the split isjoined, so neithersplits rmnor the collector removes the patch under it, and the release keeps it with a fresh 7 days. A lane with no changes applies nothing.--jsonprints one object,{"result":"clean"|"conflicts"|"failed"|"unknown", "files":[paths],"conflicts":[paths],"message":TEXT}, and decides the outcome from git and the project's index, never from git's text. git alone does the apply, and marsh never rolls anything back (a rollback would overwrite an editor's save or agit addmade meanwhile):git apply --check, then a plaingit apply(git checks the whole patch before it writes, so a patch that does not apply writes nothing; a filesystem error while writing can still leave it partial, which isunknown); a patch that does not check is retried with--3way(which writes nothing when it fails; its merged changes are staged).clean: applied.conflicts: some paths merged with conflict markers and unmerged index entries (conflictsare the unmerged paths).failed: git wrote nothing (filesis empty), including a project whose index already has unresolved conflicts.unknown: marsh cannot tell what was written (the shell VM's reply was lost after the apply began, git ended abnormally, or the 3-way result could not be made self-contained);fileslists the paths the patch touches, and the user checks withgit status.filesfor the other results are the paths the patch changes, fromgit apply --numstat -z(NUL-delimited, never the quotedfileslisting), so names with quotes, backslashes, or newlines are exact. A 3-way merge stages blobs read from the split's object store: the ones the patch names are copied into the project's own, each id verified, BEFORE the index is touched (a failed copy isfailed, the index as it was), and the index is checked to resolve without the split's store beforecleanorconflictsis reported. A root that is not a Git repository gets the plain apply only (cleanorfailed). Exit status 0 forclean, else 1; a split or lane that cannot be applied isfailedwith status 1 (2: no captured lane).- Cancel.
marsh splits cancel IDon an open split stops admission (journaledclosing, and the fence), cancels every live lane job tree (INT, then KILL after 10 s). A job marked cancelled before it could be signalled (its Kit still being prepared) keeps the cancel: it is delivered (INT, then KILL after 10 s) the moment the job's container registers, and the split waits for that job too. Once every lane job's end is confirmed, removes the split's files; otherwise the split is kept with the unconfirmed lanesuncertain. A closing split cannot be cancelled. On a kept or uncertain lane split, cancel ends the lane jobs a close timed out on; the lanes stayuncertain. - Removal.
marsh splits rm ID(and the 7-day kept-split collector) never removes a lane split while a lane job may still write: it refuses while a lane job runs ("still has a running lane job; end it withmarsh splits cancel ID") or while one's end is unconfirmed and its Kit was not reset since ("runmarsh workers reset all").splits rmand the collector check and claim the split (taking its record) in one step under the lockjointakes it with, so a join orsplit applyeither wins (the split isjoinedand the removal is refused; if kept again its 7 days restart) or finds it gone. - Restart.
closingis journaled. An open lane split whose lanes had no live job and no close under way stays open; one with a live lane job becomesuncertain(section 6). A close or cancel the restart interrupted leaves the splitkept, its still-open lanesuncertain("daemon restarted while closing"), forks in place; it never reopens.
Storage. marsh storage [--json] [--all] reports, for the current project (every journaled project with --all): {"projects":[{"root","checkpoints":{"count","bytes"},"kept_splits":{"count","bytes","splits":[{"id","state","bytes","kept_unix_ms"}]},"volume":{"free_bytes","total_bytes"}}]}. Bytes are logical (APFS clones share blocks until they diverge).
Events. Split changes are published to marsh events (results.md) as {"seq","type":"split","split":{"id","state","root","branches":[{"label","state","job_id"}]}} (state removed when the record is gone), checkpoint changes as {"seq","type":"checkpoint","checkpoint":{"id","root","label","removed"}}. At most 8 subscribers are connected at once (each holds one of the daemon's 128 connections); a ninth is refused with "marsh events: at most 8 subscribers at once", and ordinary requests are never held off.
The model covers lanes (many jobs per lane, admission only while open, close before capture, restart, restart during close, cancel and removal of a kept lane split), lane jobs never splitting, and the checkpoint as an immutable source: Workspace_lanes_pass.cfg, and the controls laneAfterClose, captureLiveLane, laneRestartLive, checkpointMounted, laneSplit, restartReopens, and removeLiveLane. A lane checkpoint adds no state to the model: its Ckpt is already an abstract immutable source that no job mounts, whatever tree it was copied from, and checkpoint --lane is a daemon read of a lane's copy that gives no job an authority (the job capability socket does not carry it). The checkpoint lease, the event subscriber cap, and the collector/join race are checked in code tests (checkpoint.rs, crates/marsh/tests/workspace_cli.rs).