# Coding agents (mounted workspaces)

A Swarmfile repository mounts as a real filesystem path. That makes it a good
workspace for a coding agent: the agent reads and writes ordinary files, and
every change is versioned, lockable, and shared - no `git clone`, no
`git worktree` per task, and no full re-install of dependencies for every
parallel checkout.

The shape this guide builds:

- one **engine process** per machine (or per agent when you want process isolation - see below),
- one **repository API key** (optionally branch-scoped, or path-scoped when the agent should not touch git) so the engine runs headless (no browser sign-in),
- one **mount per agent**, each with a label and (optionally) its own branch,
- one **shared scratch cache** per repository per machine, so a second mount
  reuses the first one's downloaded packages,
- an optional **installed dependency tree**, so a new branch or a second
  workspace starts without reinstalling (see [§3](#3-shared-dependency-cache)),
- and the **durable create queue**, which is what makes a burst of
  file creations from an agent safe.

The same primitives appear in the Desktop App - this guide is the scripted,
headless form.

## What each agent gets, and what it must not be given

Give an agent:

- **The mount path.** It's a normal POSIX/Windows path
  (`~/agents/agent-1/…`, `X:\…`). Everything the agent does happens
  there; there is no separate "sync" step.
- **The scratch dir** (below) as the place for tool caches.
- **Exit codes** (below) so its automation can tell "you need to do
  something" (2) from "something failed" (1).
- **One `SWARMFILE_*` environment set** per engine - never two engines
  sharing a cache directory.

Do **not** hand an agent:

- A second mount point that points at the *same directory* another agent
  uses - mount points are exclusive to one engine process.
- A personal refresh token copied off a workstation. Use a repository API key:
  it's revocable, it's walled off to one repository, it can be branch- or
  path-scoped (see [§7.1](#71-branch--and-path-scoped-keys-and-read-only-delegations)),
  and it can't act as the human who minted it.

## Platform matrix: how many mounts per engine

| Platform | Several mounts in one engine? | Recommended shape for N agents |
|---|---|---|
| Windows (WinFsp) | Yes - `mounts open` takes a drive letter (`Y:`, `Z:`, …), `auto` for the next free one, or an **empty** folder (a folder with anything in it is refused) | One engine, N mounts, one API key |
| Linux (FUSE) | Yes - `mounts open` takes directory paths (same engine path as Windows; macOS/Linux use a folder, not a drive letter) | One engine, N mounts, one API key |
| macOS (FUSE-T) | Yes - `mounts open` takes directory paths; FUSE-T provides 18 mount-helper slots per Mac, shared with every FUSE-T app (not a macOS mount limit - see below) | One engine, N mounts, one API key |

An engine can serve every agent's mount: auth is one API key, and the shared scratch cache (below) is per machine, so the dependency cache is still paid for once. Running one engine per agent remains a valid isolation choice (a wedged mount helper then can't affect siblings), but it isn't required on macOS. FUSE-T provides 18 mount-helper slots per Mac, shared by every FUSE-T app on it.

An `open` at capacity fails with `fuse_t_helper_ports_exhausted`: close a drive or quit the app holding a slot, then retry; `swarmfile doctor` names the holders. A boot mount that never attached can retry in place with `swarmfile mounts retry`; one that attached earlier needs a restart.

## 1. Headless engine with a repository API key

The commands in this guide use the `swarmfile` CLI, which ships with every platform installer (Linux `.deb`, the Windows MSI, the macOS `.pkg`). A headless box needs only that package - no GUI sign-in - and the CLI resolves the running engine's control socket on its own. See [CLI: swarmfile](https://swarmfile.com/docs/cli/swarmfile) for the per-platform install locations.

Mint a key as an org admin or owner, from any running engine:

```bash
swarmfile api-key create agent-node-1                 # this mount's repository
swarmfile api-key create agent-node-2 --repository proj_… # or an explicit repository id
```

`--repository` takes a **repository id**, not a slug (a slug is refused with
`repository_not_found`, and the error names the id to use). The secret is printed
**once** (`sf_key_…`). List and revoke
keys with `swarmfile api-key list` and `swarmfile api-key revoke <id>`. A key
is walled off to exactly one repository, so a compromised agent node can't reach
anything else in the org.

Keys count against your plan's **headless-seat allowance** (Free 1, Starter 2 per
seat with a minimum of 5, Pro 5 per seat with a minimum of 10, Studio 10 per seat
with a minimum of 20), and an additional headless seat is $2/month on any paid
plan (one repository-scoped key each).
One key per machine/fleet is the recommended pattern (revocation radius and its
own rate-limit bucket); a `402` with `code: keys_cap` means the org is at its
cap, so revoke an unused key or add a seat under Settings → Billing. Agents
running through a workstation's existing mount need no key at all.

To give each agent its own engine (process isolation; otherwise one engine
can host every agent's mount, as the matrix above recommends), point each at
its own cache dir and mount point:

```bash
export SWARMFILE_API_KEY=sf_key_…
export SWARMFILE_ORG_ID=org_…
export SWARMFILE_REPOSITORY_ID=proj_…
export SWARMFILE_CACHE_DIR="$HOME/.swarmfile/agent-1"   # one per engine
export SWARMFILE_MOUNT_POINT="$HOME/agents/agent-1"     # one per engine
export SWARMFILE_MACHINE_ID=agent-node-1
swarmfile-engine
```

With `SWARMFILE_API_KEY` set, the engine skips sign-in entirely - no
browser, no refresh token. (If both an API key and a refresh token are set,
the key wins and the engine says so in its log.) See the
[`api-key` CLI reference](https://swarmfile.com/docs/cli/swarmfile#api-key) for the full flags,
and [Deployment Topologies](https://swarmfile.com/docs/guides/deployment-topologies) for putting
these on dedicated boxes.

## 2. One mount per agent (and targeting it)

The engine's first mount is the **boot mount**, id `default`. Additional
mounts are full, symmetric mounts - each with its own changelists, metadata,
and lock manager:

```bash
swarmfile mounts list
swarmfile mounts open Y: --label agent-2 --branch feature-x
swarmfile mounts open Z: --label agent-3 --repository proj_other
swarmfile mounts status agent-2-id
swarmfile mounts current agent-2-id
```

> The examples use Windows drive letters; on macOS and Linux the mount point
> is a directory path instead (e.g. `swarmfile mounts open /Volumes/agent-2
> --label agent-2`). Everything else - labels, ids, `--branch`, `--repository`,
> `status`, `current` - is the same on every platform.

- `--conflict-mode hard` makes the mount tell an agent the truth about
  a lost write: when a save would overwrite a version another writer changed
  first, the saving `fsync` (and on Linux the close-time `flush`; on Windows
  `FlushFileBuffers`) waits for the server and fails with a stale-version
  error (`ESTALE`; Windows: the file-was-externally-altered status) instead
  of accepting the save locally and surfacing the conflict later.

  Agents should `fsync` before treating a save as committed - on macOS a `close()`
  cannot carry the error (the NFS client would retry it forever).

  Without hard mode (neither this flag nor a repository's `conflictMode` = hard in
  repository settings), a save that lost the race parks quietly - fine for a human at
  the tray, wrong for a loop that will never look.

  Agents should treat the error as "re-read the file, re-apply your change, retry"; `EAGAIN` from the
  same call means the server is just slow (the save stays queued - fsync
  again later).

  A checked-in `.swarmfile/conflict-policy` can mark regenerable paths
  (lockfiles, build output, generated code) as newest-wins. A stale save to a
  matching path is resolved in the newest writer's favor through the hub's
  conflict record instead of parking read-only; the replaced version stays on
  the conflict record.

  It is opt-in per path, gitignore syntax with `!`
  exceptions, and `swarmfile mounts status <id>` reports how many rules the
  mount found. Unmatched paths keep the behavior above. A fresh write against a held editing lock is still refused; a stale replay
  that already conflicted is not re-checked against the lock at resolve time
  today.

![Two agents work one branch from their own mounts: both read index.html, the first save lands, and the second agent's save - made against the version it read, over a range that does not even overlap - is refused. The agent takes the teammate's version, re-reads, re-applies, and both writes land.](https://swarmfile.com/demo/oss-agents.cast)
- `--label` is for humans; the id (a long hex string, or `default` for the
  boot mount) is what scripts use - take it from `mounts list --json`.
- `--branch <name>` pins that mount to a branch. It opens (or reuses) a
  divergent `(repository, branch)` scope, so the mount works that branch while
  every other mount stays on its own - and can be switched later with
  `mounts branch`.   A unique directory root per agent (e.g. `/agents/<name>/…`)
  is still good hygiene, but not required: the engine creates missing ancestor
  directories on a directory create, so a fresh branch is safe to write into
  anywhere.
- `--repository <id>` opens a mount on a different repository in the same org.
- `--sparse <glob>` (repeatable) opens a **sparse** mount: only the matching
  paths are visible (and writable) on that drive, so an agent working one
  package never sees the rest of the repo. `--exclude <glob>` is sugar for the
  `!` negations ("everything except"); an excluded path has no listing entry,
  refuses an open and a write-create, and the mount's offline (`hydrate`) set
  matches. Scope is per mount, so branches mount differently.
- `--exclusive` opts that mount into **exclusive-write mode**: while it has a
  file open for writing, another mount opened with the same flag on the same
  repository+branch has its write-open refused (the app sees `EAGAIN`, or
  "file in use" on Windows) - a rename, delete, or atomic-save replace of that file is refused too -
  instead of both editing the file and the later save becoming a conflict to resolve.

  Off by default, fixed at open, and shown as a lock badge in the drive list. Open
  **every** agent mount with it when several agents share one tree, and pair
  it with `--conflict-mode hard`: two mounts of one engine are a single
  identity to the hub, so ordinary locks do not separate them.
- Every command that isn't under `mounts` targets the current mount unless
  you pass the global flag:

```bash
swarmfile --mount agent-2-id status
swarmfile --mount agent-2-id commit -m "agent 2 results"
```

Close a mount with `swarmfile mounts close <id>`. It refuses while a
changelist is open (`--force` abandons it) and refuses the boot mount
outright (`exit 2`, `is_default_mount`) - closing that one means shutting
down the engine.

## 3. Shared dependency cache

Every mount of a repository on a machine can share one **scratch directory**
for tool caches (a pnpm store, a cargo registry, a pip wheel cache). Declare
what `run` should redirect, in a committed file at the repository root:

```yaml
# .swarmfile/cache.yml
caches:
  - name: pnpm
    env: PNPM_HOME
    subdir: pnpm
  - name: cargo-registry
    env: CARGO_HOME
    subdir: cargo
```

`swarmfile scratch init` writes a commented starter file. Then run installs
and builds through `run`, so the tool sees the shared cache:

```bash
swarmfile mounts scratch-dir default     # the shared dir + declared redirects
swarmfile run -- pnpm install            # PNPM_HOME -> shared scratch
swarmfile run -- cargo build --release   # CARGO_HOME -> shared scratch
```

`run` passes stdio and the exit code through, and it never refuses to run
your command over a cache problem - with no config, a bad entry, or an
unreachable engine it warns and runs the command unmodified.

Maintenance:

```bash
swarmfile scratch list
swarmfile scratch gc --older-than-days 14 --dry-run
swarmfile scratch clear <name> --force
```

One scratch dir per repository per machine, shared regardless of branch. Only
redirect **read-mostly, content-addressed caches** - not build output
directories, which would contend between concurrent mounts. Nothing in a
scratch cache is unrecoverable repository data; clearing one only costs a
slower next build. Full reference: [`scratch`](https://swarmfile.com/docs/cli/swarmfile#scratch)
and [`run`](https://swarmfile.com/docs/cli/swarmfile#run).

### Installed dependency trees

The scratch cache removes the downloads, not the extract: a fresh mount still
runs the installer over its packages (about 22 s for 69 packages). Two opt-in
forms keep the installed tree itself:

- **Hub-backed, for agents on different machines.**
  `swarmfile workspace warm --share-deps -- npm install` installs inside
  `.swarmfile/deps/<OS-arch-Node-ABI>-<libc>-<lockhash>/tree`, stages the
  packages copy as `tree/.packages.partial`, renames it to `tree/packages`
  with a completion marker, and leaves a relative `node_modules` symlink. A
  branch forked with `swarmfile mounts new --from <warming-branch>` inherits it.

  Measured: **126 s** one-time install+copy, then a 1,246-file fork ran
  `require("express")` with no install, including from a fresh engine cache.

  It is ordinary repository content - synced and storage-billed; `.npmrc`
  credentials are never copied; pnpm's nested layout and a WinFsp mount are
  not supported.
- **Machine-local, for agents on one machine.** `swarmfile workspace warm
  --local -- npm install` installs in the engine cache and imports the tree
  into the mount as local-only metadata/blocks (no hub row, no absolute link).
  A new workspace on the same machine attaches it with no install - measured
  **14.6 s** first install+import (2 s npm, warm cache) and **12.6 s** for the
  second workspace.

  It is Unix-only, must run from the mount root, and
  refuses workspace/monorepo installs; the import is capped at 20,000 entries
  and 512 MiB per file. Executable bits are preserved (so `.bin` tools run),
  a strict E2E/static mount is refused (the layer is plaintext), and a failed
  import is rolled back rather than left as a truncated tree.

  `workspace deps gc` lists/removes old layers; `workspace deps materialize <key> <checkout>`
  copies one into a plain (unmounted) checkout on the same machine.

Both forms key on the repository's manifests, and `--local` also keys on the
install command; a cached `--local` hit does not run the command (the CLI says
so, and `--json` reports `commandRan: false`). Remove the old `node_modules`
once after a lockfile change. Old layers are manual cleanup with the repository's
`swarmfile workspace deps gc --kind local` (a live layer is kept by its repository marker; `--keep`/`--force` handle the exceptions).
Full flags: [`workspace warm`](https://swarmfile.com/docs/cli/swarmfile#workspace); the limits are
in [Known Limitations](https://swarmfile.com/docs/reference/known-limitations#workspace-dependency-sharing-has-storage-and-platform-limits).

## 4. Create bursts and the pending-create queue

File creation returns immediately on the drive. On the mounted drive, a create (or `mkdir`, or a symlink on macOS/Linux - Windows refuses symlink creates) returns at once under a locally minted id; a background worker confirms it with the hub (8 in flight by default) and peers on the LAN see the name by gossip before the hub does.

Creates that are due together go to the hub together, up to 50 in one request, and a new file's first save travels with its create instead of in requests of its own. This is what makes an agent's scaffolding burst safe and fast: on Pro's default limits, 5,000 new files reach the hub in under a minute (lower plans drain the same burst more slowly, and nothing is lost), and a create made while the hub is unreachable simply queues.

What to check, and what an agent will see:

```bash
swarmfile status                 # "new files: N waiting to reach the hub (oldest …)" while queued
swarmfile --json status | jq .pendingCreates
```

| `pendingCreates` field | Meaning |
|---|---|
| `queued` | Creates this machine made that the hub hasn't confirmed. `0` = drained. |
| `cancelled` | Deleted locally before the hub heard of them; no hub call needed. <!-- docs-lint-allow cancelled: the JSON field is spelled this way in the wire format --> |
| `stuck` | Queued and failed 6+ times - hub refusing or unreachable for these. |
| `oldestAgeSecs` | Age of the oldest queued create. Growing with `queued` unchanged means nothing is draining. |
| `peerUnconfirmed` | Entries peers gossiped as created that this machine hasn't seen confirmed. |
| `items` | The oldest 20 queued creates (path, type, attempts, age). |

Rules of the road while something is pending:

- **A name collision on the hub renames, it doesn't overwrite.** If the hub
  already has a different file at that path when the queued create lands,
  your copy is kept as `name (conflict-xxxxxxxx).ext` and the error ring
  says so.

  The exception is a name held only by this machine's own queued
  delete or move of the old file - an editor's safe save, which moves the
  original aside and deletes it - where the create waits (up to two
  minutes) for that to reach the hub and then keeps its name; it shows as
  queued meanwhile. A **folder** with the same name is merged into the hub's folder
  (like `mkdir -p`) - files you created inside it land there, and the hub's
  existing contents appear after a few seconds.
- **Operations on a just-created file wait, then answer `409`.** Locking,
  ACL reads, share-link creation and comment writes on a pending file wait
  up to 8 seconds for the create to confirm and then proceed. A change (a
  lock, share, ACL or comment write) sends the file's create at once, even
  while its first save is still uploading, so it doesn't wait behind that
  save. If the hub
  can't be reached in that time they answer `409` with
  `code: "pending_create"` - retry shortly. For an entry *another* machine
  created and the hub hasn't confirmed, the refusal is immediate.
- **A create the hub refuses for good is retracted** from peers and reported
  once in the error ring (`create failed for "…"`). An empty file, a
  symlink, or a folder is removed. A file you had already written content
  into is **kept on this computer only** (never uploaded) so the work isn't
  lost - the message says so. Content in files under a refused folder is
  discarded, and the count is in the message.
- **Deleting or renaming a just-created file** is passed to other machines
  immediately. A file a peer created that never reaches the hub is removed
  after 6 hours with a message.
- **A new file can reach the hub up to a minute after it appears locally.**
  While a new file's first save is still uploading, its create waits for it
  (up to 60 seconds) so the two go to the hub as one request. Other machines
  on the LAN see the file at once by gossip, and the web dashboard's Files
  view shows "N files arriving from …" until the hub has them.

Tunables, rarely needed:

| Variable | Default | Effect |
|---|---|---|
| `SWARMFILE_CREATE_DISPATCH_CONCURRENCY` | `8` (1-64) | Creates sent to the hub at once when they go one by one. Lower it if the hub keeps answering `429`; raise it on an unthrottled hub. |
| `SWARMFILE_PENDING_CREATE_WAIT_SECS` | `8` (0-120) | How long lock/ACL/share/comment writes wait for a pending create before `409 pending_create`. `0` refuses at once. |
| `SWARMFILE_CREATE_BATCH` | on | Send due creates in batches of up to 50 per request. `0` sends each on its own. |
| `SWARMFILE_CREATE_COALESCE` | on | Send a new file's first save with its create (one request). `0` sends the create, then locks and commits separately. |
| `SWARMFILE_CREATE_HOLD_UPLOADING_SECS` | `60` (0-600) | How long a create waits for its first save while that save is uploading. The upload finishing sends it at once, so this only caps a stall. |
| `SWARMFILE_CREATE_HOLD_SECS` | `2` (0-10) | How long a create waits for a file that is open for writing but not saved yet. `0` turns off all waiting. |
| `SWARMFILE_ARRIVING_REPORTS` | on | Tell the repository how many new files are on their way (at most once every 30 s), for the dashboard's "files arriving" note. `0`/`false`/`off` turns it off. |

These are client-side. The hub's own ceilings are per-org and per-user (plan defaults, owner/admin configurable). Each active API key gets its own window; a per-key limit (`swarmfile api-key rate-limit`) changes that key's bucket.

The shared org window is the larger of the plan's per-org default and active keys × the per-key default, capped by the plan org max and by the plan's key allowance (purchased headless seats): give each machine or fleet its own key to add a bucket and scale the org window, not one shared key with a high limit. `swarmfile admin rate-limits usage` reports this minute's usage against them; see [Organizations, Repositories & Members](https://swarmfile.com/docs/admin/organizations-repositories-and-members#who-can-see-plan-and-usage-standing).

### How fast can one user create files?

The per-user ceiling is a number of requests per minute, and it depends on the plan. Defaults:

| Plan | Per-user default | Owner/admin can raise it to | Per-org default |
|---|---|---|---|
| Free | 100 / min | fixed | 300 / min |
| Starter | 300 / min | 500 / min | 1,000 / min |
| Pro | 500 / min | 1,000 / min | 1,000 / min |
| Enterprise | 500 / min | 5,000 / min | 10,000 / min |

The per-org column is the default; active keys scale it to the larger of that default and
(active keys × the per-key default), up to the plan org maximum (Enterprise auto-scaling stops at
50,000/min). The plan key allowance caps how many active keys count.

What counts against it is requests, not bytes, and block uploads are not counted at all:

| Kind of new file | What it costs |
|---|---|
| A new file with content (saved when it is created) | one create that carries its first save: **1 request**, or **a tenth of one** when it goes out in a batch |
| An empty file or folder | **1 request**, or **a tenth of one** in a batch |
| A file created empty and written later | create, take the write lock, then one commit that also gives the lock back: **3 requests** |

Batching is paced to the plan's per-minute allowance: on Pro's default ceiling (500 requests a minute), a
5,000-file burst drains in well under a minute - batched creates cost about a tenth of a unit per file, so a
full 50-file batch is 5 units even though it is a single HTTP request. Nothing is lost when a limit is reached;
the queue simply drains more slowly.

If a fleet needs more, give it its own key(s): each active key adds its own bucket and one per-key
allowance to the org window, up to the plan org max; a per-key ceiling (`swarmfile api-key
rate-limit`) only limits that key's share. An owner/admin org override replaces the scaled window
(time-boxed with `--for 6h`).

## 5. Parking and switching

An agent's scope can move without losing queued or staged work:

- **Branch switch (hot).** `swarmfile branch switch <name>` moves the
  boot mount; `swarmfile mounts branch <id> <branch> [--wait]` moves one
  independent mount. Both refuse (exit 2) while a changelist is open.
  Creates queued before the switch land on the branch they were made under -
  the scope is captured when the create is enqueued, not when it drains.
- **Repository/org switch.** `swarmfile workspace switch --org <id>
  [--repository <id>]` moves the whole engine. A same-org switch usually takes
  a hot path; the fallback restarts the engine process (the OS supervisor
  relaunches it). Queued creates and their corrective renames/deletes stay
  in the repository captured at enqueue.
- **Park.** `swarmfile changelist park` sets staged work aside so a branch
  or repository can be left; `swarmfile changelist parked` lists it (age,
  files) and `swarmfile changelist resume` restores it. Parked work is a
  *set* per branch, and it's kept alive on the hub, so it survives the
  switch. `changelist discard --yes` abandons it.
- **Upstream refresh.** A branch is a fork: it does not see later work on
  `main`. There is no main→branch merge exposed - `swarmfile merge` and
  `mr` both go *into* the parent - so plan agent branches to be short-lived,
  or recreate the branch from current `main` when it needs the latest. A
  merge-down surface is a known gap.
- On a TTY, `workspace switch` prompts before abandoning staged/queued work
  and offers to park first; `--yes`/`--json` skip the prompt for scripts.

The tray mirrors all of this: the mount switcher lists every mount with its branch and per-row switch - and the tray menu's **Open Another Drive…** opens the same **Open a drive** dialog (its **Prevent another drive from editing a file this one has open** checkbox, under **Advanced**, is the same `--exclusive` opt-in), so a second mount is one menu click away - while a **Parked changes** panel lists, resumes (all at once or one at a time), and discards parked work.

The dialog puts the drive at the next free drive letter on Windows and in a folder next to your main drive on macOS and Linux, unless you choose otherwise under **Advanced**. If a mount can't open, the form says why straight away - for a drive letter that's taken it offers the next free one - and the failed mount never becomes the current one.

## 6. What to hand an agent (a copy-paste preamble)

```
You are working in a Swarmfile mount, not a git checkout.
- Workspace path: <mount path>          (writes sync automatically; there is no commit-required step)
- Tool caches:    run builds via `swarmfile run -- <cmd>` from the mount
- Status:         `swarmfile status` / `swarmfile --json status` (jq .pendingCreates)
- Exit codes:     0 success, 1 failure, 2 a refusal you should act on,
                  3 a long operation detached (`swarmfile op status` follows it)
- If an operation answers 409 with code "pending_create", the file is still
  syncing: wait a moment and retry. Do not delete and recreate it.
- Don't run two engines against the same cache dir or mount point.
- Session-scoped secrets are rendered into the session environment and are
  redacted from tool output; a value SHORTER THAN 4 CHARACTERS is not redacted
  (use a longer value for anything that must never appear in output).
```


## 7. One workspace per session (harness hooks)

The manual shape above works, but the harness can do it for you. One command
installs Swarmfile's hooks into the harness's own settings - repository-level by
default, so the whole team gets it in one committed file. Repository-scope hooks
call `swarmfile` from PATH and use the default cache, so every teammate needs
the CLI installed; `--user` pins the absolute binary and cache instead.

```bash
swarmfile hooks install claude-code          # .claude/settings.json + skill
swarmfile hooks install cursor               # .cursor/hooks.json + rule
swarmfile hooks install codex                # .codex/hooks.json + skill
swarmfile hooks install copilot              # .github/agents profile (no hooks)
swarmfile hooks install claude-code --user   # ~/.claude/settings.json
```

At `--user` scope, Cursor's hooks file is written but its rules are
UI-managed, so add the Swarmfile rule in Cursor Settings; repository-scope rules
are written automatically.

Cursor and Codex expose lifecycle hooks (Codex asks you to review/trust new
hooks via `/hooks`, and caps `SessionEnd` at 3 seconds; Cursor does not run
session hooks in its cloud agents). Copilot custom agents are prompt
profiles, not lifecycle hooks, so that adapter writes the agent profile only;
use `swarmfile hooks run -- copilot` for a mounted workspace.

Each session then behaves like this:

- **Session start** creates an ephemeral `agent/<label>-<6 hex>` branch and
  opens a mount for it, waits until the drive is attached, and gives the agent
  the workspace path as context. Nothing is cloned.
- **After every mutating tool call** (`PostToolUse` for Write, Edit,
  MultiEdit, NotebookEdit, Bash and PowerShell; Codex also `apply_patch`), the workspace's open changeset is
  committed as a checkpoint named after the step (`step 12: Bash`, or
  `step 13: Edit: src/cart.ts`). `Stop`
  is a turn-end backstop. On an `agent/*` branch the engine also checkpoints
  after 30 seconds of quiet (`SWARMFILE_AGENT_CHECKPOINT_IDLE_SECS`), so
  agents without hooks still get per-turn history.
- **Session end** waits briefly for in-flight saves, checkpoints, then closes
  the mount and archives the branch - its commits stay in history. With
  `--mr`, it opens a draft merge request instead and leaves the branch for
  review. **Codex is the exception:** its 3-second SessionEnd cannot run the
  archive, so it closes the mount and leaves the branch to the TTL sweeper;
  use `swarmfile hooks run --mr -- codex` for a draft MR.

The hooks call `swarmfile` from PATH; nothing else is added to the agent's
environment. The installer also writes the harness's instructions file
(`.claude/skills/...`, `.cursor/rules/...`, `.agents/skills/...` for Codex, or
the Copilot agent profile) if absent, with the command cheat-sheet:
checkpoint, `blame --lines`, restore, conflicts, the shared cache, and the
"never clone" rule. An edited skill is left alone. Re-running the install
replaces Swarmfile's own hooks and leaves any others in the file alone.

A hook cannot change the agent's working directory, so the safest launch is
the wrapper:

```bash
swarmfile hooks run -- claude
```

It mounts first, starts the command with its cwd **inside** the workspace,
and finishes the workspace when the command exits. It prints how long the
workspace took to become ready.

`swarmfile workspace warm -- <install or test command>` runs one dependency
warm-up through the same shared cache (the first workspace on a machine pays;
later ones reuse it). The `hooks run` wrapper exports the `.swarmfile/cache.yml`
redirects to the agent process, so its own installs/builds use the shared
cache too; the hook path (an agent launched without the wrapper) should use
`swarmfile run --` explicitly.

Add the global `--timings` to see elapsed and phase timings on stderr -
supported on `commit`, `checkpoint`, `changelist submit`, `mounts new/open`
(with `--wait`), `materialize` and the hook internals; `--json --timings` also
adds a `timings` object (`elapsedMs` plus named phases). `mounts new --wait`
blocks until the drive is attached instead of returning a `pending` mount. The installed hooks see
`SWARMFILE_AGENT_MANAGED=1` and stand down, so the two paths never double-mount.

If the engine is not running, FUSE is unavailable (a container), or the mount
is refused, the hook says so on stderr and exits 0; `SessionStart` waits up to
60 seconds for an attach, and `hooks run` exits 2 if it cannot mount at all. A crashed
session's workspace is covered by its TTL (7 days by default, `--ttl-days`
1-30) and by the normal workspace sweeper.

### MCP tools

The same workspace is available as Model Context Protocol tools with the
published `swarmfile-mcp` server (Node 20+; the engine and `swarmfile` CLI must
be running/on `PATH`, and the `search` tool also needs the standalone
`swarmfile-search` on `PATH`):

```bash
claude mcp add swarmfile -- npx -y swarmfile-mcp
```

Claude Desktop, Cursor, Codex and VS Code configs are in the
[`swarmfile-mcp` repository](https://swarmfile.com/public/swarmfile/swarmfile-mcp). The tools cover
workspaces, checkpoints, restore, blame/diff, conflicts, edit leases, agent
sessions and search. The default policy is safe for a prompt-injected agent:
`restore`, `conflicts_resolve`, `claim` and `finish_agent_session` need
`SWARMFILE_MCP_ALLOW_DANGEROUS=1`, and `SWARMFILE_MCP_READ_ONLY=1` exposes only
reads. `SWARMFILE_MCP_POLICY_ROOT` points `create_workspace` at a non-writable
base checkout, so an agent cannot rewrite the `.swarmfile/agents.yml` that
governs it.

The recorded two-agent run is on [the demo page](https://swarmfile.com/demo) (`oss-agents`);
the eight-agent harness is `scripts/demo/coding-agents.sh`. The npm listing is
the source of truth for the MCP package; the public project's source snapshot
refreshes with the next release.

### Rewinding an agent

Every checkpoint is a normal commit, so the existing restore works unchanged:

```bash
swarmfile steps                               # the agent's step timeline
swarmfile checkpoint -m "before the refactor" # close the current batch now
swarmfile log --limit 10                      # find the one you want
swarmfile restore --to 482 --path src/        # back to that state (a new commit)
```

The web History page has the same view behind **Steps only**.

`--to` is an alias for the positional ref. Restoring never rewrites history:
it creates a new commit that matches the old state, so the undo is itself
undoable. Checkpoints exist only on the workspace's own branch; a person's
`main` keeps the normal auto-commit cadence.

### Repository policy: `.swarmfile/agents.yml`

Commit a flat policy file to the repository so every agent session and the
GitHub Action use the same limits:

```yaml
max_concurrent: 20
branch_prefix: agents
ttl_days: 2
checkpoint_idle_secs: 30
conflict_mode: hard
image: node:24-bookworm
paths_deny:
  - secrets/**
merge_diff3: true
```

The GitHub Action (`swarmfile-agent-action`) reads `ttl_days`, `conflict_mode`, `image`, `branch_prefix`, `local_checks` (running its `local-check-command`), `upstream_push` (`never` or `manual`) and `upstream_ci` (`pr_only`, `on_push` or `none`; the caller's workflow mirrors that with `on: pull_request` / `on: push`). The engine reads `max_concurrent`, `checkpoint_idle_secs` and `paths_deny` on `mounts new`; the MCP server (`swarmfile-mcp`) reads `max_concurrent`, `ttl_days` and `conflict_mode` for `create_workspace`, and passes its operator-owned `SWARMFILE_MCP_POLICY_ROOT` to the engine.

`merge_diff3` is the engine merge fallback when `.swarmfile/merge.yml` is absent. An explicit action input still overrides the policy.

The action installs the Linux `.deb` from the hub's anonymous release assets by
default. A runner image may opt into its own Swarmfile toolchain with
`allow-preinstalled: true`; a preinstalled copy receives the repository key, so
enable it only on an image you control.

## 7.1 Branch- and path-scoped keys, and read-only delegations

A **branch-scoped** key is a repository API key bound to one non-default
branch. It keeps git, history and merge requests on that branch; a write to
another branch is refused. A **path-scoped** key is a branch-scoped key that
is also limited to a set of path globs (`src/**`, `docs/**`). It can list,
read and (unless it is a read-only delegation) write only inside those paths,
plus the branch's fork base where projected files live; anything outside is
refused, including a copied CID whose manifest is not in scope.

Mint one from the CLI:

```bash
swarmfile api-key create agent --branch-scope agent/x \
  --path-glob 'src/**' --path-glob 'docs/**' --deny-glob 'secrets/**'
```

or from the dashboard's API keys page / the tray's API keys panel. The API
is `POST /orgs/:orgId/api-keys` with `branchScope`, `pathGlobs` and
`denyGlobs` (the request body is published in the hub OpenAPI). The scope is
**set at mint time** - to change it, revoke the key and mint a new one. Each
list holds at most 64 globs of at most 1,024 characters; a blank branch or
glob is refused. Minting does not check that the branch exists; the hub
refuses a dead or default branch on first use, and the UI/CLI warn that the
branch must already exist and be non-default. A branch-only key may use git;
adding path globs makes it engine/API-only.

Two path-key limits are worth knowing:

- **No git, history or commit walk.** Path keys are engine/mount keys: no
  changesets, LFS, merge requests, branch history, commit messages or project
  jobs list. `swarmfile log`/history against one is refused.
- **New content must be verifiable.** A path key's upload is recorded only
  after the hub verifies it (ciphertext is decrypted and hashed); a
  presigned upload is declined and falls back to the Worker upload. On an
  E2E repository (client-only keys) a path key cannot introduce new content,
  and a manifest with more than 8,192 blocks is refused. In-scope edits of
  existing files and copies of in-scope content still work. E2E git with a
  scoped key is a documented non-goal for now - use an owner credential.
  On a community server scoped keys are not supported (hosted-only until P1).

A delegation can be minted **read-only** (`repositoryRole: "read"`); every
write through it is refused, so use it for an agent that only reviews. Agent
session secrets are redacted from tool output, but a value shorter than 4
characters is not - use a longer value.

## 8. Copy-paste install prompt

Paste the block below into a fresh session in Claude Code, Cursor, Codex, or
GitHub Copilot. It pins the CLI version this page documents (**0.3.17**): the
agent checks `swarmfile --version` first and stops if the installed CLI does
not match, rather than half-working against a different flag set. The prompt
installs that harness's hooks, keeps the generated instructions file, and
gives the agent the mounted-workspace commands.

```
# Swarmfile setup for this agent session

You are setting up Swarmfile for this coding-agent session. Work through the
steps in order, and report what you ran and what it printed. Do not install or
upgrade Swarmfile: this prompt assumes the CLI, engine, and repository are already
available.

1. Verify the pinned CLI.
   Run: swarmfile --version
   It must print: swarmfile 0.3.17
   If it prints a different version, stop and report the version. Do not
   install or upgrade anything.

2. Get onto a mounted workspace FIRST.
   This is not a clone or a checkout. If the directory you are in is already a
   Swarmfile mount, work there. If not, run:
     swarmfile mounts new --label <short-label> --wait
   It creates an `agent/<label>-<6 hex>` branch and waits until the drive is
   attached; cd into the mount path it reports. Do not open a second mount on
   the same directory.

3. Install this harness's hooks from inside that mount (or user-wide).
   Pick your harness:
   - Claude Code: claude-code
   - Cursor: cursor
   - Codex: codex
   - GitHub Copilot: copilot
   Recommended when the agent will create fresh agent/* workspaces: a
   user-wide install from anywhere:
     swarmfile hooks install <harness> --user
   (Copilot has no --user; use repository scope on the base branch instead.)
   Repository scope, run from the mount root:
     swarmfile hooks install <harness>
   It writes settings/instructions into the repository, but a later workspace
   inherits them only if they are committed on the branch it forks from. Do
   not install repository-scope hooks only on an ephemeral agent/* branch and
   expect the base branch to see them.
   Then run
     swarmfile hooks doctor <harness>
   (add --user if you installed there) and re-run the install only if it
   reports missing pieces. Keep the generated instructions file: Claude Code
   and Codex get a SKILL.md, Cursor a rule, Copilot an agent profile. Do not
   edit, move, or delete it. Codex asks you to review and trust new hooks with
   /hooks; Cursor does not run session hooks in its cloud agents.
   Harnesses load hooks at session start: restart the harness after installing
   (or use `swarmfile hooks run -- <command>` for this session).
   If you installed at repository scope, land the generated settings and
   instructions files on the branch the team uses (a checkpoint or
   `swarmfile commit`) so teammates and later workspaces see them.

4. Run commands in the workspace.
   To start a command in a fresh mounted workspace (including starting the
   harness itself), use:
     swarmfile hooks run -- <command>
   It mounts first, runs the command with its cwd inside the workspace, and
   checkpoints/finishes the workspace when the command exits. Inside an
   existing workspace, run installs and builds as:
     swarmfile run -- <command>
   so the repository's shared dependency cache is used.

5. Checkpoint after meaningful changes.
     swarmfile checkpoint --if-changed
   This is a no-op (exit 0, no output) when nothing changed. With hooks
   installed, mutating tool calls and turn end already checkpoint; an explicit
   checkpoint at a natural boundary is still fine.

6. Verify without writing to the hub.
     swarmfile --version                 # must be 0.3.17
     swarmfile hooks doctor <harness>    # hooks and instructions present
     swarmfile status --json             # mounted repository, branch, pending creates
     swarmfile checkpoint --if-changed   # silent no-op when nothing changed
   swarmfile restore --to <seq-or-changeset> is non-destructive (it creates a
   new commit that matches the old state), but it is still a write: on a
   read-only repository, do not run it and do not attempt edits; report the
   repository as read-only.

What this setup does NOT do:
- It does not install the Desktop App, the engine, or the CLI.
- It does not work without a mounted repository: there is no clone, and a session
  that cannot mount says so on stderr and continues in its original directory.
- It does not capture non-mutating calls: only mutating tool calls are
  checkpointed (Write, Edit, MultiEdit, NotebookEdit, Bash, PowerShell; Codex
  also apply_patch). Reads and other non-mutating calls are not.
```

The pin is deliberate: a prompt that assumes flags from a newer CLI is worse
than one that refuses to run. At repository scope the hooks call `swarmfile` from
PATH and use the default cache; `--user` pins the absolute binary and cache.
The Copilot adapter is a repository-scoped agent profile, not lifecycle
hooks, so `--user` is refused for it.

## 9. Agent spend attribution

Coding-agent sessions can report their token usage to the org's **Agent spend**
card without sending prompts or file contents. Collection is opt-in: an
an owner enables it in Settings → Usage; a member's engine then posts token
counts and model names (never transcript text) at most every five minutes.
Checkpointed sessions are split into **landed**, **exploration**, **in review**
and **unknown** cost by the hub's default-branch history and merged-MR chains;
unknown is never counted as exploration.

Scan a transcript locally, with no upload and no running engine:

```bash
swarmfile usage agents --local
swarmfile usage agents --local --session claude-abc123 --json
```

The local scan keeps the transcript path locally, discards each line's content
after reading its id/model/timestamp/token counts, and reports an unknown model
as `unpriced` rather than guessing a price. The org ledger is the default
(no `--local`) and needs a running engine; it reads only your own sessions as a
member, the org's as an owner/admin. See
[`swarmfile usage`](https://swarmfile.com/docs/cli/swarmfile#usage) for the flags and JSON shape.

Budgets are a reported circuit breaker for new workspaces, not an invoice: a
configured budget refuses work when the day's spend reaches it, and when a
model has no price it refuses with `agent_budget_unpriced` rather than counting
the unpriced tokens as zero. The price table is versioned and dated; treat the
total as an estimate.

## 10. Service-minted agent tokens

A **Starter+** hosted org can approve a service delegation for an `agent/`
workspace. An owner/admin - or a member with the repository root write (the
repository creator or a whole-repository grant), for themselves - creates it
for a service user (the account the delegation acts as), with an optional
path-glob scope and a token TTL ceiling
of at most one hour (900 seconds by default). The service user's PAT then
mints a token for an exact `agent/<label>-<6 hex>` branch:

```bash
curl -sS -X POST \
  -H "Authorization: Bearer $SERVICE_USER_PAT" \
  -H 'content-type: application/json' \
  -d '{"branch":"agent/hydrate-abc123","ttlSeconds":900}' \
  "https://hub.swarmfile.com/agents/v1/orgs/$ORG/agents/$AGENT/delegations/$DELEGATION/tokens"
```

The response's `key` (`sf_key_…`) is a branch-scoped key valid for the
requested TTL (15 minutes by default; the delegation's ceiling and the
platform's 1-hour cap both apply). It narrows rather than replaces the PAT:
path globs can only narrow it, and revoking the token, the delegation or the
PAT (lineage) ends it. In an SSO-enforced org the mint needs an owner or an
interactive session - a non-owner service user's PAT is refused by the same
policy as any PAT. Hosted only: the community server has no hosted
agent-delegation or service-minted agent-token surface. (Its short-lived TTL
member keys are a separate, narrower credential, not a delegation or an agent
token.)

A **glob-free** delegation's token can also call the branch archive in §11. A
path-scoped token is engine/API-only and the archive refuses it.

## 11. Hydrating without a mount: the branch archive

When a tool cannot mount a drive, the hub can stream the branch as one tar:

```bash
# a live branch; paths are relative to the branch root
curl -sS -H "Authorization: Bearer $TOKEN" \
  "https://hub.swarmfile.com/orgs/$ORG/repositories/$REPOSITORY/files/archive?branch=main" \
  -o main.tar

# sparse + gzip (paths is repeatable; prefix or glob, e.g. src/**/*.ts)
curl -sS -H "Authorization: Bearer $TOKEN" \
  "https://hub.swarmfile.com/orgs/$ORG/repositories/$REPOSITORY/files/archive?branch=main&paths=src&paths=README.md&format=tar.gz" \
  -o main.tar.gz

# the manifest primitive (JSON); If-None-Match with a prior ETag -> 304
curl -sS -H "Authorization: Bearer $TOKEN" \
  "https://hub.swarmfile.com/orgs/$ORG/repositories/$REPOSITORY/files/archive/manifest?branch=main&paths=src" \
  -o manifest.json

# a folder; paths are relative to that folder (v2 filters/format/ETag)
curl -sS -H "Authorization: Bearer $TOKEN" \
  "https://hub.swarmfile.com/orgs/$ORG/repositories/$REPOSITORY/files/$FOLDER_ENTRY_ID/archive" \
  -o folder.tar

# LFS-hydrated (pointer files remain the default)
curl -sS -H "Authorization: Bearer $TOKEN" \
  "https://hub.swarmfile.com/orgs/$ORG/repositories/$REPOSITORY/files/archive?branch=main&lfs=1" \
  -o main-lfs.tar
```

The token is a member credential, a branch-scoped repository key, or a
glob-free service-minted token. A path-scoped key is refused, and the folder
form is member-token only (service callers are refused). The branch must be
live; the archive is the caller's readable tree, not a repository-wide dump.

Limits: at most 5,000 **emitted** files, 480 walked directories and 1 GiB per
request on hosted (256 MiB on a self-hosted community server). The walk (and
the two route-level reads that precede it) scans at most 20,000 rows and 500
tree pages - those are scan limits, not an emitted file count, and hosted and
self-hosted share them. At most 64 `paths` values
of 1,024 characters each. On the community server archive starts are limited
to 30 per minute **per repository** (shared by all callers); a 429 carries
`Retry-After`. A cap or scan failure is a typed 413; an unsafe or
ustar-unrepresentable path is a 422 (`archive_unsafe_path` /
`archive_path_unrepresentable`); a malformed filter or unsupported format is a
400; E2E is 409; an unreadable **projected** leaf manifest is
`503 archive_content_unavailable` (a materialized row can still fail
mid-stream).

The branch response is `tar` by default; `format=tar.gz` is opt-in gzip (chunked, no `Content-Length`); zstd is not supported (`format=tar.zst` is a typed 400). A strong `ETag` is a generation hash (branch head/sequence, ACL/LFS generations, caller role/principals/mode and the selection); tar, gzip and manifest responses each have their own representation-specific ETag, so send the ETag from the response you are revalidating. A match returns 304 before the walk.

The manifest route returns the same filtered list plus `headSeq` (main included: it reads the live `repository_head_ref`), so a sandbox can keep its prior manifest, fetch only changed paths with `paths=`, and delete old paths absent from the new list. The manifest's `headSeq` - repeated as `X-Swarmfile-Archive-Seq` on both 200 and 304, so a cached manifest can refresh a stale base - is the branch sequence to pass to the batch checkpoint's `baseSeq`. There is no server-stored delta, resume or checksum.

Empty directories and zero-byte files are emitted; non-empty directories are implied by their members. Safe relative symlinks are emitted (absolute or root-escaping targets are a 422); a submodule/gitlink is an empty directory placeholder, not hydrated. An LFS pointer is archived as the pointer by default; `lfs=1` replaces it with the native content-map object (decrypted on managed tiers) or a standalone plaintext `lfs/<repository>/<oid>` object, and the hydrated size drives `Content-Length`/ETag. A missing or managed-encrypted standalone object is `503 archive_content_unavailable`; LFS object upload is not part of the archive.

Windows-hostile names such as `CON` or a trailing dot are allowed but a Windows extractor may reject them; traversal and absolute/drive/backslash/NUL paths are refused. Successful responses carry `X-Swarmfile-Archive-Branch`, `-Head`, `-Repository` and `-Format` (plus `ETag`). On the community server `-Head` can be a member's **provisional** claim rather than a confirmed commit hash; the `X-Swarmfile-Archive-Claim-Status` header says `confirmed`, `provisional` or `unknown`, and only `confirmed` is repository history. Hosted and self-hosted; both scan at most 20,000 rows, and a self-hosted community server cannot serve managed/E2E tiers.

## 12. Committing a sandbox's changes in one request

`POST /orgs/{org}/changesets/batch?branch=<branch>&machineId=<id>` stages and commits a
branch's side-effects as **one atomic Mode-B changeset**:

```bash
curl -sS -X POST   -H "Authorization: Bearer $TOKEN"   -H 'content-type: application/json'   -d '{
    "repositoryId": "<repository id>",
    "message": "run tests + format",
    "baseSeq": 42,
    "changes": [
      {"path": "src/app.ts", "rootCid": "...", "size": 1234},
      {"path": "docs/new.md", "rootCid": "...", "size": 88},
      {"path": "src/old.ts", "delete": true}
    ]
  }' \
  "https://hub.swarmfile.com/orgs/$ORG/changesets/batch?branch=agent/task-123"
```

- Content is **content-addressed**: upload blocks/manifests first (the engine
  chunker or your client), then name each `rootCid`/`size`. The hub does not
  apply a unified patch. On a **plaintext `agent/*` branch**, a small file may
  instead carry `contentBase64`: the hub chunks one block server-side (4 MiB/
  file, 16 MiB/batch), runs the same subscription, grace, community-email and
  storage gates as a block upload, and commits the real CID. The hub's inline
  form is refused on managed/E2E repositories. The sandbox sync client is
  stricter: it writes content only to plaintext repositories and refuses a
  managed/E2E create or update with `content_requires_plaintext` before any
  upload (deletes remain allowed).
- A large non-LFS file is uploaded as BLAKE3 blocks with a flat manifest, or a
  segmented v2 manifest once one block would overflow. On a **plaintext**
  repository the sandbox hydrates a changed file above
  `directReadThresholdBytes` (default 256 MiB; `--direct-read-threshold-bytes`
  / `SWARMFILE_SANDBOX_DIRECT_READ_THRESHOLD_BYTES`) by fetching its root,
  segment and chunk blocks directly and verifying every BLAKE3 CID, so there
  is no archive-size ceiling for plaintext files. On a **managed** repository
  the same threshold routes the file through the hub's `/content` range read
  (decrypted server-side), so existing managed files above the archive cap
  also hydrate read-only. Sandbox content writes to managed remain refused;
  use the engine for managed writes. **E2E** has no server-side read path:
  sandbox sync is unsupported at every size (the archive is `409` and the
  client reports `e2e_unsupported`), not merely above a 1 GiB cap. A
  path-scoped key cannot direct-hydrate a large file; use a branch-scoped key.
- An existing path is updated; a missing path is created (missing parent
  directories too); `delete` removes a file. Directory deletes and renames are
  not supported.
- One changeset, one head advance. `baseSeq` refuses a stale base with 409;
  `id` is the client idempotency key (a retry while open finishes it; a
  committed id returns 409 `changeset_not_open`). At most 500 changes.
- Use a member token, a branch-scoped service key, or a **path-scoped** key
  for content-addressed changes.

  A path-scoped key is admitted only when every
  change path is inside its globs and every `rootCid` is this key's upload, the
  entry's previous root, or an in-scope branch entry's root; inline
  `contentBase64` is refused for it. `?branch` is required.

  The response is `{changeset, entries, changes:[{path,entryId,action}]}`; errors are
  `path_scope_forbidden`, `path_scope_content_not_owned`,
  `path_scope_provenance_too_large`, `batch_base_mismatch`,
  `batch_path_not_found`, `batch_path_is_directory`, `batch_path_not_file`,
  `invalid_batch_change`, `batch_path_not_directory`, `batch_projection_changed`,
  `batch_path_conflict`, `batch_path_reserved`, `batch_path_forbidden`,
  `too_many_entries`,
  `inline_content_requires_plaintext`, `inline_content_requires_agent_branch`,
  `commit_mode_locked`, `locked`/`protected_branch`, `archive_overlay_unavailable`.
- A symlink change is `{path, linkTarget}` (create/retarget) or
  `{path, delete:true}`. `linkTarget` must be relative and non-escaping; it
  cannot be mixed with content. The archive emits symlinks. Directory
  rename/delete is not part of the batch (use the entry rename/delete API).
- **More than 500 changes:** create an async batch with
  `POST /changesets/batch/async` (first <=500 content-addressed changes;
  reuse `jobId`/`chunkId` on retries; the changeset id is server-generated), append <=500-change chunks at
  `/changesets/batch/async/:jobId/changes` (4,000 total), then
  `/seal`.

  Poll `GET /jobs/:jobId` or cancel with
  `POST /jobs/:jobId/cancel`. The job pins the branch/base and re-checks ACL,
  path scope and provenance at execution; inline content is refused.

  The SDK exposes `createBatchCheckpointAsync`, `appendBatchCheckpointAsync`,
  `sealBatchCheckpointAsync`, `getRepositoryJob` and `cancelRepositoryJob`.
  A collecting job not sealed within 24 hours fails.
- Hosted and self-hosted. The self-hosted server uses its flat key model (no
  path scopes or hosted agent-delegation/service-minted agent tokens; it does
  mint short-lived TTL member keys), and a member key's batch is a provisional
  claim rather than a confirmed-head advance. It rebuilds the whole live
  branch tree per commit, so the base is capped at 100,000 entries by default
  (`SWARMFILE_SERVER_MAX_BATCH_TREE_ENTRIES`, up to 10,000,000); an over-cap
  branch is `413 batch_tree_too_large`. Batch starts are limited to 60/minute
  per repository there. The sandbox flow is: hydrate with §11, run/tests,
  upload changed content, then this one request. The agent SDK exposes
  `batchCheckpoint` (including `dryRun`) and `planSandboxSync`.
