TangentSwarm checks out each branch of a Git repository into its own directory and opens a tmux session for it, with the programs and pane layout you configure.
The idea is to give each branch its own AI agent, such as Claude Code or OpenAI Codex.
- Clones repositories and checks out branches
- Opens a tmux session per branch with the same layout each time
- Manages branches across several repositories
- Runs the programs you configure in windows and panes
- Assigns each branch its own port
- Runs initialization commands for new repositories
- Substitutes the branch's port into commands
- Saves the configuration between runs
- Names each session port/branch
tangentswarm is a Python package (Python 3.10+, tmux required):
pip install . # or: pip install 'git+https://github.com/tangentstorm/tangentswarm'
pip install '.[cloud]' # optional: Claude Code cloud sessions (Playwright + websockets)
playwright install chromium # ...plus a browser for the cloud extraThis installs four commands:
swarm, the branch and tmux launcher described below, plus the agent tools ported from scialect (see Agents and the swarm state machine).swarm-mcp, an MCP server for tmux, agents and cloud sessions (see MCP server).swarm-hub, the message queue agents report to, andswarm-agent, the MCP server agents use to reach it (see swarm-agent).swarm-api, the Swarm status API for the control panel (see swarm-api).
# Simple usage with default repository
swarm <branch-name>
# Specify repository and branch
swarm <repo-name> <branch-name>
# View status of all branches
swarm -c statusTangentSwarm keeps its configuration in ~/.swarm.yaml in your home directory. The file holds the repositories, the port for each branch, the programs to run, initialization commands and environment variables. Because it lives in your home directory, the status command works from any directory.
Example configuration:
# Global swarm configuration
.swarm:
root: ~/projects # Root directory for all branch directories
git@github.com:username/repo:
branches:
main: 5000
feature1: 5010
feature2: 5020
# Branch with custom environment variables
custom-branch:
port: 5030
env:
APP: custom
DEBUG: 1
# Repository-level environment variables (applied to all branches)
env:
APP: default
NODE_ENV: development
programs:
- 'codex'
- '| npm run dev --port=${PORT}'
- '~ python api/server.py --port=${PORT+1}'
init:
- 'npm install'
- 'pip install -r requirements.txt'.swarmholds global options.rootis the directory where swarm creates the branch directories, such as~/projects.
branchesmaps each branch name to a port number or a dictionary.- The short form is
branch_name: port_number. - The long form adds environment variables:
branch_name: { port: port_number, env: { KEY: VALUE } }.
- The short form is
envsets repository-level environment variables for all programs and initialization commands.programslists the commands to run.- The first command always runs in the initial window.
- Each later command's sigil decides whether it gets a new window or a split.
initlists the commands to run when swarm sets up a new repository.
You can set environment variables for a repository and for a branch:
- Repository-level variables apply to all branches.
- A branch-level variable overrides a repository-level one with the same name.
- All commands in
programsandinitsee these variables.
Example:
git@github.com:username/repo:
branches:
# Simple branch with just a port
main: 5000
# Branch with custom environment
dev:
port: 5010
env:
APP: developer
DEBUG: 1
# Repository-level environment
env:
APP: default
NODE_ENV: development
programs:
- 'codex'
- '| APP=${APP} npm run dev --port=${PORT}'In this example:
- The
mainbranch getsAPP=defaultandNODE_ENV=development. - The
devbranch getsAPP=developer(overriding the repository value),DEBUG=1andNODE_ENV=development.
Each tmux session name has the port number and the branch name:
PORT/branch_name
For example:
5000/main5010/feature-branch
The main branch uses the repository name in place of main. The tmux session list then shows each branch's port.
Each command in the programs list can start with a sigil, a one-character prefix:
*creates a new window. This is the default when there is no sigil.|creates a horizontal split (side by side).~creates a vertical split (one above the other).@runs a tmux command against this session, such as@ next-window.!runs the command directly, outside tmux. Use it for one-off commands such as setting the status.
Examples:
programs:
- 'codex' # First pane of initial window
- '| vite --port=${PORT}' # Horizontal split (side by side)
- '~ python api/server.py --port=${PORT+1}' # Vertical split in the second pane
- '* npm test' # New window
- '@ next-window' # Run tmux command against session
- '! echo "Working on feature X" > .swarm-status' # Set status (runs directly)
- '! make build' # Run command outside of tmuxTo switch to the next window after setup, add @ next-window to the list.
Commands can use these variables:
${PORT}becomes the branch's port number.${PORT+n}becomes the branch's port plus n, where n is a digit from 0 to 9.
Example:
programs:
- 'codex'
- '| vite --port=${PORT}'
- '~ flask run --port=${PORT+1}'If the branch's port is 5000, this runs:
codexin the first panevite --port=5000in a horizontal splitflask run --port=5001in a vertical split of the second pane
- TangentSwarm checks whether the branch is in the configuration file.
- If it is not, swarm assigns it a new port and adds it to the configuration.
- It creates the branch's worktree
<root>/<repo>.<branch>if there is none, cloning the plain checkout<root>/<repo>first if it is missing (see One worktree per agent). - It fast-forwards the plain checkout and checks out the branch in the worktree.
- For a new repository, it runs the initialization commands, and asks whether to continue if one fails.
- It creates a tmux session with the layout the sigils describe.
- It starts the configured programs, with the port variables filled in.
- It attaches to the tmux session.
When the commands have no sigils, TangentSwarm creates a new window for each one:
- The initial pane runs the first command (
codexby default). - Window 1 runs the second command.
- Window 2 runs the third command.
The status command lists your branches and their sessions:
swarm -c statusIt works as an interactive session picker:
- It lists inactive repositories and branches, which have no local directory.
- It lists active branches that have a directory but no tmux session.
- It numbers every tmux session, including ones swarm did not create.
- You press a session's number to switch to it.
Each session shows its full name, which includes the port for sessions swarm created, and the text of its .swarm-status file if there is one.
Put a .swarm-status file with one line of text in the root of a branch directory:
Working on feature X
swarm -c status shows that line next to the branch, so you can note what you are working on in each branch.
- Each repository in the config file can have its own programs and layout.
- Put setup steps such as
npm installininit. - Use port variables so each branch's services listen on that branch's ports.
- Inside tmux, TangentSwarm switches to the new session instead of nesting one.
tmux lslists all running sessions with their port numbers.set -g status-left-length 50gives the session name more room in the status bar.- Add
bind s choose-tree -s -O nameto your~/.tmux.confto sort sessions by name when you press<prefix> s. Swarm names start with the port, so this sorts them by port. - To use swarm's status command as the tmux session chooser, add this to your
~/.tmux.conf:Use the full path tobind-key s run-shell "tmux split-window -p 70 'swarm -c status'"swarmif tmux can't find it. The config is in~/.swarm.yaml, so this works from any directory. - To put a session at the top of the sorted list, rename it with
<prefix> : rename-session *important-session.*sorts before digits. Most other characters that sort before digits are not allowed in tmux session names.
- Python 3.10+
- tmux
- Git
- PyYAML,
mcp(>=2.3), PyJWT, uvicorn (installed by pip) - For the optional
[cloud]extra, Playwright (plusplaywright install chromium) and websockets
tangentswarm/
cli.py swarm CLI + subcommand dispatch
tmux.py tmux wrappers (argv lists only; structured list_sessions/list_panes)
git.py git helpers
worktrees.py one worktree per agent: layout, sync, .swarm.yaml, spawn/list/remove
mcp_server.py swarm-mcp (stdio, or Streamable HTTP with OAuth or an API key)
agent_mcp_server.py swarm-agent: agents' message tools (stdio, or one shared HTTP server)
agent_report.py report_status: agent done / needs-input / blocked reports and the swarm's actions
http_app.py Streamable HTTP app + auth wiring shared by swarm-mcp and swarm-agent
queue/ swarm-hub: SQLite message queue, its HTTP server and client
auth.py OAuth resource server + optional built-in authorization server
auth_cli.py swarm auth ...
agents.py agent detection, prompt-empty detection, space probe, tell/wait
workers.py workers.jsonl / known-agents.jsonl
local_status.py swarm status table (scialect local-status)
tell_worker.py state-machine handoffs (scialect tell-worker)
local_step.py propose/run next handoff (scialect local-step)
for_all.py run a command in every worker dir (scialect for-all)
rule_deps.py `uses:` closure of prompt guides (scialect rule-deps)
swarm_state.py swarm-status deltas (scialect swarm.mts)
methlab.py Meth Lab: fake GitHub, delivery replay, live sandbox guard
cloud/ Claude Code cloud sessions (scialect browser/sessions/server/client/...)
These commands are Python ports of scialect's
agent tools. Like scialect, they run in a control directory, which is the current
directory. It holds workers.jsonl (one {"id","dir","session","window"} per line), an
optional known-agents.jsonl (the built-in defaults are claude, codex, gemini/agy and
opencode), and a git-tracked rules/ directory of prompt guides.
swarm -c local-status # id | agent | state | health | status
swarm -c tell-worker jc3 accept # assigned|accept|plan-approved|adjust|unblocked|reject|rebase [branch]
swarm -c tell-worker mgr review jc3 # review|approve-task|unblock <worker>
swarm -c step # propose the next transition, confirm, run it
swarm -c for-all 'git status -s'
swarm -c agent-status agents:1 # which agent, is its prompt blank?
swarm -c tell-agent agents:1 'please run the tests'Sending to an agent always follows scialect's tell-worker sequence.
- Reach an empty prompt with the space probe. It types a space, checks the prompt and deletes the space. This sees past placeholder text but refuses when someone is typing.
- Optionally send
/new, submit it as in step 3 and wait 10s. - Type the text literally (long text goes in 2048-character
send-keyspieces, a CR becomes a newline so it can't submit part-way, and leading blank lines are dropped). Wait at least 0.5s, and until the text shows in the input box and stops changing, then press Enter in a separatesend-keys: TUIs drop an Enter that arrives with the text. - Check that the text left the input box. Under load the Enter can still be lost, so
while the text is still sitting there, press Enter again (checking after 0.5s, 1s, 2s
and 4s). Grey ghost text (Claude Code's suggested prompt, Muse's placeholder) does
not count as input. Enter is never pressed into anything but our own unsent text, so
a dialog that opens mid-send can't have an option picked. If the text never showed
up, is still there after the retries, or the box never comes back blank, the send
fails with the screen's last lines (
SubmitError; MCP and the CLI report it).
Handoffs are atomic. Swarm writes the worker state (.sci/status-line and the guides)
only after it delivers the message.
swarm cloud and swarm auth are reserved words. The other new commands live behind
-c, so swarm [<repo>] <branch> keeps its old meaning.
Agents never share a working tree, and no agent ever starts in the plain checkout.
swarm -c start-agent, the start_agent MCP tool and swarm <repo> <branch> all go
through tangentswarm/worktrees.py, so they behave the same.
~/ver/platform plain checkout: always on the default branch, kept current
~/ver/platform.minavo-auth-fix worktree for branch minavo/auth-fix
~/ver/platform.render-freeze worktree for branch render-freeze
-
Layout. The top directory is
$TANGENTSWARM_AGENT_ROOT(default~/ver), or.swarm.rootforswarm <repo> <branch>. A worktree lives at<top>/<repo>.<slug>, where the slug is the branch name with every/turned into-. Branch names may only use[A-Za-z0-9._/-], so the slug is one safe path component.a/banda-bshare a slug. If the directory already holds the other branch, the spawn is refused. -
The plain checkout stays on the default branch. Every spawn runs
git fetch originand fast-forwards<repo>toorigin/<default>(fromorigin/HEAD). It refuses loudly if<repo>is on another branch, has uncommitted or untracked files, or has diverged. -
Branches. The worktree checks out the local branch if there is one, else tracks
origin/<branch>if that exists, else creates a new branch (no upstream) from the up-to-date default branch. The default branch itself is refused. -
Retrying is safe. An existing worktree for the branch is reused. If a live agent of the same kind is already in it,
start_agentreturns that pane (reused: true, withtrust.status: reusedand its current trust state) instead of starting another. A different agent there is refused. Operations on one repo are serialised by a lock file in its git dir. -
Removal.
remove_worktreerefuses if a tmux pane or any process has its cwd in the worktree, or if the worktree has uncommitted or untracked changes. There is no force option.delete_branchdeletes the branch only if it is merged intoorigin/<default>. The plain checkout is never removed. -
Pre-trusted, then watched. Before the agent starts, its worktree is marked trusted so no "do you trust this folder?" screen stalls it (see below). After the launch,
start_agentwatches the pane for a few seconds and reportsstartup.state:ready,starting,exitedorblocked, withstartup.blocked.kindnaming the screen.
swarm -c start-agent claude platform minavo/auth-fix [--session agents] [--window NAME]
swarm -c worktrees [platform] [--json] # repos, worktrees, dirty?, panes working in each
swarm -c remove-worktree platform minavo/auth-fix [--delete-branch]tangentswarm/trust.py records trust for the worktree's real path before the agent
starts. The start_agent result's trust says what it did (trusted,
already_trusted, skipped with a warning, or unsupported). A failure never blocks
the launch.
| agent | how | where |
|---|---|---|
claude |
projects[<worktree>].hasTrustDialogAccepted = true |
$CLAUDE_CONFIG_DIR/.claude.json, else ~/.claude.json |
codex |
[projects."<worktree>"] trust_level = "trusted" |
$CODEX_HOME/config.toml, else ~/.codex/config.toml |
muse |
--trust-workspace flag |
|
grok |
--trust flag (trusts the main repo root; trust.scope: repo) |
$GROK_HOME/trusted_folders.toml, else ~/.grok/trusted_folders.toml |
gemini |
not pre-trusted (screens are still detected) |
Grok (checked against 1.0.62) asks only when the repo has something trust gates, such as
project hooks, and keys trust by the main repo root. It ignores an entry for the
worktree path, so there is no way to trust just the worktree; --trust trusts the
repo, its plain checkout and all its worktrees.
Claude Code (checked against 2.1.302) has no flag or env var that trusts a folder for an
interactive session. For a linked worktree it accepts trust recorded for the main repo
root (the key it writes when you accept the dialog there) or for any directory from the
cwd up to the worktree root. It never looks above the git root, so trusting ~/ver does
not cover ~/ver/<repo>.<branch>. swarm trusts only the worktree, not the plain
checkout. Claude rewrites its config itself, so the update takes the same lock Claude
uses (a <config>.lock directory, refreshed every 5s while held and stale after 10s; a lock taken over meanwhile means no write), re-reads the file, sets only that
key, and replaces the file atomically (temp file in the same directory, same mode, fsync,
os.replace). A file that is missing, unparsable or the wrong shape is never written.
For Codex, an existing entry for the path (for example an explicit "untrusted") is left
alone. The config written is the one for swarm's own HOME (or CLAUDE_CONFIG_DIR /
CODEX_HOME), while the agent inherits the tmux server's environment. If those differ,
the agent still asks, and trust.warning says so.
Any remaining first-run or blocking screen is reported by name as blocked: {kind, lines, hint} in start_agent (under startup), agent_status, pane_ready and
wait_for_idle. tell_agent refuses with "agent is on the screen" before typing
anything, even with require_empty_prompt=false, because typed text would answer the
dialog. The kinds are trust_prompt, theme_picker, login, api_key_prompt,
bypass_permissions_confirm and update_prompt. The screen text comes from captures of
Claude Code 2.1.302 and Codex 0.157.0 in tests/fixtures.
A repo can commit a .swarm.yaml at its root, read from the plain checkout on the
default branch. It lists paths to share with every worktree, so each one does not need
its own node_modules or a Lean/mathlib download of several GB.
worktree:
symlink: # linked from the plain checkout into each worktree
- node_modules
- auth/node_modules
- .lake/packages # Lean: mathlib and other dependencies (not .lake/build)
copy: # copied once; an existing file is never overwritten
- .claude/settings.local.json- Nothing in the file is ever run. There is no hook or command key, and unknown keys are an error.
- Paths are relative to the repo root and use only
[A-Za-z0-9._@+-]and/. They may not contain..or touch.git. A source that resolves outside the repo is skipped, and so is one that is missing (for example before the firstnpm ci). A spawn retry fills in links that were skipped before. - A destination that already exists in the worktree, such as a tracked file, is left
alone and reported under
skipped. - The listed paths go into a managed block in the repo's shared
.git/info/exclude. Anode_modules/gitignore rule does not match a symlink, so without this every worktree would look dirty. - Symlinked directories are shared. Two agents running
npm installat the same time write into the samenode_modules.
Requires pip install 'tangentswarm[cloud]' and playwright install chromium.
swarm cloud login # headed browser at claude.ai/code -- sign in by hand once
swarm cloud serve # browser + websocket hub on ws://127.0.0.1:5002/ws
swarm cloud client # REPL: /list /use <name> /status [name] /latest /help /quit
swarm cloud list | status "<name>" | open "<name>" | wait # one-shot browser
swarm cloud serve --port 5003 & swarm cloud orchestrator # scialect's split setup:
# thin :5002 hub polls the swarm, pushes swarm-status, relays to :5003The login cookie lives in a persistent Chromium profile outside the repo, at
~/.local/share/tangentswarm/playwright-profile. TANGENTSWARM_PROFILE_DIR or
--profile-dir overrides the path. TANGENTSWARM_STORAGE_STATE can point at a
Playwright storage-state JSON file, also outside the repo, whose cookies the browser
loads at launch. The first login needs a display. Run swarm cloud login on a desktop
or over ssh -X, and copy the profile directory if needed. After that, --headless
works. Stop the server with Ctrl-C, not SIGKILL, so Chromium writes the cookie to disk.
The websocket protocol is the same as scialect's. Each frame is JSON, a reply carries
its request's id, and pushed events have kind: "event". See scialect's
docs/websocket-agent.md. The hub binds 127.0.0.1 and has no authentication, so never
expose port 5002 or 5003.
swarm-mcp speaks MCP over stdio (the default) or Streamable HTTP (--http).
| tool | scope (HTTP) | what it does |
|---|---|---|
list_sessions |
read | tmux sessions: name, id, windows, attached, created |
list_panes(target?, all?) |
read | panes: session, window index/name, pane index/id, active, command, path, size |
capture_pane(target, history_lines?, escapes?) |
read | raw pane text (-S -N scrollback, -e escapes); diagnostic, not evidence of typed input |
send_keys(target, text, enter=true, literal=true, allow_ctrl_b=false) |
shell | agent panes only: literal text, 0.5s, separate Enter; literal=false for key names; the tmux prefix and a lone C-b are refused (see below) |
tmux_action(target, action, arg?) |
shell | named tmux command on an agent's own pane or window: show_window, select_pane, zoom, unzoom, rename_window, move_window, set_pane_title (see below) |
list_agents |
read | the registered agents: installed?, binary, exact argv, adapter level; the agent root |
start_agent(agent, repo, branch, session="agents", window_name?) |
shell | start a registered agent (enum) in its own pre-trusted worktree <root>/<repo>.<branch> (see One worktree per agent); reports trust and startup (any blocking screen) |
list_worktrees(repo?) |
read | repos under the agent root and their worktrees: branch, dirty, on-layout, panes working in each |
remove_worktree(repo, branch, delete_branch=false) |
shell | remove a clean, unused worktree; delete the branch only if merged |
agent_status(target) |
read | registered agent in the pane's foreground, typeable?, blocked (named screen)?, prompt blank?, prompt (typed input vs ghost suggestion), last lines |
pane_ready(target, probe=false) |
read (probe: shell) | is the agent's prompt empty; blocked names a first-run screen (never probed) |
wait_for_idle(target, timeout_sec=120, poll_ms, settle_sec) |
read | screen stable + prompt blank |
tell_agent(target, text, new_conversation?, require_empty_prompt=true) |
shell | agent panes only: tell-worker send sequence; refuses on a blocking screen |
swarm_status(control_dir) |
read | local-status rows |
tell_worker(control_dir, worker, verb, arg?) |
shell | state-machine handoff (agent panes only) |
cloud_list_sessions |
read | claude.ai/code sidebar sessions (needs swarm cloud serve) |
cloud_send_message(session_id, text) |
shell | send to a cloud session |
cloud_get_latest_response(session_id) |
read | last transcript message |
cloud_wait_for_response(session_id, text?, timeout_sec=120, poll_ms=1500) |
shell | send, then poll until settled (max 600s) |
There are no kill-pane, kill-window or kill-session tools, and no tool that runs an
arbitrary command. shell_exec and the free command argument of new_session and
new_window are gone. You start agents with start_agent and drive them through their
panes with tell_agent and send_keys. stdout carries only MCP protocol traffic, and
logs go to stderr.
tangentswarm/registry.py holds a fixed allowlist. Nothing else can be launched, and
the caller cannot add arguments.
| agent | binary (first that exists) | fixed flags | adapter |
|---|---|---|---|
claude |
~/.npm-global/bin/claude, ~/workspace/.npm-global/bin/claude, ... |
full (❯ box between ─ bars; dim suggestions ignored) | |
muse |
~/.local/bin/muse (launcher; execs muse-bin-<version>) |
--trust-workspace |
full (❯ box between ─ bars; grey placeholder ignored; /new) |
codex |
~/.npm-global/bin/codex, ... |
basic (› prompt, ported from scialect) | |
gemini |
~/.npm-global/bin/gemini, /usr/local/bin/gemini, ... |
basic (> prompt, ported from scialect) | |
grok |
~/.grok/bin/grok |
--trust |
basic (❯ line inside a rounded │ … │ box) |
list_agents still lists an agent that is not installed, with installed: false, and
starting it fails with "not installed". The operator can point an agent at another binary
with TANGENTSWARM_AGENT_<NAME>=/abs/path.
-
start_agentopens the window as a persistent/bin/bash -lin the worktree, waits for an idle prompt there, then types one fixed launch line into it withsend-keys -land a separate Enter: the shlex-quoted[binary, *flags](flag-less agents through/usr/bin/env --) wrapped in its ownsystemd-run --user --scopeunit inswarm-workers.slice. Nothing from the caller is in that line. When the agent exits, the shell and directory survive, with the launch line in history. A laterstart_agentfinds the window by session and name (wherever its shell is, whatever it runs). It reuses the shell only if the input buffer is positively empty: bash in the foreground, in the same worktree, and the cursor line is exactly the prompt that start_agent recorded for that shell (or exactly$or#), with the cursor at its end, and nothing below it. The launcher reads the whole logical line at the cursor, so a prompt wider than the pane still counts, but the wrapped end of earlier input does not. It does not use the history size as a scroll counter, so a fullhistory-limitdoes not matter. Anything else is refused and never typed into, and no second window is made. Enter is pressed only after the typed line reads back exactly after the prompt. The typing tools below still refuse the bare shell.repomust resolve, after symlinks, to a git main worktree directly inside$TANGENTSWARM_AGENT_ROOT(default~/ver). The agent runs in that repo's worktree forbranch, never in the repo itself.sessionmust match[A-Za-z0-9_-]{1,40}, and swarm creates it if it is missing.window_nameis kebab-case, with a default of<agent>-<branch>. -
send_keys,tell_agent,pane_ready(probe=true)andtell_workerresolve the target to the exact pane withdisplay-message -t, which is the pane send-keys would hit. They list the processes on its tty and go ahead only if a process in the terminal's foreground process group (+in thepsstat) is a registered agent. They refuse a bash prompt, a dead pane, or a shell whose agent was suspended with C-z. They then send keys to that pane id. -
Clients never press tmux's prefix.
send_keyswrites straight to the pane, so tmux's key bindings never fire and a prefix key would only reach the agent as a stray control character.send_keysrefuses the prefix keys in effect for the target's session (prefixandprefix2: the session's own setting, else the global one), both as key names and as the raw control character they type (0x12 for C-r, even in literal text), and points the caller totmux_action. -
tmux_action(target, action, arg)runs one command from a fixed table against the agent's own pane, window or session. It resolvestargetto the exact pane and needs a registered agent there, like the typing tools. It then uses ids (%pane, and$session:@windowfor window commands), so renaming a session or window can't redirect the command. The session comes from the caller's target, so for a window linked into several sessions,other:sharedacts inother. A bare%panetarget leaves the session choice to tmux:action arg tmux command show_windowselect-windowon the agent's windowselect_paneselect-paneon the agent's panezoom/unzoomresize-pane -Z, only when the zoom state needs to changerename_windowkebab-case name, max 40 rename-windowmove_windowindex 0–9999 move-windowwithin the agent's session; a taken index gets-b(insert there, later windows move up)set_pane_title1–64 printable characters select-pane -T. Agents such as Claude Code may retitle their own pane later (tmux'sallow-set-title)There are no kill, respawn, run-shell, split, new-window, source-file, set-option or detach actions.
-
The
ctrl+b ctrl+b to run in backgroundhint on Claude Code's screen is a Claude Code shortcut, not tmux. Agents that copy it off the screen would background the target's running command, sosend_keysrefuses C-b (as a key name, or a raw 0x02 byte) unlessallow_ctrl_b=true. -
Agent recognition looks at the process's comm, its argv[0] and, for node, bun and deno, the script name. It never looks at the rest of the command line, because prompts often mention other agents.
-
Prompt detection uses an escape-coded capture. Text drawn dim or in grey (Claude's prompt suggestions, Muse's placeholder) counts as an empty prompt, and text in the normal colour counts as real input.
-
Screen text is not prompt state. Plain text (
capture_pane,last_lines) loses the styling, so Claude's dim autocomplete suggestion after an empty❯looks like typed input. For claude and muse,agent_status.promptseparatesinputfromsuggestion(the trailing dim/grey run of an input line).inputdrops only Claude's padding (the separator after❯, the continuation indent) and keeps typed spaces and line breaks; tmux trims blanks at a line end. A dim run next to a dim prompt glyph or box character stays ininput, becauseinput_viewkeeps those glyphs and the prompt is then not blank.last_lineswraps that run as[ghost suggestion, not typed: ...]. Nothing outside the input box is relabelled or erased, and text in unfamiliar styles counts as input.tell_agentstill refuses to type over real input.
The guard does not stop the agents themselves from running commands. You can use
Claude's ! bash mode or ask an agent to run something, and send_keys can answer
approval prompts. So a key that can talk to agents can still run commands as the
server's user. It cannot type into a shell or launch an arbitrary program directly.
Give the server its own SSH key with a forced command in the target user's
~/.ssh/authorized_keys:
command="/home/swarm/.venvs/tangentswarm/bin/swarm-mcp",no-port-forwarding,no-X11-forwarding,no-agent-forwarding,no-pty ssh-ed25519 AAAA... swarm-mcp-client
Then point the MCP client at ssh:
{
"mcpServers": {
"tangentswarm": {
"command": "ssh",
"args": ["-i", "~/.ssh/swarm_mcp", "-o", "IdentitiesOnly=yes", "-T",
"swarm@host.example", "swarm-mcp"]
}
}
}The forced command runs whatever the trailing swarm-mcp argument says.
swarm-mcp --http --host 127.0.0.1 --port 8765 # endpoint: http://127.0.0.1:8765/mcpThe server is an OAuth 2.0 resource server built on the MCP SDK's auth support.
GET /.well-known/oauth-protected-resource/mcpreturns the Protected Resource Metadata (RFC 9728), which names the authorization server.- A request without a valid bearer token gets
401withWWW-Authenticate: Bearer ... resource_metadata="...". A token withouttangentswarm:readgets403 insufficient_scope. - Every request needs
tangentswarm:read. Tools that type into panes or start agents also needtangentswarm:shell(see the table).
There are two authorization-server modes, set by TANGENTSWARM_AUTH_MODE (default builtin).
External mode. An outside OAuth or OIDC issuer signs the tokens. The server checks a
JWT access token against the issuer's JWKS, which it finds through
/.well-known/openid-configuration or /.well-known/oauth-authorization-server unless
jwks_url is set. It checks the signature, iss and exp. The aud claim, or a
resource claim, must equal this server's resource URL or audience. Scopes come from
scope or scp. For opaque tokens the server falls back to RFC 7662 introspection when
introspection_url is set. It also accepts tokens from swarm auth token issue
(accept_local_tokens).
Builtin mode. A small authorization server runs in the same process (the SDK's
OAuthAuthorizationServerProvider) and keeps its state in
~/.local/state/tangentswarm/auth.db (mode 0600). It supports:
- Authorization code with PKCE and dynamic client registration (
/register,/authorize,/token,/revoke,/.well-known/oauth-authorization-server) for interactive MCP clients. The authorize step shows/login, where you approve with the admin password (swarm auth set-password, stored as a scrypt hash inadmin.json, mode 0600) or a one-time code fromswarm auth approve. client_credentialsfor confidential clients fromswarm auth client add. The CLI shows the secret once and stores a hash.- Pre-issued bearer tokens from
swarm auth token issue, managed withswarm auth token listandswarm auth token revoke. - Refresh-token rotation and RFC 7009 revocation.
The config keys live in ~/.config/tangentswarm/mcp-auth.yaml. Environment variables
override the file, and CLI flags override both.
| key | env | default |
|---|---|---|
mode |
TANGENTSWARM_AUTH_MODE |
builtin |
resource_url |
TANGENTSWARM_AUTH_RESOURCE_URL / --public-url |
http://<host>:<port>/mcp |
issuer_url |
TANGENTSWARM_AUTH_ISSUER / --issuer |
builtin: origin of resource_url |
audience |
TANGENTSWARM_AUTH_AUDIENCE / --audience |
resource_url |
jwks_url, jwks_file |
TANGENTSWARM_AUTH_JWKS_URL, ..._JWKS_FILE |
discovered |
required_scopes |
TANGENTSWARM_AUTH_REQUIRED_SCOPES |
tangentswarm:read |
introspection_url |
TANGENTSWARM_AUTH_INTROSPECTION_URL |
unset |
introspection_client_id / _secret |
..._INTROSPECTION_CLIENT_ID / ..._CLIENT_SECRET (or ..._CLIENT_SECRET_FILE) |
unset |
accept_local_tokens |
TANGENTSWARM_AUTH_ACCEPT_LOCAL_TOKENS |
true |
access_token_ttl, refresh_token_ttl |
none | 3600, 30 days |
No secrets go into the repo. The server stores tokens, client secrets and approval codes
only as SHA-256 hashes, and the admin password as a scrypt hash, all in 0600 files under
~/.local/state/tangentswarm.
The HTTP endpoint listens on loopback, optionally behind a TLS reverse proxy. From
another machine, open a tunnel first with ssh -N -L 8765:127.0.0.1:8765 user@host.
(a) Pre-issued token. On the server, run swarm auth token issue --client my-client --scopes tangentswarm:read tangentswarm:shell --ttl 30d. Then:
TOKEN=tsw_... # shown once
curl -sS http://127.0.0.1:8765/mcp -H "Authorization: Bearer $TOKEN" \
-H 'Content-Type: application/json' -H 'Accept: application/json, text/event-stream' \
-d '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{"name":"my-client","version":"1"}}}' -D -
# reuse the Mcp-Session-Id response header on later requests, send notifications/initialized,
# then tools/list and tools/call(b) client_credentials. On the server, run swarm auth client add --name my-client --scopes tangentswarm:read tangentswarm:shell, which prints the client_id and secret once. Then:
curl -sS -u "$CLIENT_ID:$CLIENT_SECRET" -d grant_type=client_credentials \
http://127.0.0.1:8765/token # -> {"access_token": "...", "expires_in": 3600, ...}Use the access token as in (a), and fetch a new one when it expires.
(c) Interactive clients (authorization code with PKCE). Point the client at
http://127.0.0.1:8765/mcp. It reads the metadata, registers itself and opens /login,
where you enter the admin password or a swarm auth approve code. The device-code flow
is not implemented, so use (a) or (b) for headless clients.
The MCP SDK client for Python works with a static token:
import asyncio, os
from mcp import ClientSession
from mcp.client.streamable_http import create_mcp_http_client, streamable_http_client
async def main():
url, token = os.environ["SWARM_MCP_URL"], os.environ["SWARM_MCP_TOKEN"]
async with create_mcp_http_client(headers={"Authorization": f"Bearer {token}"}) as http:
async with streamable_http_client(url, http_client=http) as (read, write):
async with ClientSession(read, write) as session:
await session.initialize()
print(await session.call_tool("list_sessions", {}))
asyncio.run(main())For a single trusted client, --auth-mode apikey replaces OAuth with one random key.
swarm-mcp --gen-api-key # writes ~/.config/tangentswarm/api_key (0600), prints only a fingerprint
swarm-mcp --http --auth-mode apikey --host 127.0.0.1 --port 8766 \
--public-url https://host.example/swarm-mcp/mcp- Every request must send
Authorization: Bearer <key>orX-API-Key: <key>. Any other request, on any path, gets401from an ASGI middleware around the whole app, before any MCP handling. The comparison takes constant time (ApiKeyMiddlewareintangentswarm/apikey.py). - The server reads the key from the first of these that is set:
--api-key-file,$TANGENTSWARM_API_KEY,$TANGENTSWARM_API_KEY_FILE,~/.config/tangentswarm/api_key. Key files must be mode 0600. Setting a key selects apikey mode unless--auth-modeorTANGENTSWARM_AUTH_MODEsays otherwise. In apikey mode the server refuses to start without a key, or with a key shorter than 32 characters. - A valid key grants every scope, including typing into agent panes with
send_keysandtell_agentand starting registered agents. Treat it like an SSH private key. To rotate it, delete the file, run--gen-api-keyagain and restart. - This mode serves no OAuth routes (
/register,/token,/loginor metadata). - Behind a reverse proxy,
--public-urlmust name the public URL, so the DNS-rebinding Host check accepts the proxied Host header.
Run it under systemd or any process manager. Behind nginx, proxy a location to the
loopback port with proxy_http_version 1.1, proxy_buffering off and a long
proxy_read_timeout, because responses stream over SSE.
By default the server listens only on loopback. To expose it:
- Put it behind TLS, with an nginx or Caddy vhost that proxies
https://swarm.example.com/tohttp://127.0.0.1:8765/. Keep--host 127.0.0.1. - Start it with the public resource URL, so the metadata, audience checks and
DNS-rebinding protection use the public host:
swarm-mcp --http --host 127.0.0.1 --port 8765 --public-url https://swarm.example.com/mcpTheissuer_urlmust use https. In builtin mode it defaults tohttps://swarm.example.com. - Set an admin password with
swarm auth set-password, or switch to an external issuer. - Give clients that don't need to type into panes only
tangentswarm:read.
swarm-mcp controls agents. swarm-agent lets them talk back: it puts status, blocker,
question and done messages on the swarm-hub queue, and lets an agent read messages
addressed to it. It has no tmux, filesystem or shell tools.
Run it once, as a shared Streamable HTTP server that every agent (local, cloud, other machines) connects to:
swarm-hub # queue on http://127.0.0.1:8777 (no auth: loopback only)
swarm-agent --gen-api-key # ~/.config/tangentswarm/agent_api_key (0600)
swarm-agent --http --host 127.0.0.1 --port 8768 --path /mcp/agent \
--public-url https://swarm.example.com/mcp/agentswarm-agent with no --http still serves stdio, one process per agent.
| tool | what it does |
|---|---|
register_agent(name) |
binds this MCP session to an agent name |
whoami() |
the bound name and the credential it authenticated with |
send_message(recipient, type, body, context?) |
posts to the hub, signed with the bound name |
read_messages(since?, limit?) |
new messages addressed to you; moves your read cursor |
report_status(state, pr, window, message?, question?) |
tells the swarm you are done, need input, are blocked or are working; the swarm acts on it (below) |
One server serves many agents, so each MCP session (Mcp-Session-Id) is bound to an
agent name, taken from the first of: register_agent(name), an X-Swarm-Agent: <name>
request header, or send_message's legacy sender argument. Once bound, a session
cannot change its name. The header is the most robust choice, because the binding lives
in memory and a re-initialized session (after a server restart, say) re-binds from it:
claude mcp add --transport http swarm-agent https://swarm.example.com/mcp/agent \
--header "Authorization: Bearer $(cat ~/.config/tangentswarm/agent_api_key)" \
--header "X-Swarm-Agent: myrepo/my-branch"Clients that cannot set headers (claude.ai connectors) call register_agent first; the
server instructions tell them to. Names are self-declared: anyone with a valid
credential is trusted to say who they are. Every send is logged to stderr with the name
and the credential (apikey or oauth:<client_id>).
A swarm worker (any agent, here or in the cloud) tells the swarm its state over this HTTP
server, so the swarm does not have to guess from an unchanged tmux screen (tangentswarm #53).
Each report is one agent-report row in the swarm events DB (swarm-events shows it), and
the swarm-promoted daemon acts on it through the spool op report
(tangentswarm/agent_report.py):
| state | what the swarm does |
|---|---|
done |
the worktree must be clean and pushed (else the worker is told why); the Stop-hook handoff advances the card; then the Claude is closed with /exit once idle. The window stays and the session is kept for swarm-revive. |
needs-input (with question) |
posts the question on the ticket, moves the card to Needs Input, and closes the Claude. Moving the card back to In Progress resumes it with the answer. Until the report is handled, the Stop-hook handoff does not run. |
blocked (with message) |
posts the blocker on the ticket and moves the card to Needs Input; the Claude keeps running. |
working |
the events DB row only. |
Identity: pr is the agent's PR and window its tmux window name. The daemon refuses a
report whose window is not the one the swarm gives that PR, and one MCP session can report
for only one PR@window. The worker brief tells every worker to call this. The #40
watchdog's pane capture is the fallback only: agent_report.last_report(pr) says whether
the agent reported recently.
The same modes as swarm-mcp, with credentials that are separate in both directions:
apikey(selected automatically when a key is configured): the key comes from--api-key-file,$TANGENTSWARM_AGENT_API_KEY,$TANGENTSWARM_AGENT_API_KEY_FILEor~/.config/tangentswarm/agent_api_key. swarm-mcp's key is never read, and the agent key opens nothing on swarm-mcp, so agents never hold a key that can type into panes.external: swarm-agent is a resource server only. With no--issuer, the issuer is the origin of--public-url, which is where a swarm-mcp in builtin mode on the same host already runs its authorization server; their tokens share the store in~/.local/state/tangentswarm/auth.db. Tokens must carry thetangentswarm:agentscope and be issued for swarm-agent's exact resource URL, so swarm-mcp tokens are refused here and agent tokens are refused there. MCP clients find all this through/.well-known/oauth-protected-resource/mcp/agent. For headless agents, useswarm auth token issue --client <agent> --scopes tangentswarm:agent, or a client_credentials client withresource=<swarm-agent URL>in the token request.builtin: swarm-agent runs its own authorization server, issuing onlytangentswarm:agent. Use this only when it has an origin to itself, because the authorization server routes live at the origin root.
swarm-tick moves the tangentcode/platform swarm forward with no LLM in the loop. A
routine runs it every 15 minutes. The goal is that every Project 4 card is in Human
Review or Needs Input when Michal sits down.
swarm-tick --dry-run # change nothing; print "would: ..." lines and judgment items
swarm-tick # do the mechanical moves; print "did: ..." lines and judgment items
swarm-tick --verbose # also print every pane's class and each tool's outputEach pass classifies every pane in the tmux session agents (working, finished,
idle-dirty, asking, input, menu, exited). It then does the safe mechanical moves:
- An open In Progress or Auto Review PR whose body has no brief section gets the
coordinator's brief file (
$SWARM_BRIEF_DIR/<PR>.txt) added at the end of its body. A PR with no brief file is reported for judgment. - There is no held-launch list (tangentswarm #40): the Backlog column is the queue. An
idle shell whose head is still the
Start #Nscaffold commit, with a brief file, is reported, not queued. Memory pressure that lasts 10 minutes or more is reported with the live slice numbers. - A draft In Progress PR whose Claude is finished (idle, clean worktree, local HEAD is
the pushed PR head, no open Codex findings, head merges cleanly onto origin/main) is
marked ready and moved to Auto Review, with one
@codex reviewper head. active-gate --sweep --demoteandactive-gate --promote-missingrun as they are. The source ofactive-gateisbin/active-gatein this repo (tangentswarm #140). An Active issue whose linked open PRs are all in Deferred, with no open sub-issue, moves to Deferred; an issue with no linked PR stays needs-launch. The live copy is~/bin/active-gate. A human installs a new version withcp bin/active-gate ~/bin/active-gate(orln -sf "$PWD/bin/active-gate" ~/bin/active-gatefrom the live checkout).- One
swarm-flow stepruns (see below). Ready PRs are never gated by the tick.
Candidates in the priority milestone (ptw 15; override with
SWARM_PRIORITY_MILESTONES) go first, then FIFO.
Everything else is printed as one line per item that needs judgment, in the form
#PR %pane window: reason. Examples are Codex findings to relay, a menu, idle work
that is not pushed, a missing MinBot pass, a staging redeploy and a Claude that exited
mid-work. A pass with nothing to do prints nothing.
swarm-tick never merges, deploys, types into a pane, or kills or closes anything. It
reuses the tools in ~/bin (hr-gate, active-gate, pending-promote) and mn-workflow's
state file; it does not replace them. Its log is ~/.local/state/swarm-tick/tick.log.
Every platform worker PR has one fixed body template, tangentswarm.prbody.TEMPLATE. The
launcher opens the draft PR with it, so the worker never picks a heading name:
Fixes #N
## Before
## After
## Steps to reproduceThe worker writes text under each heading. Screenshots go under ## After. ## Steps to reproduce is a short list (1. ... or - ...): the steps to reproduce the problem, then
the steps to see the fix. It is not a where-to-see line: that is almost always staging.
Gate check 7b is gatechecks.template_problem() (it calls prbody.problem()). It needs
each heading by its exact name (no other spelling, level or case) and at least one step
under ## Steps to reproduce. A failure names each missing heading. Headings and steps
in a fenced code block, an HTML comment or the brief section do not count. There is no
phrase list. The worker brief gets the rule as prbody.RULE.
The coordinator writes one brief per worker PR to $SWARM_BRIEF_DIR/<PR>.txt. A draft
PR scaffolded with only Fixes #N hides that brief from reviewers. swarm-brief puts
the brief in a marked section at the end of the PR body:
swarm-brief 472 --file brief.md # save the brief for #472, then write it into the body
swarm-brief 472 473 # write the saved briefs into the bodies (no-op if present)
swarm-brief --check 472 473 # report onlyThe section starts with <!-- swarm-brief:start --> and ends with
<!-- swarm-brief:end -->. A gate check that reads the body (screenshots, the
PR body template headings, the served commit, code-only) must skip this section, because a
brief names those things before they exist. tangentswarm.brief.strip_brief() does that.
A PR body must not say whether the PR is merged into work, whether it is on staging, or
which commit a site serves. That text goes stale and contradicts the board column. The
## Steps to reproduce section lists only the steps to reproduce the problem and see the
fix. Every worker gets this as gatechecks.STATUS_RULE.
The swarm never edits a PR body (option A, Michal via MethBot on PR #133). Before
swarm-flow or swarm-tick runs hr-gate --apply, gatechecks.check_status() reads the body.
If a sentence states where the PR stands, the PR is held (a pull waits, as for
screenshots, and like screenshots it never times out), its worker gets one relay per head
that names the sentences, and one incident is opened per head. When a job is new for the
head, every open job (screenshots and status text) goes in one relay, relay-<N>-jobs.md,
because the revive queue keeps one entry per PR. The relay goes through to_worker: a Claude that cannot take the relay now gets a queued revive, and a gone
worktree gets a worker start with the relay as its brief. The detector has no wording exemptions: a false match costs
the worker one rewording. It reads whole sentences over soft line breaks and skips code
fences (also inside blockquotes) and the brief section.
swarm-start-scoped exits 3 when the worker slice is short of memory and leaves an
idle shell. swarm-launch runs it and returns held. There is no held-launch list
(tangentswarm #40). The launcher checks live capacity (slots.capacity(): MAX_CLAUDES
minus the Claudes running now and the launch and start requests in the spool, and 0
while memory holds starts) before it makes a branch or a PR. A start that memory holds
after the PR exists keeps the PR's unstarted record, and the cascade retries it. At
daemon start, swarm-promoted moves each row of an old held list ($SWARM_HELD, or
~/var/swarm-held.json) into an
unstarted record. A row with no PR gets the open PR of its branch. A row it cannot
move, or an unreadable file, stays and is reported at each daemon start; the file goes
only when it is empty.
swarm-launch BRANCH [WINDOW] --pr N --brief FILE # start now; exit 3 on a memory hold
swarm-launch --memory # print the live worker memoryMemory is read live each time: the slice's MemoryCurrent, MemoryHigh and MemoryMax,
and the host's MemAvailable. A launch needs 700 MB under MemoryHigh and more than
1.5 GB available, the same rule as swarm-start-scoped.
swarm-flow enforces methodology#56. Columns are matched by option id
(tangentswarm.board): Ready (finished, never merged, gated or checked), Staging (3 to 5
fully prepared PRs) and Human Review (exactly 2).
swarm-flow step [--dry-run] # one step under the serial lock (exit 75 = busy)
swarm-flow event NAME < JSON # from the GitHub hook: steps only on a Status change or a merge
swarm-flow status # Human Review, Staging, Ready, and the running pullOne step:
- Promote. Human Review has fewer than 2:
pending-promote --apply(never--fill). - Pull. Staging is below its target (
SWARM_STAGING_TARGET, default 2) and no pull runs: take the NEXT Ready PR in the shared pick order (board.pick_key: fast-track by the lowest number, then the soonest milestone due date, then the lowest number). If it does not stack cleanly on main + Human Review + Staging (local merge-tree only), nothing behind it is pulled (tangentswarm #65: no queue-jumping). A PR that does not merge onto main is fixed in place (tangentswarm #146, below). Merge the head intoworkas one merge commit and push it; the push redeploys staging.
The cascade (swarm-advance --cascade) pre-merges the top Ready PR every pass
(tangentswarm #65; tangentswarm #111 and #146: only the top one, always).
The main check also looks only at the top Ready PR. The rest of Ready is never re-checked:
a merge does not touch their labels, branches or columns. When a PR ahead of the top one
merges into main as its head, the top one keeps its -vN with no probe and no write
(Flow.assumed). A PR ahead that is sent back, gets a new head, or leaves the queue makes
it re-check. Human Review holds 2; each Staging to Human Review move queues the cascade at
once, and the cascade pulls the next Ready PR in pick order into Staging. Future main is main plus every queued PR (Human Review, then Staging,
then pulls in flight). A new <branch>-vN = future main + the PR head is pushed. A clean
one gets the label merge-ready. A real conflict gets pre-merging, and the PR's worker
resolves it on that -vN only; nothing is ever merged into the PR's own branch. A new head
or a new future main builds the next -vN. The pull takes the -vN tips in strict order
and stops at the first PR that is not merge-ready. Staging and Human Review PRs carry
merge-ready; a merge to main removes both labels.
3. Advance the pull. Evaluate hr-gate on the pulled head. All pass: hr-gate --apply
puts it into Staging. CI running or screenshots missing: wait (90 minutes at most). A
real conflict at the final mergeability check (row 2: the head conflicts with
origin/main): fixed in place (tangentswarm #146). Anything else (a hard
failure, a timeout, a moved head) has no conflict: the pull ends and the card stays in
Ready at its place in the pick order (tangentswarm #83). Its worker gets the reason once
per head; a moved head gets no relay (the webhook moves it to Auto Review).
One MinBot check (tangentswarm #154, Michal 2026-12-01). advance.minbot_check is the
one check of a PR at a head: the head is the one Codex reviewed, the PR is not a draft, no
open question for Michal on the PR or its linked issue, no conflict with main, no open Codex
thread on the head, Codex clean on the head, and every CI job on the head green. Three
places run it: the MinBot step (swarm-advance --minbot N, for a card in Auto Review or in
Ready), hr-gate condition 4 (gatechecks.minbot_pass on the current head), and the fast
Ready -> Staging move. No "MinBot pass" comment is posted, and nothing waits on one. So a PR
fixed in place in Ready passes condition 4 as soon as its facts hold, with no visit to Auto
Review. In Auto Review a pass moves the card to Ready and resolves the addressed Codex
threads; a conflict or an open thread on the head sends it back to rework. In Ready a pass
only resolves the addressed threads and queues the cascade. Green CI on a Ready head queues
the check. Every run writes one minbot-check event row.
Only the top Ready PR (tangentswarm #146, Michal 2026-11-18 2:09-2:18 PM ET). The fill looks only at the first Ready PR in the pick order (fast-track, milestone, lowest number). No PR further down Ready is checked against main, pre-merged or reworked until it reaches the top. If the top PR is blocked, the fill waits on it; it never skips ahead.
- Updated onto main after every merge. A merge into main queues the cascade, and the
top PR gets a new
<branch>-vNon the new main (a kept-vNthat does not hold the new main is not kept). Its tests run again on the-vNtip: the workflows inSWARM_PREMERGE_TESTS(defaultrs.yml mna.yml; empty turns this off) start once per tip withgh workflow run --ref <branch>-vN, and each pass reads the check runs on the tip. It moves up only when they are green. While they run, the PR carriespre-merging. - Fixed in place, never In Progress. If the top Ready PR conflicts with main (the main
check, the step pull, or the row-2 check at the move) or its tests fail on the
-vN, the card stays in Ready with the labelpre-merging, and its worker gets one fix relay per head (or per failed tip): merge origin/main into the branch, fix, test, push. A worker start is queued when it has no worktree. The fix-in-place record (fix-in-place.jsonbesidepull.json) keeps a new head in Ready (swarm-webhook does not move it to Auto Review, and a Codex finding or red CI on it is relayed with no move). The new head must be Codex clean before the fill goes on. When the tests pass on its new-vN, the record is dropped, the label becomesmerge-ready, and the PR moves up. - A stall notice at once. When Human Review is short of 2 after a cascade pass and no
pull in flight fills it, the cascade sends one plain-English notice that names the
blocked PR and why ("#580 (the top Ready PR) blocks it: it conflicts with main in
web/x.ts", or "Ready is empty"). It is a JSON POST
{source, kind: "stall", pr, text, at}to the URL in~/.config/tangentswarm/stall-url(SWARM_STALL_URL_FILE; optional bearer key install-key,SWARM_STALL_KEY_FILE). With no URL, swarmbot is woken instead. It is sent once per stall; a full Human Review resets it.
There is no parking (tangentswarm #101, Michal 2026-11-17: this replaces the Nov 15 rule
never to move a card into a column with no worker). A conflicting PR out of Ready (the
Staging main recheck, or an Auto Review rework) always goes to In Progress. Its
Claude gets the relay now, or the relay waits for a Claude: a queued revive (queued in
slots.json) or, with no worktree, a worker start with the relay as its brief (unstarted).
The cascade runs both in the shared pick order when a worker slot or memory frees. Nothing
is held in Ready, so the PRs behind it are pulled as usual. swarm-tick and the sanity check
accept such an In Progress card with no live Claude. At start, swarm-promoted deletes the
old held.json; the next passes find each conflict again.
Only the pulled PR is merged, deployed or gated. swarm-tick runs one step per pass; the
GitHub hook runs swarm-flow event on projects_v2_item and merge events.
First keep the flow full (Human Review 2, Staging 2, more Ready; fixed WIP targets,
never pulled past). Within that, a PR
labeled fast-track or high priority (on the PR or on an issue it closes) jumps the
queue at every step: pane order in swarm-tick, the Ready head, the
FIRST Staging slot (it stacks on main + Human Review only; the Staging PRs behind it are
re-stacked at their own promotion), and the next free Human Review slot. The serial lock
and every gate still apply. tangentswarm.board.priority_rank() is the rule; the live
hr-gate's queue order uses the same one.
A systemd user service with no LLM in the path. Every 30 seconds (or at once on
SIGUSR1, for example from a webhook receiver after a merge) it reads the Status of
every open PR from the board cache. When Human Review holds fewer than 2 and Staging is
not empty, it takes the serial lock (retrying every 5 seconds while busy) and:
- Fast path (tangentswarm #116): if hr-gate passed the Staging PR at its current head (an hr-gate PASS or PENDING line with no failure), it moves that card to Human Review first and writes the hr-gate PASS line. Nothing else is checked again: every Human Review check ran before the PR entered Staging. After the move, one GraphQL read confirms the head; a PR whose head moved, or that became a draft, goes back to Staging. The main SHA, the deploy-lag check and the cascade check run after the move.
- Slow path:
pending-promote --applyif Human Review is still short.SWARM_PROMOTE_PULL=1runs a fullswarm-flow stepinstead (it also pulls).
Every second it also reads the new lines of the relay's GitHub event log
(~/relay/github-events.jsonl, tangentswarm/events.py, tangentswarm #31). A submitted
review or a Codex comment on a PR in a repo that mn-workflow runs for (the repos of
SWARM_MN_CONFIG, default ~/ver/mn-workflow/config.json) starts mn-workflow.service
at once. When a pass is already running, it starts the next pass when that one ends. The
wanted pass is kept in SWARM_MN_PENDING (default ~/.local/state/swarm-flow/mn-pending),
so a daemon restart does not lose it. A Codex result on a platform PR also queues
swarm-advance --minbot N. mn-workflow.timer is only a slow backstop.
Board cache (tangentswarm #116). swarm-webhook patches the board snapshot
(~/.cache/swarm-board-snapshot.json) from every delivery: a Status move, a merge or a
close, a new head, labels, draft state. Every swarm card move patches it too. So nothing
reads the board before a move. An event the cache cannot follow (a new card, a new
milestone, hr-gate's own move) marks it dirty, and the next read takes the board. The
sync reads the board every SWARM_BOARD_SYNC seconds (default 1800) and writes each
difference it finds to ~/.local/state/swarm-flow/board-sync.log: those are the events
the cache missed. The merge clock writes one line per platform merge to
~/.local/state/swarm-flow/merge-to-move.log: the seconds from the merge event (and from
GitHub's merge time) to the card move, or "no move".
Priority staging site (tangentswarm #116). Each PR has one priority staging site. A
milestone word picks it ([staging] priority = { PTW = "ptw" } in the config, the
default), else [staging] priority_default (default ptw). hr-gate condition 6 and the
cascade's served check wait only for that site. The other sites roll out in the
background; their lag is named as "rolling out (not blocking)" and never holds a card.
swarm-promoted --once --dry-run # one check; print what it would move
systemctl --user kill -s USR1 swarm-promoted # wake it nowA thread of swarm-promoted (SWARM_WATCH=0 turns it off), with no LLM. Once a minute it
runs tmux capture-pane on every pane of session agents, keeps the latest capture, and
compares it with the last one. A working Claude shows a running timer, so a screen that
did not change for a minute has finished or stopped. It then acts on a worker pane:
- unsent text in the prompt: Enter
- idle with the work handed off, or the card in Needs Input:
/exit; the window stays - idle, clean and pushed, but the card is still In Progress or the PR is a draft: the
watcher runs the handoff itself, right then (tangentswarm #120): it marks the PR ready,
moves the card to Auto Review and asks Codex, also for a head that was handed off before
(a finding the worker found already fixed). A handoff that does not finish in
SWARM_HANDOFF_WAITs goes to swarmbot once, with an incident - idle with uncommitted files or unpushed commits: one nudge, and swarmbot is told once, with an incident; the card is not moved
- a question in the pane: queued as a needs-input report (a worker never asks in its pane)
- a menu, a frozen busy screen, or a trust dialog that stays: swarmbot diagnoses
It also wakes swarmbot (an alert row in the events DB) for a new Needs Input card on any
board, a Codex outage (one alert per outage) and Human Review empty while Staging holds PRs
(with the reason and a suggested fix). These never go to MethBot (tangentswarm #19). It kills hung test runs in
worker worktrees and wakes swarmbot with the process and the pane capture. Every hour it
sweeps issue cards with no PR back to Backlog and moves Done PRs whose head is not on main
out of Done. Each failure opens an incident ticket on Project 6 (methodology #81).
Agents report their own state with report_status (below); the pane capture is the
fallback, and a PR whose agent reported in the last 10 minutes is left to that report.
The worker MCP tool needs_input(pr, question) queues the same needs-input report (the
question goes on the ticket, the card to Needs Input, the Claude closes); Michal's move
back to In Progress resumes it with his answer. Every @codex review round is logged to
the events DB, with no cap.
One code path posts @codex review: codexrounds.ask() (tangentswarm #63). The tick, the
Stop hook, the worker MCP and the webhook all call it. It holds an interprocess lock and
posts at most one ask per (repo, PR, head SHA). It skips a head that Codex already answered
or is reviewing, and a head with a pending ask younger than SWARM_CODEX_ASK_WAIT (1800 s).
It asks again only after a Codex "Something went wrong" reply or that timeout. A re-ask is
a codex-retry row in the events DB, not a new round.
MethBot gets POSTs only for the Project 6 repos (tangentcode/tangentswarm,
tangentcode/methodology; tangentswarm #19, #89): one POST to the URL in
~/.config/tangentswarm/methbot-alert-url with the bearer key in methbot-alert-key.
needs_input from a worker in ~/ver/tangentswarm.<slug> or ~/ver/methodology.<slug> sends
{"source":"swarm","kind":"needs-input","repo":...,"pr":N,"question":...,"at":ET time}.
That worker's handoff (done, clean and pushed, the head shown on its open PR) has no AI
on the success path (tangentswarm.p6merge, tangentswarm #89). The worker's
MERGE-READY <full sha> PR comment does the same, through swarm-webhook. The swarm checks
the exact head: the PR is open, not a draft and on main; Codex is clean on the head (a
completed review-state summary with both findings flags false); no unresolved review
thread (an outdated one counts unless the worker replied); required CI is green; GitHub
says MERGEABLE. Then it runs gh pr merge --merge --match-head-commit <sha>, moves the PR
card and the closed issue cards to Done, runs the merge cleanup (below: the worker ends with
/exit, its windows close, a clean worktree and its local branch are removed), writes a p6-merge events row,
tells swarmbot that a tangentswarm deploy is needed (only a note), and sends MethBot one
pull POST with the next Project 6 Backlog issues for about 4 live workers, in pick order.
A check that fails sends one exception POST with the reasons, once per PR and head, and
there is no merge. Each POST is also a methbot-<kind> row in the events DB.
swarm-watch --panes # the latest capture class of every pane
swarm-watch --once --dry-run # one pass of every check; print what it would do
swarm-codex-rounds --days 7 # the PRs with the most Codex rounds, round by roundAfter a PR merges, on every board (tangentswarm.mergecleanup): an idle Claude in the PR's
worktree is ended with /exit, the PR's windows (<code>-<PR>-*) and every window with a pane
in the worktree close, the worktree is removed when it is clean, and the local branch is deleted.
The merge event starts it (swarm-webhook cleanup for platform, p6merge for Project 6).
- A busy Claude, or a window that runs a program, is never killed. The cleanup stays pending in
~/.local/state/swarm-flow/merge-cleanup.json, and swarm-promoted tries it again every minute. A cleanup still busy after 6 hours is reported once. - A worktree with uncommitted or untracked changes is kept, with its worker, and reported once (MethBot exception for Project 6, swarmbot alert for platform). A local branch with commits that the PR head does not have is kept and reported once too.
- Every 15 minutes swarm-promoted also sweeps
~/ver: a worktree whose latest PR merged or closed, and that no open PR uses, gets the same cleanup. A worktree with no PR is left. - Never removed:
tangentswarm.flow-live,tangentswarm.swarm-tick,tangentswarm.agent-dashboard(SWARM_CLEANUP_KEEP), and proofbot'sleannyc/lean-nyctrees.
swarm-merge-cleanup # one full sweep now
swarm-merge-cleanup --pending # the pending cleanups and what they wait forA deterministic check (no LLM) of the board column rules of methodology workflow.md and of
one Claude per worktree. The watchdog runs it at startup, on a board change (a webhook
projects_v2_item event, or a changed Project 4 snapshot), and once an hour as a backstop.
There is no polling of its own. A finding must still be there after 10 minutes. Then each
pass makes one report for all its new findings (#82): one incident ticket on Project 6 and
one swarmbot wake. The same finding is not reported again while it stays. Cards in the
Deferred column of Project 4 are not checked. docs/sanity-check.md lists every check.
swarm-sanity # dry run: every finding, and what --apply would do now
swarm-sanity --apply # file the incident ticket and tell swarmbot
swarm-sanity --json # the findings as JSONIn methodology #84, two MCP units ran from ~/srv/swarm-tmux while the other swarm units
ran from ~/ver/tangentswarm.flow-live, so a deploy did not reach them. swarm-unit-check
reads each swarm user unit (swarm*.service) that is enabled or active, with systemctl --user show: WorkingDirectory, PYTHONPATH and ExecStart. It finds where Python imports
tangentswarm from: the first sys.path entry (the working directory for python -m, or the
script directory), then PYTHONPATH. That must be flow-live. A WorkingDirectory or an
ExecStart path in another tangentswarm checkout also fails. When the unit runs, its process
is checked the same way, with the cwd and environment from /proc. A disabled unit that is
not active is skipped. A running template instance (swarm@x.service) or transient unit
has no unit file of its own; it is found with systemctl --user list-units and checked while
it runs. It exits 1 and names each bad unit; it exits 2 when it cannot read
systemd.
swarm-unit-check # one line per unit; exit 1 if any unit fails
swarm-unit-check --json # the results as JSON
swarm-unit-check swarm-webhook.service # only these unitsThe flow-live path is $SWARM_FLOW_LIVE (default ~/ver/tangentswarm.flow-live).
Where it runs:
-
The sanity check runs it as the rule
unit-source. swarm-promoted runs the sanity check at startup, so each flow-live deploy (it restarts swarm-promoted) runs it, and so does the hourly pass. A bad unit wakes swarmbot and opens an incident ticket. -
A deploy script on the host calls it after its restarts, so the deploy fails loudly:
~/ver/tangentswarm.flow-live/bin/swarm-unit-check || exit 1
The host scripts (
~/bin/swarm-flow-live-deploy,/usr/local/sbin/swarm-tmux-deploy) are host config outside this repo, so this line is added there by hand.
Only one merge or gate operation may run at a time: hr-gate --apply, hr-gate --sweep, pending-promote and the work merge. Each takes one global lock with a
non-blocking flock. A second caller prints busy: <holder> and exits 75 at once, with
no API call; the next event or pass tries again. swarm-tick reports a busy lock as a
note, not as an error.
swarm-lock -n work-merge -- git push origin HEAD:work # run a command under the lock
swarm-lock --status # free, or busy and the holderThe lock file is $SWARM_GATE_LOCK (default ~/.cache/swarm-serial.lock); the holder
note is next to it. SWARM_SERIAL_HELD=1 (or the older HR_GATE_LOCK_HELD=1) marks a
run whose parent already holds the lock. hr-gate --apply also skips draft PRs before it takes the lock.
A CI-completion hook runs ci-last-check SHA first and stops when it exits 1. A storm
of CI events on new draft PRs once used up the whole REST quota. swarm-hookgate
decides before any REST call:
swarm-hookgate ci-last-check SHA # gate, then the REST check; 0 = go on, 1 = stop, 2 = error
swarm-hookgate check SHA # gate only (no REST call)
swarm-hookgate wait # return once the REST quota has a reserve; sleep through the reset- It maps the SHA to a PR with a cached board snapshot (GraphQL only; refreshed when it is older than 2 minutes or the SHA is not a known head).
- It skips closed and draft PRs, and every card outside Auto Review and Pending.
- It debounces per head: a head with complete CI is skipped for 30 minutes, and repeated events while CI runs reach the REST check at most once a minute.
- Below 300 REST calls left it waits for the reset time instead of failing mid-run.
The SWARM_HOOK_* variables override these limits. The state is in ~/.cache/swarm-hook.
swarm-api is a loopback HTTP service (default 127.0.0.1:8779) for the platform swarm
app (the Petri-net control panel) and, later, a coordinator. The front proxy on the swarm
host routes /api/ to it. It answers only /api/*; the app (/) and the MCP routes
(/mcp/*, /login, /token, /authorize, /register, /revoke, /.well-known/) are not
its routes. It refuses to bind a non-loopback address.
Read (per swarm; {b} is the board number): GET /api/swarms, /api/swarms/{b}/places
(each column with its open cards and a count), /transitions (the steps, who fires each,
the rules and the limits such as Human Review at 2), /events (the events DB, each row
handled, unhandled, pending, dropped or error; ?since=&limit=&source=&pr=), /messages
(the swarm-hub messages; read = handled) and /lease (the coordinator lease: none until
#23 adds one; and the serial gate lock's holder note and queue). GET /api/health needs
no auth; GET /api/whoami shows the caller.
Human actions (JSON bodies): POST /api/swarms/{b}/cards/{n}/triage {"action": "approve" | "backlog" | "active" | "discuss"} (approve = Backlog, where the launcher takes work),
POST /api/swarms/{b}/cards/{n}/answer {"body"} (a comment where the question is: each linked issue whose latest comment is
the question, else the card itself; then Needs Input
-> In Progress, which swarm-webhook relays to the worker) and POST /api/swarms/{b}/messages/{id}/answer {"body"} (a hub reply to a question or blocker). Each
one uses the swarm's own tools (board.move_card, tick.sh for the gh write, the hub
client) and logs a human-action row with the human as actor.
Auth:
- Work login (browser): the front proxy does the work login and forwards
X-Swarm-User: <login>andX-Swarm-Proxy-Secret: <secret>. The secret is in~/.config/tangentswarm/api-proxy-secret($TANGENTSWARM_API_PROXY_SECRET_FILE; mode 0600, 32+ characters). Without the right secret the user header is ignored. Proxy users read and write;$TANGENTSWARM_API_HUMANS=a,blimits writes to those logins. - Machine credential:
Authorization: Bearer <token>fromswarm auth token issue --client NAME --scopes tangentswarm:status(read). A write also needstangentswarm:act, which the CLI issues only with--subject LOGIN(the human the token acts for). A token with another resource (an MCP token) does not count. - A write must be
Content-Type: application/jsonand, when the browser sendsOrigin, same-origin (HostorX-Forwarded-Host). There is no CORS.
swarm-webhook (tangentswarm/webhook.py) is the GitHub org webhook receiver. It runs the
board rules with no LLM.
Everything the swarm does is one row in one append-only SQLite table,
~/.local/state/swarm-flow/events.sqlite (tangentswarm/eventdb.py, $SWARM_EVENTS_DB).
The old webhook-events.sqlite is renamed to it once. Each row has a source and an
actor:
| source | what |
|---|---|
| webhook | every GitHub delivery (received, handled, replay) |
| mcp | every worker MCP call (worker_status, handoff, request_review) |
| stop-hook | each Stop hook run and its decision |
| launcher | a launch (branch, draft PR, brief, worker) and a worker start |
| slots | park (/exit), resume, feedback to a running Claude, tell |
| relay | a merge-main relay to a Claude pane |
| minbot, gh | every minbot --apply call and every gh call that writes |
| board | every card move, with its PR and column |
| cascade | each cascade pass (its lines) and each MinBot check |
| hr-gate | hr-gate's own card moves |
Rows are written with eventdb.log_event(), which never raises.
swarm-events is the console viewer of that log. --source mcp,stop-hook shows only those
sources. It opens the DB read-only and shows today's events (ET), one row per event: time,
status (handled, queued, failed), event (an action row starts with its source), PR, actor and the outcome in plain words ("moved #513 to Done; cascade"). Skipped events, log-only
events, redeliveries and cascade passes that did nothing are hidden. A signature shows only
when it failed (white on red); a failed event is red. In a terminal the screen is redrawn
every 10 s (--redraw): rows from the last 2 minutes are bright, and each older minute is a
darker gray. -v prints the rows as JSON. --since all|YYYY-MM-DD and --once are also
available.
The Agents screen (press a in a terminal, e to go back, q to quit; or start with
--agents) shows one line per pane of the agents tmux session, read live from tmux, /proc
and ~/.claude/sessions (tangentswarm/livestate.py, tangentswarm/agents_view.py). When
the panes do not fit, j/k (or the arrows) scroll a row and space/b (or PgDn/PgUp) a
page; the header and the summary stay. No line is wider than the terminal. Each line shows:
- the Claude pid, or "no claude" when no
claudeprocess runs in the pane; - active or idle: the Claude session status, and a screen capture once a minute (a screen that changed in the last minute is active);
- tests (pytest, jest, vitest, ...) and other processes in the pane;
- the memory and CPU of the pane's process tree;
- the PR and card, from the board snapshot file (never fetched by the viewer).
The header shows the load average, the worker slice memory, the Claudes that count against
SWARM_MAX_CLAUDES, and the start capacity. Starts are held while the worker memory is short
or the 5-minute load average is over SWARM_LOAD_PER_CPU (default 1.5) per CPU
(launches.admits). With --once or a pipe the screen prints once.
python -m tangentswarm.livestate --json prints one sample as JSON (for the sanity check, #43).
Install it, in one of these ways:
pip install . # the swarm-events entry point
ln -sf "$PWD/bin/swarm-events" ~/bin/swarm-events # or: this checkout, no install
The bin/swarm-events wrapper uses $TANGENTSWARM_PYTHON (default python3). To keep it
open in tmux:
tmux new-session -d -s events -n webhook ~/bin/swarm-events
tmux attach -t events
Private ids, hosts and secret paths are in ~/.config/tangentswarm/config.toml, never in
the repo. tangentswarm/config.example.toml shows the shape.
swarm-methlab (tangentswarm/methlab.py, tangentswarm #115) tests the swarm flow with no
GitHub and no network. methlab.FakeGitHub is an in-memory GitHub (PRs, issues, board cards,
Codex reviews, CI). The real webhook rules run against it in tests/test_methlab.py.
swarm-methlab replay --hours H runs the recorded deliveries of the event DB (read-only)
through the current rules and lists each decision that changed. swarm-methlab live-check
and live-env guard the settings of the on-demand live sandbox (a separate test org). See
docs/meth-lab.md.
swarm-tmux-status is a standalone console table of the windows in the swarm tmux session
(default agents, or --session / $SWARM_TMUX_SESSION). It reads tmux only. Each window
gets one class from its foreground command and its screen:
WORKING: Claude runs and is busy ("esc to interrupt" under its input box)idle: Claude runs but does no workshell: no Claude, a shell prompt- a program name (such as
python): no Claude, another program in the foreground
A row also shows the window index, the ticket from the window name (mn-458-... is
mn #458) and the last activity line (Claude's last transcript entry, or the shell's last
line that is not a prompt). The default view lists only the working windows. Keys: a
toggles all windows, up/down or j/k select, Enter or z zooms into the window's recent
output, Esc or q goes back, r refreshes now. It refreshes every --interval s (default 2).
swarm-tmux-status # the interactive table
swarm-tmux-status --once [--all] # print the table once
swarm-tmux-status --zoom 41 # print the recent output of window 41
ln -sf "$PWD/bin/swarm-tmux-status" ~/bin/swarm-tmux-status # this checkout, no install
MIT