SLOPSHOPPER

adversary-draft

Tells the adversary bridge whether the prompt box holds an unsent draft, so it never pastes into one.

prompttimer
★ 1v0.1.0no licenseupdated 2026-10-25a904guy/Adversary-Dueling-Claude/adversary/draftmod
A shopper browsing a rack in a slop shop
README

Adversary: Dueling Claude: Automating Claude Code

I run one Claude Code session (the worker) on a task and a second Claude Code session (the adversary) as its supervisor, side by side in tmux. The adversary:

  • is given the task first, studies the repo, and hands the worker a plan — the worker is never given the task directly, so the two don't start from competing plans,
  • answers the worker's "shall I proceed?" questions,
  • approves or denies the worker's permission prompts,
  • reviews the work against the original task when the worker says it is done. It reads the code and runs the tests itself, and sends back anything missing or broken until the task is actually finished.

Both sides are the regular claude CLI, so usage comes out of the logged-in Claude plan, not an API key.

┌─ WORKER · does the task ───┬─ ADVERSARY · reviews ──────┐
│ real `claude` session      │ real `claude` session      │
│ (watch it, copy, Esc to    │ (read-only + MCP tools)    │
│  stop it)                  │ ◀ type here: it has focus  │
├────────────────────────────┴────────────────────────────┤
│ BRIDGE · [running] exchange 3/30 · approvals 7 · …      │
└─────────────────────────────────────────────────────────┘

Requirements

  • Python 3.11+
  • tmux
  • the claude CLI, logged in
  • git (optional, see Without git)

Install

python3 -m venv .venv
.venv/bin/pip install -e '.[dev]'

The package has no runtime dependencies beyond the standard library. It installs two names for the same command, adversary and claude-adversary; use whichever you like.

Usage

adversary run "Implement X so all tests pass and document it"

That is all that's required. It works in the current directory. Every flag below is optional.

FlagEffect
--repo PATHWork in PATH instead of the current directory.
(default)The worker runs in Claude Code's auto mode: its classifier approves what's safe, and every prompt that remains goes to the adversary, which must call approve_tool or deny_tool. The worker sees the deny reason.
--worker-permission-mode manualEvery worker permission prompt goes to the adversary.
--skip-permissionsThe worker runs with --dangerously-skip-permissions, so there is no approval traffic.
--worker-permission-mode acceptEditsEdits are auto-approved and only the remaining prompts (for example Bash) go to the adversary. This is cheaper, because each prompt costs a full adversary turn.
--strict-approvalsIgnore user-level settings for the worker, so no personal allow rule lets a tool call skip the adversary.
--worktreeWork in a fresh git worktree on branch adversary/<timestamp> (git repos only).
--max-exchanges NLoop guard: after this many round trips between the agents without me (default 30), the worker is put on hold. The count restarts whenever I type to either side and on resume, and the run is never ended by it. Permission requests don't count.
--stall-after SECONDSTreat it as a stall when both agents sit idle this long while the run is unfinished (default 120, 0 turns it off): it's logged and the supervisor is woken to get the run moving.
--worker-model, --adversary-modelPick the model for each side. Both default to opus, Claude Code's alias for the latest Opus, whatever the account's default model is.
--worker-effort LEVEL, --adversary-effort LEVELEffort level for each side (low, medium, high, xhigh, max; passed as claude --effort). Defaults: worker high, adversary xhigh. Also accepted by adversary resume to change them; otherwise a resume keeps the run's levels.
--adversary-mcp SPECGive the supervisor an MCP server by name (repeatable; by default it gets the worker's browser servers read-only: every Chrome DevTools server, and Claude in Chrome when it's on by default). NAME is the server's key under mcpServers in your MCP config — the name claude mcp list shows — and gives all its tools; NAME:readonly a look-don't-touch preset for browser servers (Chrome DevTools, Claude in Chrome: navigate, snapshot, screenshot, console/network — no clicking, typing or running script); NAME:tool1,tool2 exact tools. claude-in-chrome turns on Claude in Chrome. On resume it replaces the run's choice; none clears it.
--adversary-permission-mode autoThe default. The supervisor may run ordinary commands to check the worker's claims about the machine as well as the code (lsusb, ps, systemctl status, journalctl, curl against the app), and Claude Code's auto-mode classifier stops risky ones. It still can't Edit or Write, and its prompt tells it to look, not change.
--adversary-permission-mode strictThe supervisor gets only its allowlist (dontAsk): Read/Grep/Glob, web research and read/verify Bash prefixes. Anything else is refused.
--verify-cmd "just test"Extra command prefix the adversary may run (repeatable). In strict mode, this is how to allow another command.
--task-file FILERead the task from a file.
--no-attachStart the tmux session detached.

Resuming

adversary resume

This picks up the last run in the current directory (or the folder it was started from, for --worktree runs). It works after a crash, a closed terminal, a stall, or a run that already finished.

  • Both sessions come back: each Claude Code session is reopened with claude --resume, with its full history.
  • The adversary decides what's next: it is told the run was resumed and given the worker's last message (or told the worker's last turn left none). It checks the current state, then sends the worker what to do next, calls hold, or calls finish. This is the same hand-off as at the start of a run: the worker stays idle until the adversary's reply reaches it.
  • New instructions are optional: adversary resume "Also add a --verbose flag" passes them to the adversary as an amendment to the task, and the worker starts on them first. Without them, the adversary is told to carry on with the task as it stood, including changes asked for earlier.
  • Settings can change on resume: resume takes the same setting flags as run — --worker-permission-mode / --skip-permissions, --adversary-permission-mode, --strict-approvals (or --no-strict-approvals), --max-exchanges, --stall-after, --worker-model, --adversary-model, --worker-effort, --adversary-effort, --verify-cmd (added to the run's existing ones) and --no-attach. Anything not given keeps what the run used; anything given is saved for later resumes too, and the launcher prints what changed. Only the task, --task-file and --worktree are run-only.
  • Counters carry over: exchange, approval, denial and stall counts, and permission request numbers.
FlagEffect
--repo PATHResume the last run in PATH instead of the current directory.
--run IDResume a specific run, by timestamp (20261001-143802) or run directory.
--killIf the run is still open in its tmux session, close it first. Without this, I'm asked to confirm.
--no-attachStart the tmux session detached.

Runs record their session IDs as they start. For older runs, the sessions are found in Claude Code's session logs for the folder.

Keys in the bridge pane:

KeyAction
pPause or resume relaying, to take over by hand
sPrint the status line and the full run stats (the same block shown at close, with current figures)
qEnd the run: marks it ABORTED and shuts both Claude Code sessions down (SIGTERM, then SIGKILL after 10 s). adversary resume picks it up again.

Closing the run from outside tmux does the same orderly shutdown — saving state and recording the final numbers — without marking the run ABORTED (a bare close is an interruption, not a finished run). adversary resume --kill closes the old session (SIGHUP) on its way to relaunching, and a kill on the bridge (SIGTERM) also ends it cleanly.

At the close the stats are printed to the bridge pane, written to stats.txt in the run dir, and — when the run was started in the foreground (attached) — reprinted in the terminal you launched from once tmux exits, so they land in your scrollback and aren't lost when the window closes. (Opened in a new window, or started with --no-attach, there's no launching terminal to return to, so the bridge pane holds its readout open until a keypress instead.) The stats also go into report.md. When the run was resumed they show this session's numbers alongside the lifetime total; on a first run they are just the totals. Metrics are exchanges relayed, worker and supervisor turns, permission requests (and how many approved/denied), holds, message_worker nudges, read_worker peeks, stalls, human interjections, runtime, approval rate, tokens written this session (model output; input is mostly repeated cache reads, so it isn't counted), and the diff size since the run started: files, lines added and lines removed, counting new files a worker hasn't committed. In a folder that isn't one git repo, each git repo inside it gets its own line, counted with git from the commit it was on when the run started, so its .gitignore applies. Everything else is counted from the snapshot, with the biggest top-level folders named, so scratch output such as screenshots shows up as such and doesn't hide the code changes. Binary files count as files but add no lines. A run from before starting commits were recorded gets them on resume: the last commit before the run began.

The first run in a project opens a short "how this works" popup over the panes, and the first time I select the worker pane, a tip points me back to the adversary pane. Each is shown once per project; which ones I've seen is kept in ~/.local/state/adversary/projects/<folder>.json (delete it to see them again). A key closes them.

I talk to the run through the adversary pane on the right. It has the keyboard when a run starts or resumes: the bridge selects its window and pane once its session has loaded. I can type into it at any time, for example to add features or change the task. Its reply to me isn't relayed, but it passes the work on with its message_worker tool, which reaches the worker straight away. If the worker is busy, the message is typed into its pane and Claude Code folds it into the running turn. Delivery waits while a permission request is pending, and while I have a message drafted in the worker's prompt box. The same goes for the adversary's ordinary replies (what it says at the end of a turn in answer to the worker): they're sent to the worker immediately too, folded into its running turn if it's busy, rather than held until the worker finishes.

The worker pane on the left is for watching, copying output, or stopping the worker with Esc. Anything typed there is passed to the adversary as an amendment to the task, and it takes precedence over the original.

The bridge pane along the bottom is kept 4 rows high. It shows the status line ([running]/[PAUSED], exchanges since I last spoke against the cap, approvals and denials, pending permissions, whether each side is busy or idle, "worker on hold", and "waiting for your draft") and a log of each relay. The keys above work when it has focus.

When the worker has nothing to do — because I need to decide something, or because it is waiting on a background subagent or task it launched — the adversary calls hold. Its reply that turn isn't forwarded and the worker stays idle, rather than the two trading "still waiting" / "leaving it be" messages while nothing happens. The hold ends when the worker's next real turn arrives (a subagent finishing brings it back on its own), when the adversary calls message_worker, or when I type to the worker, and a held run isn't logged as a stall.

If the adversary doesn't hold and instead keeps replying to a worker that does nothing back (the classic subagent-wait loop), the bridge steps in: after a couple of worker turns in a row that take no action after an adversary reply while background work the worker launched is still out (a run_in_background command or a background subagent/teammate that hasn't reported back), it puts the worker on hold itself, naming what it's waiting on, and tells the adversary to stop replying. With nothing in the background, a reply in words is conversation, not a wait loop — "I don't understand X", "I'll get to that after Y" — so it is always relayed, and the supervisor is prompted to re-explain with concrete detail or settle the order of work rather than repeat itself. A genuine back-and-forth loop is still caught by --max-exchanges. Nothing the worker says during an auto-hold is dropped: it's kept (the status line shows worker on hold (N msg kept)) and delivered to the supervisor ahead of the worker's next message, so it reads the whole chain in order.

A hold on background work has a check-in deadline: background tasks can hang, or finish without the notification that wakes the worker, and the run would sit parked forever. If the worker isn't back within 10 minutes, the bridge sends the supervisor a check-in — how long it's been, what is still running (or that nothing is), and anything kept back — and the supervisor decides whether to keep waiting (hold again) or get the worker moving (message_worker). Unanswered, it asks again at double the interval, up to an hour. The supervisor can set its own interval with hold(check_after_minutes=N) (0 turns it off); a hold that waits on you rather than on background work has no check-in unless it asks for one. Messages a subagent sends back to the worker ("Another Claude session sent a message…") are treated as background notifications, not as me typing, so they don't reset the loop guard.

The run repairs itself where it can.

  • An agent that exits (the kernel killed it for running out of the run's memory, a crash, /exit) is started again in a new pane with its conversation, after 5 seconds, doubling with each restart. The supervisor is told what happened, and when it was killed for memory, it's asked to have the worker keep memory use down. An agent that exits five times within an hour is left down; a managed run closes then, so the manager can start it fresh.
  • A stall (both agents idle with the run unfinished, nothing on its way) wakes the supervisor to check the worker and give it its next step, up to three times until the worker moves again. A side whose turn ended without a Stop event (an Esc interrupt) is treated as idle. A card that's waiting on people isn't woken; it parks.
  • A message that never went in (no submit, nothing running, after 30 seconds) is settled from the session log: delivered if it's there, sent again if not.
  • A compacted supervisor gets its role and the task back straight away. Its role file is the system prompt and survives compaction, but the brief (the task verbatim, the repo and baseline, how its Bash works) was its first message and is only summarised. So the SessionStart hook that fires after the compaction returns a reminder of both as additionalContext. This doesn't need a turn or typing into the pane, so it works mid-turn too. A person's /clear is left alone.
  • A dialog over the prompt holds deliveries back, like a draft. In a pane nobody is attached to it's closed with Esc after a minute. Both agents run with Claude Code's /auto-mode-setup prompt switched off (skillOverrides), since it opens by itself and takes the keyboard.

finish isn't final. When the adversary marks a run complete and I come back later with a new task or a follow-up, I just tell the adversary in its pane; its message_worker call picks the finished run back up and starts the worker again (the report already on disk stays as the record of that round). I can also restart the worker by typing straight into its pane. This is lighter than adversary resume, which is for picking a run up in a fresh tmux session after the window is gone.

Each run writes to ~/.local/state/adversary/runs/<timestamp>/:

  • transcript.md: every relayed message, permission decision and human input
  • report.md: outcome, the adversary's summary, the run's metrics (exchanges, worker/supervisor turns, permission decisions, holds, nudges, peeks, stalls, runtime, tokens, diff size — this session alongside the lifetime total on a resumed run) and the files changed since the run started
  • stalls.jsonl: one record per stall, written when both agents have been idle for --stall-after seconds with the run unfinished. Nothing moves the run forward at that point, so it is almost always a relay failure. Each record holds both sides' last turn, queued messages, pending permissions and last message. It is also shown in the bridge pane and the transcript, and appended to ~/.local/state/adversary/stalls.jsonl across all runs.
  • snapshot/: the folder's original contents (folders without git only)
  • state.json: counters, runtime and token totals carried over by adversary resume
  • stats.txt: the end-of-run stats block, written at close and reprinted in the launching terminal
  • the generated settings, MCP config and launch scripts

Managing a pool from a 4ga board

adversary manage watches a 4ga Boards project and keeps up to --pool runs working its cards. Runs started by hand (adversary run, adversary resume) are unchanged: everything below applies only to runs the manager launches.

adversary manage --project "AnySite" --folder /mnt/projects/AnySite -- --cpu-quota auto

Flags after -- go to every run it starts. --pool (runs at once) defaults to the number of CPU threads available, so with --cpu-quota 100% (one core's worth per run, see below) a full pool fills the machine without any run taking more than its share.

CPU and memory limits. --cpu-quota 100% and --memory-max 3G (on run, resume, or after manage --) put a run in its own systemd slice, adversary-run_<id>.slice. Its worker, supervisor and bridge each join the slice as they start (systemd-run --scope), so everything they launch (Bash commands, MCP servers, test runners) is held to the run's limits by the kernel. The tmux server is shared, so the processes join the slice themselves; tmux attach works as before. --cpu-quota auto gives a run its share of the CPU with one thread kept free for the OS: (threads − 1) ÷ the pool size, so 4 runs on a 4-thread machine get 75% each (3 cores in all), or threads − 1 for a single adversary run. --memory-max auto gives a run its share of the machine: (RAM − 1 GB) ÷ the pool size, or RAM − 1 GB for a single adversary run. manage fills that in by itself for runs given --cpu-quota without a memory limit. The slice is a unit under /run: gone at reboot, written again on resume. Running as root it's a system unit; otherwise a user unit, which needs cgroup delegation for CPU limits.

Several projects at once. adversary manage --config FILE runs every project in a TOML file from one process, sharing one pool, so CPU and memory shares (auto) are worked out for the machine as a whole:

pool = "auto"                      # runs at once across all projects (auto = CPU threads)
interval = 15
members = ["you@example.com"]      # kept on every project
run_args = ["--cpu-quota", "auto"]

[[project]]
name = "Website"                   # found by name, or created with its board
folder = "/srv/website"

[[project]]
id = "1887993708561827225"         # an existing project, by its 4ga id (the bot must be a project manager)
folder = "/mnt/projects/AnySite"
pool = 2                           # optional: this project's cap within the shared pool
# run_args = [...]                 # optional: replaces the shared run_args
# members = [...]                  # optional: added to the shared members

Each project keeps its own lock, so a project can't be managed by two managers at once. A project that fails (for example, an id the bot can't see) logs it once and doesn't hold up the others. Command-line flags (--pool, --member, --interval, flags after --) override the file.

Credentials. Create a dedicated bot user in 4ga, give it access to the project, and create an API client while logged in as it (Settings → API). Comments only record a user, so the bot's own comments are told from people's by its user id. Put the credentials in ~/.config/adversary/4ga.env, readable only by you (chmod 600), or pass --board-env FILE; FOURGA_* environment variables override the file:

FOURGA_URL=https://kabana.example.com
FOURGA_CLIENT_ID=...
FOURGA_CLIENT_SECRET=...

The board. The manager finds the project by name. If there's none, it creates one, then a board. It re-reads the project's boards on every pass, so boards people add later are picked up within one pass.

  • The bot joins every board as an editor. As a project manager it can see every board but can't change one it isn't a member of.
  • A new board gets the six columns: Upcoming, Suggested, Approved To Do, In Progress, Needs Feedback and Done. A new board is one with no cards and either no columns, or only the Done column 4ga's "Empty" template starts it with; that Done becomes the manager's Done.
  • A board with columns of its own gets whichever of Suggested, Approved To Do, In Progress, Needs Feedback and Done it's missing, each placed just before the next of them it has (so a Done it already has stays last). Its own columns stay where they are; the manager never moves or uses them. Upcoming is for people to think out loud in; the manager never touches it. Creating a project needs the bot to be an admin, or project creation turned on for everyone; otherwise create the project yourself and add the bot as a project manager.

A card's life.

  1. Claimed. While the pool has room, the top card in Approved To Do moves to In Progress (the manager reads it back to check it stayed). It gets a workspace and a detached run. The run's task is the card's title, description and comments so far.
  2. Worked. The card shows the whole conversation. Every message between the agents is posted on it, headed with its direction:
  3. Message from Supervisor to Worker: the plan, replies and message_worker messages.
  4. Message from Worker to Supervisor: each of the worker's turn-ends.
  5. Message from Supervisor: what it says to people (to a person, while the worker is on hold, after the run finished).
  6. Message from the bridge to Worker: what the bridge sends itself, like a merge conflict to fix.

A message over 8,000 characters is split into numbered parts, at paragraph or line breaks; a code block cut by a split is closed and reopened. 4ga itself takes comments of a million characters, so the split is for reading. Permission requests aren't posted.

People's comments are relayed to the supervisor every 15 seconds, like typing to it.

  • Attachments. Files people attach are downloaded into the run's attachments/ folder, which both agents may read (images too). Files already on the card go to the supervisor with its first message, or with the resume message on a resumed run.
  • A file attached later arrives in the same message as the comments found with it, or on its own.
  • The bot's own attachments aren't relayed, and anything over 50 MB is skipped with a note.
  • Needs Feedback. The supervisor and the worker both have request_feedback(question). It posts the question and moves the card to Needs Feedback. A person's reply closes the request (any comment counts as the answer to every open request; the supervisor is told to ask again if it doesn't) and moves the card back to I
Source 1 files
hooks/register.ts 53 lines
1import type { EngineInterface, Register } from 'claude-code'
2
3// Loaded into both supervised sessions with --plugin-dir. Whenever the prompt box
4// goes from empty to holding a draft or back, it writes {"draft": true|false, "head"}
5// to $ADVERSARY_DRAFT_FILE, `head` being the draft's first characters. The bridge
6// reads that before typing into the pane, and waits while a person has a message
7// half written; `head` tells it whether the box still holds its own message.
8
9const HEAD = 60
10let reported: string | undefined
11let writes: Promise<void> = Promise.resolve()
12
13// Writes go one after another, so an edit's report can't land after the submit's.
14function report($: EngineInterface, text: string): Promise<void> {
15  writes = writes
16    .then(async () => {
17      const head = text.slice(0, HEAD)
18      if (head === reported) return
19      const path = await $.env.get('ADVERSARY_DRAFT_FILE')
20      if (!path) return
21      await $.fs.write(path, JSON.stringify({ draft: text !== '', head, at: await $.clock.now() }))
22      reported = head
23    })
24    .catch(() => {})
25  return writes
26}
27
28async function recheck($: EngineInterface): Promise<void> {
29  const box = await $.prompt.read()
30  await report($, box.text)
31}
32
33export const register: Register = on => {
34  on('session.start', async ($, e, next) => {
35    const started = await next(e)
36    await recheck($)
37    // Catches a box emptied without an edit event (cleared with a key binding, say).
38    $.clock.every(1000, () => void recheck($))
39    return started
40  })
41
42  on('prompt.edit', async ($, e, next) => {
43    const box = await next(e)
44    void report($, box.text)
45    return box
46  })
47
48  on('prompt.submit', async ($, e, next) => {
49    void report($, '')
50    return next(e)
51  })
52}
53