Use Garry Tan's exact Claude Code setup: 23 opinionated tools that serve as CEO, Designer, Eng Manager, Release Manager, Doc Engineer, and QA
TypeScript
---
name: runaway-stopper
preamble-tier: 1
version: 0.1.0
description: |
Find runaway Capy threads and subagents, stop or rotate them safely, and prevent
repeats. Use for "find runaway threads", "stop runaway jobs", "rotate this
thread" or a token sweep. (gstack)
codex_default_prompt: "Use $runaway-stopper to scan this crew for runaway threads and subagents, stop what is safe to stop, and report the rest."
triggers:
- find runaway threads
- stop runaway jobs
- rotate this thread
- token sweep
allowed-tools:
- Bash
- Read
- Write
---
{{PREAMBLE}}
# /runaway-stopper: detect, stop, prevent
Needs Capy's thread and subagent tools; without them, say so and stop (`gstack-runaway scan` still reads saved
files). Step 1 only reads. Stop only your own subagents; only a Captain rotates and archives, and only threads in
its own crew (R39). An org sweep runs Step 1 everywhere and sends each finding to the owning Captain; threads
outside every crew are left alone. For a crew over ~15 threads or the org sweep, run Step 1 from an automation
with a fresh thread per run that sets `captain` below (it is in no crew), writes the lines to the Captain's
drive, archives itself, and messages the Captain on a ROTATE, STOP, REPORT or RUNAWAY_INPUT line.
## 1. Detect
Fetch and scan in one execute program (`timeout_seconds: 900`), so nothing large enters your context:
```js
const pages = 3; // 1 for an org sweep; empty_wake needs 20+ turns, else it prints "unmeasured"
const max = Math.floor(240 / (pages + 1)); // threads per program, under the 256-call limit
const cursor = undefined; // the previous program's NEXT_CURSOR, to continue a large sweep
const dir = "/home/user/.capy/work/runaway/" + crypto.randomUUID();
const captain = undefined; // from an automation thread: the Captain's code
const standing = []; // codes that may rotate
const list = await tools.thread.list({ ...(captain ? { captain } : { scope: "crew" }), status: ["working", "waiting", "idle"], limit: Math.min(100, max), cursor }); // org sweep: scope "all"
await tools.capy.write({ path: `${dir}/crew.json`, content: JSON.stringify({ items: list.items.map(t => t.code) }) });
const codes = [...list.items.map(t => t.code), ...(cursor ? [] : [captain ?? "this"])].slice(0, max);
const fetch = async code => {
let before, events = [], doc;
for (let k = 0; k < pages; k++) {
const { transcript, recent, ...rest } = await tools.thread.get({ thread_id: code, transcript: { limit: 100, tools: true, before } });
doc ??= rest;
events.push(...transcript.items.map(i => ({ source: i.source, tool: i.tool, createdAt: i.createdAt,
calls: i.calls?.map(c => ({ tool: c.tool })), state: String(i.input?.text ?? "").match(/"state\\?"\s*:\s*\\?"(\w+)/)?.[1],
ms: i.calls?.reduce((s, c) => s + (c.durationMs ?? 0), 0),
...(i.tool === "message_agent" ? { to: /[{,]\s*"to"\s*:\s*"/.test(i.input?.text ?? "") || (!!i.text && i.input?.chars > (i.input?.text ?? "").length) } : {}),
...(i.tool === "wait" ? { input: i.input } : {}) })));
if (!(before = transcript.beforeCursor)) break;
}
await tools.capy.write({ path: `${dir}/${doc.code}.thread.json`, content: JSON.stringify({ ...doc, events, standing: standing.includes(doc.code) }) });
};
const failed = [];
for (let k = 0; k < codes.length; k += 8) (await Promise.allSettled(codes.slice(k, k + 8).map(fetch)))
.forEach((r, j) => r.status === "rejected" && failed.push(codes[k + j]));
const scan = await tools.capy.bash({ command: `$HOME/.local/share/gstack/bin/gstack-runaway scan --dir ${dir}; s=$?; rm -rf ${dir}; exit $s`, description: "Scanning" });
return scan.output + (failed.length ? "\nFETCH_FAILED: " + failed.join(" ") : "") + (list.cursor ? "\nNEXT_CURSOR: " + list.cursor : "");
```
A lane with nested subagents can also write `tools.subagent.list()` to `<code>.subagents.json` in that directory:
it lists the whole tree, where thread.get lists 200 rows at most (`own` is then an upper bound).
Limits (org rule R70, amended 2026-11-09, token lines halved because Capy's token counts read about half from
2026-11-15): a standing thread that wakes on every event (a merge lane, a watcher, an automation's standing thread)
rotates past 250M own tokens (total minus subagents) or 3 days active (working, waiting, or a turn in the last 24
hours), warn at 200M. A crew thread keeps its PR until it merges or closes, never rotated mid-PR on a token count;
past 500M own tokens it checks in with its Captain once. Open or unknown PRs block rotation
(R91). A subagent past 50M: stop and look. Empty wakes past 25% of the
last 40 turns (warm-wait check-ins left out). Review rounds past 2 per PR. `cold_extra_spend` and `empty_spend` are the shares of spend that
cold starts (after the 5-minute cache lapsed) and empty wakes cost; `scan --wakes` prices each wake. Act on each line:
| Line | Do |
|---|---|
| `FLAG: ROTATE` | A standing thread: Step 3. |
| `FLAG: CHECK_IN` | Hear its one check-in; never rotate it. |
| `FLAG: REPORT` | A Captain over a limit: report it, never rotate it (Garry decides Captain rotation). |
| `FLAG: STOP` | Step 2. |
| `FLAG: LOOK` | A finished subagent past 50M: find why (reused for several runs? full-depth review?) and fix that cause from Step 4. |
| `FLAG: WARN` | Tell the thread the Step 4 rule it breaks, once. |
| `DEFER:` | Mid-/ship, mid-merge or holding a PR: act on nothing; rescan once that ends. |
| `RUNAWAY_INPUT:`, `FETCH_FAILED:` | That thread wasn't read: fetch it again and rerun; never count it as OK. |
No `RUNAWAY:` or `SWEEP:` line means the scan failed, never that the crew is clean. `DEFER:` holds a rotation, and
a stop of a /gstack-ship reader mid-run, or of a subagent that holds one (the run's own cap stops it); stopping any other
subagent goes ahead.
## 2. Stop a subagent
Your own: `tools.subagent.stop({ paths: ["<path>"] })`, and record the reason: "<tokens> > 50M (R70), <what it was
doing>". A crew thread's subagent: send that thread one message, "Stop Subagent <path>: <tokens> > 50M (R70)." Its
PR stays open; a fresh subagent with the run directory picks the work up if it is still needed.
## 3. Rotate a thread
Rotate only a standing thread, and only at a clean point: no `DEFER:`, no READY of that thread waiting on you, no merge in flight for its PR.
1. Tell it: "Rotation (R70). Start nothing new; stop your working and waiting subagents, or list each with its run
directory; write handoffs/<code>-rotation.md from gstack's `runaway-stopper/templates/rotation-handoff.md` and
reply with its path."
2. Start the successor in your crew from `runaway-stopper/templates/successor-brief.md` (a lane asks its Captain,
R68). Its first act subscribes to each open PR in the handoff (`tools.capy.subscribe`, a pull source), so CI,
reviews and merges wake it instead of the old thread.
3. Leave the old thread unarchived while it holds an open PR (R91); archive it once every PR merges or closes,
through `gstack-archive-check thread`.
## 4. Prevent
Put the lines that apply into every brief you write:
- **One wait.** Register one `wait` on every pending operation (`return_when: "all"` when you need them all).
Subagent completions wake you on their own: never add a wait or a poll for them.
- **Quiet wakes.** A wake with nothing to decide ends with `end_turn`. No acknowledgment, "working" or progress
message to a parent or Captain: send a READY, a decision you need, a blocker or the final report.
- **Compact returns.** A program returns only the lines the next step needs; big output goes to a file under
~/.capy/work and you read the part you need.
- **/gstack-ship runs in the PR's own thread.** The thread follows `ship/DRIVER.md` itself and starts only the reviewers as
subagents; it never starts a subagent to run /gstack-ship. Raising a brief's `--token-cap` needs the owner's words.
- **Two review rounds.** Reader and review rounds stop at 2 per PR (R51), and every reader's title names the PR
(`#<n>`) so the scan can count them.
- **Rotate standing roles** at 250M own tokens or 3 days. An automation gets a fresh thread per run that archives
itself, or a slower schedule, instead of waking a standing thread.
- **Crew threads keep their PR to the end:** no token stop mid-PR; one Captain check-in past 500M own tokens.
## Report
Paste the `RUNAWAY:`, `FLAG:`, `DEFER:`, `RUNAWAY_INPUT:` and `SWEEP:` lines verbatim, then one line per flag:
stopped (path), rotated (successor code), deferred (until what) or told (thread).