SLOPSHOPPER

ghostfleet

Reports a fleet session's exact state and budget from inside Claude Code, answers /fleet and /inbox without a turn, draws a lead's team above its prompt, and…

bandguardcommandprompttoolmodel
★ 3v0.1.0MITupdated 2026-10-24PabloG55/ghostfleet/mods/ghostfleet
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · ghostfleet
› fix the failing auth test and add an audit log call ⏺ Read(src/auth.ts) ⎿ Read 6 lines ⏺ Update(src/auth.ts) ⎿ Added 2 lines, removed 1 line ⏺ Bash(bun test) ⎿ 3 pass, 1 fail ● Done. refresh now rejects expired claims and logs an audit event. ✻ Worked for 42s · done 4:20 PM › /fleet ⎿ ghostfleet: fleet-list: this session is not in a fleet (no socket in its record or its environment). ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts
README

<img src="docs/logo-banner.svg" alt="ghostfleet" width="440">

<a href="https://www.npmjs.com/package/ghostfleet-cli"><img src="https://img.shields.io/npm/v/ghostfleet-cli?color=cb3837&label=npm" alt="npm version"></a> <a href="https://www.npmjs.com/package/ghostfleet-cli"><img src="https://img.shields.io/npm/dm/ghostfleet-cli?label=downloads" alt="npm downloads"></a> <a href="https://github.com/PabloG55/ghostfleet/actions/workflows/test.yml?query=branch%3Astaging"><img src="https://img.shields.io/github/actions/workflow/status/PabloG55/ghostfleet/test.yml?branch=staging&label=tests" alt="tests"></a> <a href="LICENSE"><img src="https://img.shields.io/github/license/PabloG55/ghostfleet" alt="MIT license"></a>

Run a fleet of Claude Code agents in parallel, from one terminal. Each agent gets its own git worktree — cut, branched, dependency-linked and booted in one keystroke — and you get one screen that shows what every one of them is doing.

A ghost fleet is a fleet of autonomous, unmanned vessels under one command — agents working with nobody in the seat, and one control plane steering them.

<img src="docs/worktree-demo.gif" width="820" alt="The Projects screen, then one project's session grid, then the new-worktree form: a name, a branch, and which agent runs it. The worktree is cut, the agent boots into it, and Projects comes back counting one more session."> <b>Start a worker.</b> <sub><code>w</code> cuts a worktree, branches it, picks which agent runs it, and boots it — you land in the session.</sub>

<img src="docs/stack-demo.gif" width="820" alt="The stack screen listing three idle workers, each ticked, then the stack open: claude, opencode and codex side by side in three panes, each with its own status bar and a border naming its project and session."> <b>Watch three at once.</b> <sub><code>claude</code>, <code>opencode</code> and <code>codex</code> side by side — every pane live and typable, across projects.</sub>

<img src="docs/mobile/phone-demo.gif" width="260" alt="On a phone: the projects list and its profile tabs, one project's grid of session cards, the actions sheet behind the header's dots, a session as a chat with bubbles and a composer being typed into, a swipe to the next session, and the live pane showing a permission prompt waiting on an answer."> <b>Unblock one from anywhere.</b> <sub>The same grid as an installable web app. A session is a chat; its <code>pane</code> tab is the real terminal, so a worker stuck on a permission prompt gets an answer from your pocket. It <b>notifies</b> when a worker is blocked or has an answer, and you can <b>send it a photo</b>.</sub>

<sub>All three recorded against a real fleet by <a href="worktree.tape"><code>worktree.tape</code></a> and <a href="stack.tape"><code>stack.tape</code></a>. Details: <a href="docs/SHORTCUTS.md">keys</a> · <a href="docs/stack-view.md">the stack</a> · <a href="web/README.md">the phone client</a>.</sub>

Why another one of these

Orchestrating agents is easy to demo and hard to trust. The parts that took real debugging — and that most wrappers get wrong:

problemwhat ghostfleet does
"is it working?" — the transcript's mtime says idle mid-generation, and busy when a background write landsreads the live pane, the same signal you read
a worker needs you, you handle it, the card stays red forevera need-you older than the session's own activity is treated as spent
every project has a session called master, so their statuses collidestatus is scoped by the fleet's socket, not by name
a dispatched prompt silently lands in the input box without submittingdispatch waits for the paste, submits, then verifies a turn actually started
one account: 5 agents drain the budget 5× faster and all stall togethera non-Claude governor meters usage and parks workers at the ceiling, resuming on reset (it can't be the lead — the lead stalls too)
one laptop: 5 agents running tests can fill the process table and wedge the machinethe same governor watches the kernel's own memory-pressure level and the process table, and parks workers before the OOM killer does
you already run agents by hand in a dozen panesfleet-adopt finds those conversations and rebuilds them as one fleet

A worktree you can actually work in

git worktree add gives you a directory. An agent needs more than that before it can do anything, and the gap is where the fiddly parts live — so fleet-spawn closes it:

why it matters
node_modules symlinked from the main checkoutthe worker can run lint, typecheck and tests on its first turn instead of waiting out an install
a dev-stack slot allocatedtwo workers don't both try to bind port 3000 and one of them silently lose
the task recorded in a manifestfleet-worktrees shows what each tree is for, which is how a lead rebuilds its map after a restart instead of guessing
reuse before createit refuses to cut a new tree while a free one is sitting there, and lists them — so the disk doesn't fill with abandoned checkouts
a session started in it, on the agent you pickeda worktree with nobody in it isn't a worker

The branch is cut from your local ref, not the remote tip, so a worker never misses work you committed but haven't pushed. And fleet-spawn refuses to run from inside a worktree: a session already in one is a leaf, and spawning there would put a second tree beside the one you're standing in rather than starting a worker.

Recycling an existing tree onto fresh work is one command — fleet-spawn <name> --reuse <worktree> --branch <new> --from <base> cleans it and checks out the new branch — which is the usual case once a fleet has been running for a while. What gets recycled is the folder, never the session: a worker that finished a task has that task all through its context, so it is retired with fleet-stop --reclaim and the next task starts a new conversation. fleet-send refuses to hand a finished, shipped worker a new brief, and says to spawn instead.

Documentation

The README is the pitch, the install and the shape of the thing. Everything you look up while using it lives in docs/, one file per question, because three reference sections had grown to 78% of this page and a README is not where you go to check a keystroke.

docs/SHORTCUTS.mdEvery key, and what answers it. Start at §0 — the handful that covers almost everything — then the exhaustive sections: inside a session, the Projects screen, the grid, the stack, the fleet-* commands, and the behaviors that are not guessable from the UI
docs/ORCHESTRATION.mdA lead session driving workers. Dispatching briefs to siblings, watching them, unblocking them, reusing worktrees before making more, and metering cost with the governor
docs/OPERATIONS.mdThe special cases. Adopting Claude sessions you started by hand, the phone client, notifications, work-vs-personal profiles, staying awake, where a worktree goes, the two ways to register a project, which fleet a worker lands on, and updating Claude Code under a live fleet
docs/mobile.md · web/README.mdThe phone client — the design argument, and the client itself
docs/jarvis.mdJarvis, one session above every fleet — experimental, off by default; fleet-experimental enable jarvis turns it on. ghostfleet jarvis, the digest it reads instead of polling, the confirm-list the tools enforce, conversation mode on the phone (transcribed on the Mac), and its fresh start once the conversation grows long
docs/stack-view.mdWhy the stack is nested attaches and not join-pane, and what was measured to find out
docs/multi-agent-sessions.mdRunning codex, opencode, agy and cursor beside claude — the measured capability matrix (hooks, MCP, skill, resume) and what picking a non-default agent costs
docs/attachments.mdSending a photo from the phone: what was measured per agent, why the bytes are converted on the Mac rather than the phone, and the two recommendations the build overturned
docs/agent-council.mdWould a second agent checking the first one's work reduce iteration? Measured against 3,494 real turns and this repo's own history: misread intent is the smallest correction category, three quarters of the rest are found by a human looking at a screen, and a browser-based verifier would have passed the bug it was built for
docs/ROADMAP.md · docs/IDEAS.mdWhat is next, and what is only an idea
CHANGELOG.mdWhat changed between releases, and whether it is a reason to upgrade
CLAUDE.mdFor working on ghostfleet: how to deploy a change, what the tests cover, and the failure modes that have bitten more than once

Prerequisites

requirementwhy
gitworktrees are the isolation model — a worker is a checkout on its own branch. fleet-spawn refuses to run without it
claude (Claude Code)what a session runs by default, and what the pane detectors are written against — missing? the installer offers Claude Code's native installer (into ~/.local/bin, no sudo)
node (v18+ to run, v20.19+ to build from a clone)the grid is a zero-npm-dependency Node TUI, and v18 runs it. The phone client is built from web/src with vite, which needs 20.19 — that applies only to a clone, because the published package ships web/ already built. Debian and Ubuntu package 18.x, so a clone there needs a newer node first; the installer checks the version up front and says which
tmuxthe hidden substrate that keeps sessions alive in the background — missing? the installer offers to install it for you (see below). With no terminal attached it has nobody to ask, so a piped or CI install prints the command instead — pass --yes there and it installs without prompting
jqthe installer wires the hooks and MCP entries with it, and the status hook parses its payload with it. macOS 26 already ships it (/usr/bin/jq); anywhere it is missing the installer offers to install it
macOS, Linux, or Windows via WSL2sessions are tmux servers, and tmux is POSIX-only — see the native-Windows note below
codex / opencode / agy / cursor-agent (optional)alternative agents, chosen per worktree on the w form. Their pane signals are detected separately — see docs/multi-agent-sessions.md
$EDITOR (optional, default nvim .)what Ctrl-n's editor tab opens. Any editor works — override with CLAUDE_FLEET_EDITOR. With neither set and no Neovim new enough for LazyVim (0.11.2+), the installer offers the official Neovim release (under ~/.local) and, only where there is no ~/.config/nvim yet, the LazyVim starter
tailscale (optional)only for the phone client, and only off-LAN: it is how fleet-serve is reachable without exposing a port — see docs/mobile.md
zellij (optional)not required, but the included layout gives you one pane that frees Ctrl-s/arrows from its own bindings
terminal-notifier + AeroSpace (optional, macOS)for clickable notifications that jump straight to the fleet — see Notifications

(Native Windows isn't supported and won't be: sessions are tmux servers, and tmux is POSIX-only. Under WSL2 it's just Linux and works the same — docs/windows.md is the whole path, from a bare Windows machine to an open fleet.)

Install

npx ghostfleet-cli          # installs, no clone needed
ghostfleet demo             # see it working, on three throwaway projects

On a fresh Linux box there is no npx to run that with. A stock Ubuntu 24.04 image ships none of node, npm, git, tmux, jq or curl — measured, not assumed — so the line above is command not found and nothing tells you which of the six is the one you need. Install them first, and the rest of this page applies unchanged:

sudo apt-get update && sudo apt-get install -y nodejs npm git tmux jq curl

(That nodejs is 18.x, which runs the fleet perfectly well. It cannot build the phone client, which matters only if you clone — see the node row above.)

ghostfleet demo is the fastest way to find out whether you want this. It creates three scratch git repos under ~/gf-demo, registers them in a separate demo profile, and opens the real control plane on them — the same screens the GIFs above were recorded against. It is additive and it never repairs: anything already there is reused and said so, and if it finds something it cannot safely reuse it stops and tells you what it found rather than guessing. Your own profiles are untouched; rm -rf ~/gf-demo ~/.config/ghostfleet/projects.demo ~/.claude-demo removes every trace.

Every screen works before you log anything in — the Projects picker, a project's session grid, the new-worktree form, the stack. What needs a login is an agent taking a turn: Claude Code keeps credentials per config dir, so the demo profile has its own, and a session you open will sit at its login prompt until you do this once:

CLAUDE_CONFIG_DIR=~/.claude-demo claude     # then /login

An empty pane before that is the login prompt, not a broken fleet.

Ready to point it at your own work? ghostfleet opens your projects — and with none registered yet it walks you through picking a folder, naming it, and starting the first session, rather than showing you an empty screen.

And put it on your phone:

fleet-phone                 # what is left to do, and the one command that does it

The same fleet as an installable app — every session as a chat, the real pane one tap away, and a notification when a worker is blocked, so a permission prompt gets answered from your pocket. fleet-phone reports which of the three steps you have done (configure, enrol a passkey, run the daemon) and prints the next one; it never runs any of them for you, because each opens a port, writes a config or spends a passkey. It reaches the phone over Tailscale — fleet-serve refuses a wildcard, a LAN address or a public one before the socket opens, because this endpoint runs commands. See docs/mobile.md for the design and the threat model.

Optional, and local only: the Mac's voice. The phone can read replies aloud with Kokoro running on your machine — better English, real Spanish, chosen sentence by sentence — instead of the phone's own voice. It is ~350 MB, so ./install.sh asks and the default is No (--yes does not answer it). Add it any time:

fleet-jarvis voice --kokoro --install   # verified download + a pinned Python 3.12 venv; re-run to repair

Without it nothing is missing: the phone reads with its own voice. fleet-phone and fleet-jarvis status say whether it is installed, not installed or broken. docs/mobile.md has the details.

Two things that cost people time, so they are in that command's output too: the passkey is enforced server-side, so until a phone is enrolled the app sits on its lock screen and the API answers 401 — and an installed iOS PWA resumed from the app switcher does not pick up a new client version. The shell is served cache-first, so reopening is a resume, not a navigation; swipe the app away and relaunch.

Prefer to clone the repo (e.g. to develop against it)?

git clone https://github.com/PabloG55/ghostfleet.git
cd ghostfleet
./install.sh                # add --verbose to watch every step

Both run the same install.sh — npx ghostfleet-cli just fetches the package and runs it for you, so nothing is left checked out afterwards. The command it installs is ghostfleet, not ghostfleet-cli: the npm package name and the binary name are separate, and only the package name had to change.

The package is ghostfleet-cli, and ghostfleet on npm is someone else's. ghostfleet@0.0.2 was published by an unrelated project ten days after this one took the name, pitched as "fleets of disposable AI agents in your own cloud" — close enough that npx ghostfleet looks right and installs a stranger's package. Nothing here can be done about that, so the suffix is load-bearing: type -cli.

Cloning is also what you want if you intend to edit ghostfleet itself: cf-sync syncs the runtime from a real repo, and an npx cache is not one.

If you already have a clone, be careful running the npx installer over it. install.sh records where to sync FROM in <runtime>/.source, and cf-sync with no argument reads it — so an installer run from an npx cache used to repoint that at the cache, after which every cf-sync in your clone copied the cache into the live runtime. Nothing errors and the sync still prints synced runtime; your edits just quietly stop arriving. The installer now keeps a recorded clone when it is running from a cache (it says so: pointer stays on your clone: …), so this only bites an older install. To fix one, do either:

cd /path/to/ghostfleet && ./install.sh    # re-install from the clone — it re-records it
cf-sync /path/to/ghostfleet               # or just repoint it once; later `cf-sync` remembers

Check it any time with cat ~/.local/libexec/ghostfleet/.source. An install run from a clone always repoints — that includes a re-install from the same clone, a moved clone, and a second clone — because the guard only fires when the copy being installed from could not serve as a sync source at all.

Missing tmux? The installer detects it, works out the right package manager for your OS (Homebrew, apt, dnf, yum, pacman, zypper, or apk), and asks before running anything — it never installs (or sudos) without you confirming. No package manager recognized, or you say no? It just tells you the command to run yourself.

Installing with no terminal (CI, a Dockerfile, curl | bash)? There is nobody to ask, so the default is to install nothing and print the command — and tmux is not optional here: a fleet session is a tmux server, so an install that skipped it leaves a grid that cannot start anything. Consent up front instead:

npx ghostfleet-cli --yes          # or: ./install.sh --yes, or CLAUDE_FLEET_YES=1

That installs the missing dependencies without prompting, using the same package manager it would have offered — sudo included on Linux, which is why it is opt-in and never the default. With --yes, an install that ends without tmux exits non-zero instead of looking successful. Without it, nothing is installed unless you say yes at the terminal.

**With npx, the flag goes after the package name.** --yes (and -y) is npx's own flag too, so npx --yes ghostfleet-cli is consumed by npm and this installer is invoked with no arguments at all — it then refuses exactly as if you had never passed it (measured on npm 11.18; it notices and says where the flag belongs, but the install still skips tmux). In a Dockerfile or a CI config, the env var is the form nothing can misparse:

ENV CLAUDE_FLEET_YES=1
RUN npx ghostfleet-cli

The installer stages the runtime — it copies bin/, hooks/, mcp/, skill/, and layouts/ out of the repo into ~/.local/libexec/ghostfleet (override with CLAUDE_FLEET_HOME) — then symlinks the commands (ghostfleet, claude-here, cf-sync, and the fleet-* helpers) into ~/.local/bin pointing at the staged copy; wires the status + notification hooks into every Claude config dir it finds (~/.claude, ~/.claude-*, backing each up), plus a PreToolUse guard that stops Claude Code's built-in EnterWorktree from walking a fleet session off its own checkout (it is appended to PreToolUse, so hooks you already have there survive); registers the fleet MCP server into each config dir's .claude.json via claude mcp add -s user (Claude Code reads MCP from .claude.json/.mcp.json, not settings.json) and once, globally, for codex, opencode, agy and cursor-agent, which keep one config each and have no per-profile equivalent (agy and cursor also get the event bridge and the skill, under ~/.gemini/config/ and ~/.cursor/; an edited ~/.cursor file keeps its original beside it as <file>.pre-ghostfleet); installs the ghostfleet-orchestrate skill; and links the zellij layout. Re-run any time; it's idempotent.

macOS guards ~/Documents, ~/Desktop, and ~/Downloads with TCC. An app that hasn't been granted Documents folder / Full Disk Access — notably ClaudeCode.app — gets Operation not permitted when it tries to execute anything stored there. So if you cloned this repo under ~/Documents, running the fleet CLI, the event hook, or the MCP server directly from the repo breaks the instant such an app hosts your session (symlinks don't help — exec follows them back into the protected folder). ~/.local is not TCC-protected, so the installer runs everything from the staged copy there and the repo stays purely for development.

After you edit the repo, run cf-sync to push those edits into the live runtime (it copies the runtime dirs from the recorded source repo into ~/.local/libexec/ghostfleet; the PATH symlinks, hook, and MCP already point there, so no re-link is needed). The alternative — granting ClaudeCode.app Full Disk Access — also works but can reset on app/OS updates; staging survives updates.

The screens

One terminal window (or one zellij pane) — ghostfleet is the whole control plane:

flowchart LR
    Projects["Projects\npick a project · + add project"] -- "⏎ enter" --> Master["Master Claude\nthe lead — spawns &\ncoordinates workers"]
    Master -- "Ctrl-s" --> Grid["The grid\napi · api-1 · api-2 …"]

` `` (backtick) always steps back exactly one level, from anywhere — session → grid → master → Projects — no matter which shortcut you took down.

  • Projects — pick a project and ⏎ drops you straight into its Master Claude. Each project has its own hidden tmux server (cf-<project>) holding its sessions.
  • Master Claude — the lead session that spawns worktrees and coordinates workers.
  • The grid — a card per Claude session (status · branch · last message), plus a card for every worktree that has no live session yet. Every session keeps running in the background, so agents work in parallel while you jump between them.
  • The stack (t from the grid) — several of those sessions on screen at the same time, in split panes, including sessions from different projects.
zellij --layout fleet attach -c fleet    # one zellij session runs everything
# or just run `ghostfleet` in any pane

What makes it different: it runs beside your setup instead of taking it over. Sessions live on per-project tmux servers ghostfleet manages for you, so you

Source 7 files
hooks/register.js 1407 lines
1// ghostfleet's mod: the fleet's view of a Claude session, from inside the session.
2//
3// Everything the fleet knew about a Claude session it learned from OUTSIDE: a regex over
4// the captured pane for "is it working" (blind at 56 columns, fooled by a leftover login
5// line, by prose that quotes a spinner), the status bar scraped for the 5h budget (gone
6// below ~100 columns, frozen on an idle pane), and a lead spending a whole turn to run
7// fleet-inbox through Bash. From in here there is nothing to guess: a turn starts, a turn
8// completes, a dialog is about to be drawn, the engine measures the account.
9//
10// Seven things, each a section below, all sharing the record I/O at the top:
11//   STATE     written into the session's status record as it changes
12//   BUDGET    the account's rate-limit windows, from the engine's own measurement
13//   COMMANDS  /fleet and /inbox, answered without a turn
14//   DELIVERY  the fleet's prompts, submitted as turns of their own
15//   GUARDS    the fleet's refusals in front of Bash and the MCP tools, failing CLOSED
16//   BAND      a lead's team above its prompt
17//   LEDGER    every request made of the session, held open until a final message answers it
18// What is written is shaped by ./shape.js, ./handoff.js, ./guard-shape.js, ./band-shape.js and ./ledger.js,
19// plain functions the suite can run with node. The engine follows `$` only into functions
20// declared in this file, never across an import, which is why the hooks are one file and not six.
21//
22// THE OBSERVERS DECIDE NOTHING, THE GUARDS DECIDE AND FAIL CLOSED. STATE, BUDGET, COMMANDS
23// and BAND only observe: a hook of theirs that throws or runs out of time is skipped and the
24// session goes on as if this were not loaded, which is exactly right for an observer, so none
25// carries a `.catch` that could refuse in its place. GUARDS is the one section whose hooks
26// refuse, and each is registered with a `.catch` that refuses too (that section says why).
27// DELIVERY acts, but only on prompts the fleet already decided to send: it refuses nothing,
28// and a failure there leaves the prompt for fleet-send to paste. LEDGER is a nag, not a
29// guard: it observes, and its one act (a single re-prompt per item) fails OPEN.
30// Nothing here touches the network. The one model call is LEDGER's judge, made only when a
31// turn left something to judge. Every file and process call is bounded
32// (IO_MS), because a `$` call in flight does not count against a hook's budget and an
33// unbounded one would hold a turn open for as long as the filesystem stalled.
34
35import {
36  withState, stateAfterTurn, usageRecord, sockOfTmux, asksAPerson,
37} from './shape.js'
38import {
39  mergesAPr, changesABoundary, isMergeTool, prSelector, boundaryOn, mergeRefusal,
40  SETTING_REFUSAL, failedClosed, answerCalls, JARVIS_TOOLS, fleetTool, callArgs, markerSock,
41  jarvisMightAct,
42} from './guard-shape.js'
43import { teamOf, latestBySlot, summarize, prSummary, bandRuns } from './band-shape.js'
44import {
45  ledgerFile, parseLedger, ledgerConfig, sourceOf, openItems, ledgerSummary,
46  soundsLikeAPromise, judgePrompt, parseVerdict, applyVerdict, gateTargets, gatePrompt,
47  markGated, closeByHand, clearOpen, listing, ledgerRuns, stampTurn, withdrawn, dropItems, turnBlocks,
48  judgeBatches, JUDGE_TOKENS, gateHold, lastGateAt, isGateTurn,
49  markInterrupted, addPrompt, closeByAgent, dropByAgent, addByAgent, contextNote, TOOL,
50  revisit, expireDormant, endsOnChoice,
51} from './ledger.js'
52import {
53  spoolOf, entryId, waiting, staleReceipts, replyOf, replyMarker, armedMarker, isTurnOf,
54} from './handoff.js'
55
56// ── the record ──────────────────────────────────────────────────────────────
57//
58// ONE RECORD, TWO WRITERS. hooks/fleet-event.sh has always written
59// <fleet dir>/<session_id>.json, and every reader (the grid, the phone, the digest,
60// fleet-list, the governor) already knows how to find it and scope it by socket. So the
61// mod MERGES its fields into that record rather than starting a file beside it, and the
62// shell hook carries them forward when it rewrites the file. A second file would be a
63// second answer to "what is this session doing", and this repo has paid for that shape
64// (two status files for one session, the stale one shadowing the live one).
65//
66// THE SHELL HOOK OWNS THE RECORD'S EXISTENCE. It resolves who the session is (the slot
67// from the pane, a renamed pane, the predecessor of a backgrounded conversation) and it
68// removes the record at SessionEnd. The mod never creates one: a patch with nothing to
69// patch does nothing. Creating it here would re-derive that identity in a second
70// language, and a write landing just after SessionEnd would resurrect an ended session
71// as a "lost" card.
72
73const IO_MS = 1500
74const HEARTBEAT_MS = 60_000
75const RUN_MS = 10_000
76
77// The fleet dir, resolved exactly as hooks/fleet-event.sh resolves it, from the same
78// environment, so the two writers can only ever be looking at the same file.
79async function fleetDir($) {
80  const explicit = await $.env.get('CLAUDE_FLEET_DIR')
81  if (explicit) return explicit
82  const cfg = await $.env.get('CLAUDE_CONFIG_DIR')
83  if (cfg) return `${cfg}/fleet`
84  return `${await $.env.get('HOME')}/.claude/fleet`
85}
86
87// Settles to what `work` settles to, or to `fallback` once `ms` has passed or `work`
88// rejected. Never rejects, never waits longer than `ms`.
89async function bounded($, work, ms, fallback) {
90  const timeout = $.clock.sleep(ms).then(() => fallback, () => fallback)
91  return Promise.race([Promise.resolve(work).catch(() => fallback), timeout])
92}
93
94async function readRecord($, file) {
95  try {
96    const rec = JSON.parse(await $.fs.read(file))
97    return rec && typeof rec === 'object' ? rec : null
98  } catch {
99    return null
100  }
101}
102
103async function ownRecord($) {
104  return readRecord($, `${await fleetDir($)}/${await $.session.id()}.json`)
105}
106
107// Patches apply one at a time, in the order asked, so a heartbeat can never land between
108// a state change's read and its write and undo it.
109let queue = Promise.resolve()
110
111// Applies `change(record)` to this session's record and writes the result atomically.
112// `change` returns the new record, or null to leave the file alone. Resolves true when a
113// write landed, false for every other outcome, failures included.
114function patchRecord($, change) {
115  const run = queue.then(() => bounded($, applyPatch($, change), IO_MS * 2, false))
116  queue = run.then(() => undefined, () => undefined)
117  return run
118}
119
120async function applyPatch($, change) {
121  const id = await $.session.id()
122  if (!id) return false
123  const dir = await fleetDir($)
124  const file = `${dir}/${id}.json`
125  const rec = await readRecord($, file)
126  if (!rec) return false
127  const next = change(rec)
128  if (!next) return false
129  // Beside the record and renamed over it, as the shell hook writes: every reader skips
130  // a record it cannot parse "because the hook writes atomically", and a torn read here
131  // would cost the shell hook every field it carries forward. The leading dot keeps the
132  // temporary file out of every `*.json` glob that reads the directory.
133  const tmp = `${dir}/.${id}.mod.tmp`
134  await $.fs.write(tmp, JSON.stringify(next))
135  const moved = await $.process.run(['mv', '-f', tmp, file], { timeoutMs: IO_MS })
136  return moved.exitCode === 0
137}
138
139// Who this session is in its fleet: the socket and slot its record carries (the shell
140// hook resolved them); failing that, the environment, unless the environment is known
141// not to be this session's.
142//
143// A BACKGROUNDED CONVERSATION RUNS UNDER SOMEBODY ELSE'S ENVIRONMENT (hooks/fleet-event.sh
144// has the measurement): its process was spawned by the config dir's daemon, carries no
145// $TMUX, and carries the CLAUDE_FLEET_* of whichever session first started that daemon.
146// With $CLAUDE_JOB_DIR set and no $TMUX the environment names nobody, and only the
147// record, which the shell hook pointed at the conversation's predecessor, may answer.
148async function identity($, rec) {
149  if (rec && rec.sock && rec.slot) return { sock: String(rec.sock), slot: String(rec.slot) }
150  const tmux = await $.env.get('TMUX')
151  const job = await $.env.get('CLAUDE_JOB_DIR')
152  if (job && !tmux) return { sock: '', slot: '' }
153  const sock = sockOfTmux(tmux) || (await $.env.get('CLAUDE_FLEET_SOCK')) || ''
154  const slot = (await $.env.get('CLAUDE_FLEET_SLOT')) || ''
155  return { sock, slot }
156}
157
158// ── STATE ───────────────────────────────────────────────────────────────────
159//
160// Written the moment it changes, with `source: "mod"`; readers prefer it over the pane
161// while the process that wrote it is alive and its heartbeat is recent
162// (lib/mod-status.mjs), and fall back to the pane regex otherwise.
163
164let pid = 0
165let state = ''
166let heartbeat = null
167
168async function setState($, next, turnId) {
169  state = next
170  const nowMs = await $.clock.now()
171  return patchRecord($, rec => withState(rec, next, { nowMs, pid, turnId }))
172}
173
174// The process this module runs in. `$.process.run` starts its child from Claude Code's
175// own process, so the child's parent is the pid a reader can probe; that is what makes
176// a crash visible at once instead of after a missed heartbeat.
177async function learnPid($) {
178  const out = await bounded($, $.process.run(['/bin/sh', '-c', 'echo $PPID'], { timeoutMs: IO_MS }), IO_MS, null)
179  const n = Number(String(out?.stdout || '').trim())
180  return Number.isInteger(n) && n > 1 ? n : 0
181}
182
183async function startState($) {
184  pid = await learnPid($)
185  // A resumed conversation's record can still say `working` from the process that died
186  // mid-turn; this process has started no turn, so say what it IS doing.
187  const turns = await bounded($, $.session.turns(), IO_MS, 0)
188  const first = turns > 0 ? 'ready' : 'idle'
189  // The shell hook's SessionStart may not have written the record yet: try once more a
190  // moment later, rather than creating it here.
191  if (!(await setState($, first))) {
192    $.clock.after(2000, () => { if (state === first) setState($, first) })
193  }
194  // A state can be right for hours (a ready session nobody talks to), so its age says
195  // nothing about whether anybody is still writing it. The heartbeat is what lets a
196  // reader tell "ready for an hour" from "the plugin was disabled an hour ago".
197  if (heartbeat) heartbeat.cancel()
198  heartbeat = $.clock.every(HEARTBEAT_MS, async () => {
199    const nowMs = await $.clock.now()
200    await patchRecord($, rec => (rec.mod && pid && rec.mod.pid === pid)
201      ? { ...rec, mod: { ...rec.mod, hb: nowMs } } : null)
202  })
203}
204
205async function onTurnStart($, e, next) {
206  currentTurn = e.turnId
207  turnsStarted++
208  await setState($, 'working', e.turnId)
209  await deliveryTurnStart($, e)
210  await ledgerTurnStart($, e)
211  return next(e)
212}
213
214// A subagent's turn completes too while the main turn runs on: only the main loop's end
215// (no agentId) ends what the session is doing.
216async function onTurnComplete($, e, next) {
217  const done = await next(e)
218  if (e.agentId === undefined) await setState($, stateAfterTurn(e.reason))
219  deliveryTurnComplete(e)
220  // Not awaited: the judge is a model call, and the turn's end must not wait on it.
221  if (e.agentId === undefined) void ledgerTurnComplete($, e, takeSteps(e)).catch(() => {})
222  return done
223}
224
225// Every step's text is passed through untouched and noted for the ledger's judge, which
226// reads the whole turn (see turnBlocks in ./ledger.js). A subagent's steps are its own.
227async function* onTurnStep($, e, next) {
228  const r = yield* next(e)
229  if (e.agentId === undefined && r && r.answer) noteStep(e.turnId, r.answer)
230  return r
231}
232
233// THE PERMISSION DIALOG, FROM THE VERDICT THAT OPENS IT. The obvious events are
234// classic.PermissionRequest and classic.Notification, and on this build neither reaches
235// a user-tier mod: the debug log reads `ghostfleet: classic.PermissionRequest bypassed by
236// cc-plugin-sec-default (tier user); beneath runs`, for both, every time. The harness
237// cannot show that (it has no such plugin above the mod), which is how a hook that
238// passed every test never fired once in a real session.
239//   `tool.check` is the engine's own decision, and an `ask` on a real call (one with a
240// tool_use_id, not a `$.tool.check` query) is the call being put to "the mode's decider".
241// In manual, accept-edits and plan mode that decider is the dialog (measured: need-you
242// within 2s of the turn starting, where the shell hook's Notification took 6). A bypass
243// session's verdict is `allow`, so it never reads as need-you.
244//   NOT HANDLED: in auto mode the decider is a classifier, so a classified call would read
245// need-you until it resolves. A hook cannot read the permission mode on this build (the
246// footer's SessionMode labels were measured empty through manual, accept-edits and plan)
247// and auto mode was not available to measure, so no guess is coded here.
248async function onToolCheck($, e, next) {
249  const verdict = await next(e)
250  if (asksAPerson(e, verdict)) await setState($, 'need-you')
251  return verdict
252}
253
254// The call the dialog was about has run (or been refused): the turn is moving again.
255// tool.call wraps the permission step and the tool, so this resolves after both.
256async function onToolCall($, e, next) {
257  const done = await next(e)
258  if (state === 'need-you') await setState($, 'working')
259  return ledgerNoteOnTool($, done)
260}
261
262// Inside SessionEnd's one short bound (1.5s for every hook together). No state is
263// written: the shell hook removed the record a moment ago, and the only job here is to
264// make sure a write that was already in flight has not put it back. So the queue is
265// drained first and the record removed after it; anything queued later finds no record
266// and, by the rule above, writes nothing.
267async function onSessionEnd($, e, next) {
268  if (e.reason !== 'clear' && heartbeat) { heartbeat.cancel(); heartbeat = null }
269  state = ''
270  await deliveryEnd($)
271  const done = await next(e)
272  await bounded($, queue, 500, null)
273  const dir = await fleetDir($)
274  await bounded($, $.process.run(['rm', '-f', `${dir}/${e.sessionId}.json`, `${dir}/.${e.sessionId}.mod.tmp`],
275    { timeoutMs: 500 }), 500, null)
276  return done
277}
278
279// ── BUDGET ──────────────────────────────────────────────────────────────────
280//
281// `session.measure` is the status bar's figure pushed rather than scraped: after each
282// main-thread turn and whenever a window moves a whole point. bin/fleet-governor reads
283// it from the record instead of the pane, which below ~100 columns carries no figure.
284
285async function onMeasure($, e, next) {
286  const nowMs = await $.clock.now()
287  await patchRecord($, rec => ({ ...rec, usage: usageRecord(e, nowMs) }))
288  return next(e)
289}
290
291// ── COMMANDS ────────────────────────────────────────────────────────────────
292//
293// A lead that wants its inbox asks the model, and the model spends a turn running
294// fleet-inbox through Bash: an API round trip, a tool call, a permission check, and a
295// wait behind whatever the lead was doing. These run the SAME commands (one copy of what
296// the inbox is and of what "seen" means) as plain processes, `immediate`, so they
297// answer mid-turn as well as at the prompt.
298//
299// THE MODEL READS THE OUTPUT: a command's `text` is a transcript row the model reads as
300// well as the person. For /inbox that is the point. Running it marks the rows seen,
301// exactly as fleet-inbox does, so if the model could not read them they would be gone
302// from the one place it looks, and the lead would act on an inbox it never saw. /fleet
303// is read for the same reason: "who is free" is the question asked right before a
304// dispatch.
305
306async function startCommands($) {
307  await bounded($, Promise.all([
308    $.command.register({ name: 'fleet', description: "This fleet's sessions and their states (no turn)", immediate: true }),
309    $.command.register({ name: 'inbox', description: 'What needs the lead, marked seen as fleet-inbox does (no turn)', immediate: true }),
310  ]), IO_MS, null)
311}
312
313// The commands ship beside the plugin: the runtime holds bin/ and mods/ side by side, so
314// the copy that answers is the one cf-sync deployed with this module, never whichever
315// fleet-inbox happens to be first on the session's PATH.
316async function runFleet($, name) {
317  const who = await identity($, await ownRecord($))
318  if (!who.sock) return { text: `${name}: this session is not in a fleet (no socket in its record or its environment).` }
319  // The identity rides in the environment as well as on -s: fleet-inbox decides WHOSE
320  // inbox to read from CLAUDE_FLEET_SLOT, and in a backgrounded conversation the
321  // inherited value is another session's.
322  const env = { CLAUDE_FLEET_SOCK: who.sock, CLAUDE_FLEET_SLOT: who.slot }
323  const argv = [`${$.plugin.root}/../../bin/${name}`, '-s', who.sock]
324  const out = await bounded($, $.process.run(argv, { env, timeoutMs: RUN_MS }), RUN_MS + 1000, null)
325  if (!out) return { text: `${name}: did not answer within ${RUN_MS / 1000}s.` }
326  const text = [out.stdout, out.stderr].map(s => String(s || '').trimEnd()).filter(Boolean).join('\n')
327  return { text: text || `${name}: (no output)` }
328}
329
330async function onFleet($) { return runFleet($, 'fleet-list') }
331async function onInbox($) { return runFleet($, 'fleet-inbox') }
332
333// ── DELIVERY ────────────────────────────────────────────────────────────────
334//
335// The fleet's prompts submitted from in here, not typed into the pane. bin/fleet-send
336// used to deliver the way a person would: paste into the input box, press Enter. Each of
337// its known failures came from standing outside: a paste glued onto a half-typed message
338// (hence the empty-composer guards and deferrals), an Enter that raced the paste and
339// never submitted ("could not confirm submit"), a prompt pasted into a busy session
340// folded into the running turn so the next Stop belonged to work nobody asked for (hence
341// arming reply-to on UserPromptSubmit). From in here it is one call, `$.prompt.submit`,
342// which leaves the person's draft alone, runs as a turn of its own, and whose turn this
343// section can name exactly.
344//
345// THE CHANNEL IS A SPOOL DIRECTORY PER SESSION, polled (./handoff.js has the layout).
346// Claude Code's cross-session messaging was the other candidate and loses on each count
347// that matters here: its sender has to be a Claude session, and fleet-send is run by a
348// shell, by codex, by opencode, by the phone server; its registry is per config dir, so a
349// lead on another profile cannot address it; it lands framed as a peer's message rather
350// than as the prompt; and one in flight when the mod reloads is gone. A file is written
351// by anything, survives a reload, a crash and a restart, and orders by name. The cost is
352// latency, one poll period at worst (POLL_MS), against a turn that takes seconds.
353//
354// EACH STEP IS A RENAME, so exactly one side owns an entry at any moment:
355//   fleet-send writes <id>.json and waits for <id>.done;
356//   this claims it (.json -> .taken) only while no turn runs, and submits it; at the
357//     turn.start whose text is that prompt it writes <id>.done with the turnId and arms
358//     the prompt's reply address, if it has one, for THAT turn;
359//   fleet-send, finding the entry unclaimed when its window closes, takes it back
360//     (.json -> .revoked) and pastes. The loser of a rename knows it lost, so a prompt is
361//     never both submitted and pasted.
362//
363// NOT HERE: the queue, and --now. A prompt for a busy session still goes to fleet-send's
364// <sock>.<slot>.queue, counted on the card and drained by the shell hook's Stop through
365// fleet-send, which hands each one here: one queue, one order, and a mod that dies with
366// prompts waiting leaves them where the shell drain finds them. --now still pastes: the
367// API runs a plugin's prompt as its own turn, once idle, and the only way into a running
368// turn is a peer's message, which the model reads as somebody else's words.
369//
370// Fails open like the rest: a section that never claims costs the sender its window,
371// then the paste it would have made anyway.
372
373const POLL_MS = 500
374// How long a claimed prompt may take to reach its turn.start before it is written off: the
375// engine runs it "once idle", and a person's own turn can put that off.
376const START_MS = 120_000
377
378let turnRunning = false
379let pending = null                         // { id, text, reply, at }: submitted, not started
380let claiming = false
381let poll = null
382let spool = ''
383let deliverSid = ''
384
385const runBounded = ($, argv, ms = IO_MS) =>
386  bounded($, $.process.run(argv, { timeoutMs: ms }), ms + 500, null)
387
388async function writeSpool($, dir, name, text) {
389  const tmp = `${dir}/.${name}.tmp`
390  await bounded($, $.fs.write(tmp, text), IO_MS, null)
391  const moved = await runBounded($, ['mv', '-f', tmp, `${dir}/${name}`])
392  return moved?.exitCode === 0
393}
394
395async function receipt($, id, fields) {
396  const nowMs = await $.clock.now()
397  await writeSpool($, spool, `${id}.done`, JSON.stringify({ id, ...fields, at: nowMs }))
398  await runBounded($, ['rm', '-f', `${spool}/${id}.taken`])
399}
400
401// One at a time, and only while idle: a prompt claimed mid-turn would sit inside the
402// engine, where fleet-send can no longer take it back and nothing shows it waiting.
403async function deliverTick($) {
404  if (claiming || pending || turnRunning || !spool) return
405  claiming = true
406  try {
407    const entries = await bounded($, $.fs.list(spool), IO_MS, null)
408    if (!entries) return
409    const nowMs = await $.clock.now()
410    const old = staleReceipts(entries, nowMs)
411    if (old.length) void runBounded($, ['rm', '-f', ...old.map(n => `${spool}/${n}`)])
412    const id = waiting(entries)[0]
413    if (!id) return
414    const took = await runBounded($, ['mv', `${spool}/${id}.json`, `${spool}/${id}.taken`])
415    if (took?.exitCode !== 0) return                     // revoked under us: it is theirs
416    const entry = await readRecord($, `${spool}/${id}.taken`)
417    if (!entry || typeof entry.text !== 'string' || !entry.text.trim()) {
418      await receipt($, id, { error: 'unreadable entry' })
419      return
420    }
421    // `kind: "nudge"`: a wake-up fleet-send was told is one (--nudge), never a request.
422    pending = { id, text: entry.text, reply: replyOf(entry), at: nowMs, nudge: entry.kind === 'nudge' }
423    // The ledger's item for it is made HERE: a plugin's own submit passes every prompt.submit
424    // hook but its own, so LEDGER's never sees it.
425    await ledgerDelivery($, pending)
426    // INTO JARVIS'S MASTER, the fleet's words are marked as the fleet's before they are
427    // submitted: the event hook that records the owner's yes runs on this submit and skips
428    // what a mark accounts for (lib/jarvis.mjs consumeDelivery). Marked here and not by the
429    // sender, because this is the session that receives, under the HOME that hook reads.
430    if (await maybeJarvis($).catch(() => false))
431      await bounded($, guardRun($, [bin($, 'fleet-jarvis'), 'delivered'], { stdin: entry.text }), GUARD_MS + 500, null)
432    // Settles once the turn started or the engine queued it; turn.start is what names the
433    // turn, so this is not awaited for that. A refusal is answered here.
434    const settled = r => (r && r.drop !== undefined ? { dropped: String(r.drop) } : null)
435    const lost = async () => { if (pending?.ledgered?.length) await ledgerUndo($, pending.ledgered) }
436    Promise.resolve($.prompt.submit({ text: entry.text, asUser: true })).then(
437      async r => { const d = settled(r); if (d && pending?.id === id) { await lost(); pending = null; await receipt($, id, d) } },
438      async err => { if (pending?.id === id) { await lost(); pending = null; await receipt($, id, { error: String(err?.message || err) }) } })
439  } finally {
440    claiming = false
441  }
442}
443
444// THE REPLY ADDRESS, ARMED BY THE TURN ITSELF. hooks/fleet-event.sh relays the answer on
445// the Stop of an armed address, and for a pasted prompt arms it on the next
446// UserPromptSubmit, which is right only if that submit was this prompt. Here the turn is
447// known: the address is written and armed together at its turn.start, with the transcript
448// offset (the relay reads the answer from after it) and the turnId, which tells the hook
449// not to re-arm on a prompt somebody types into this turn.
450async function armReply($, reply, turnId) {
451  const dir = await fleetDir($)
452  const rec = await readRecord($, `${dir}/${deliverSid}.json`)
453  if (!rec || !rec.sock || !rec.slot) return
454  let lines = 0
455  if (rec.transcript) {
456    const wc = await runBounded($, ['wc', '-l', String(rec.transcript)])
457    lines = Number(String(wc?.stdout || '').trim().split(/\s+/)[0]) || 0
458  }
459  const base = `${rec.sock}.${rec.slot}.reply-to`
460  await writeSpool($, dir, base, replyMarker(reply))
461  await writeSpool($, dir, `${base}.armed`, armedMarker(lines, turnId))
462}
463
464// The turn the claimed prompt started is the first main-loop turn.start carrying its text.
465// One that starts first with other text (a person typing in the same second) is theirs,
466// and the prompt goes on waiting for its own.
467async function deliveryTurnStart($, e) {
468  turnRunning = true
469  const p = pending
470  if (isTurnOf(p, e.text)) {
471    pending = null
472    await bounded($, (async () => {
473      if (p.reply) await armReply($, p.reply, e.turnId)
474      await receipt($, p.id, { turnId: e.turnId })
475      // Recorded at its prompt.submit when that hook saw it (so its note could name it);
476      // stamped with its turn here. A nudge is never an item.
477      if (p.ledgered) await stampItems($, p.ledgered, e.turnId)
478      if (p.ledgered && p.ledgered.length) noteDue = e.turnId
479      else if (!p.nudge) await ledgerFleetItem($, p.text, e.turnId)
480    })(), IO_MS * 4, null)
481  } else if (p && (await $.clock.now()) - p.at > START_MS) {
482    pending = null
483    await bounded($, receipt($, p.id, { error: 'its turn never started' }), IO_MS * 2, null)
484  }
485}
486
487function deliveryTurnComplete(e) {
488  if (e.agentId === undefined) turnRunning = false
489}
490
491async function deliveryStart($) {
492  await bounded($, (async () => {
493    const sid = await $.session.id()
494    if (!sid || !pid) return
495    const dir = spoolOf(await fleetDir($), sid)
496    await runBounded($, ['mkdir', '-p', dir])
497    // A claim an earlier process of this conversation made and never finished goes back,
498    // so the next tick delivers it instead of leaving it stranded as `.taken`.
499    for (const t of (await bounded($, $.fs.list(dir), IO_MS, null)) || []) {
500      const id = t && t.kind === 'file' ? entryId(t.name, '.taken') : null
501      if (id) await runBounded($, ['mv', '-n', `${dir}/${id}.taken`, `${dir}/${id}.json`])
502    }
503    spool = dir
504    deliverSid = sid
505    pending = null
506    turnRunning = false
507    await writeSpool($, dir, '.ready', `${pid}\n`)
508    if (poll) poll.cancel()
509    poll = $.clock.every(POLL_MS, () => { void deliverTick($) })
510  })(), IO_MS * 6, null)
511}
512
513// The spool stays (a prompt in it is somebody's); only this process's claim on it ends.
514async function deliveryEnd($) {
515  if (poll) { poll.cancel(); poll = null }
516  const dir = spool
517  spool = ''
518  deliverSid = ''
519  if (dir) await bounded($, $.process.run(['rm', '-f', `${dir}/.ready`], { timeoutMs: 400 }), 450, null)
520}
521
522// ── wiring ──────────────────────────────────────────────────────────────────
523
524async function onSessionStart($, e, next) {
525  const started = await next(e)
526  await startState($)
527  await startCommands($)
528  await ledgerStart($)
529  startBand($)
530  await deliveryStart($)
531  return started
532}
533
534/** @type {import('claude-code').Register} */
535export const register = on => {
536  on('session.start', onSessionStart)
537  on('turn.start', onTurnStart)
538  on('turn.step', onTurnStep)
539  on('turn.complete', onTurnComplete)
540  on('tool.check', onToolCheck)
541  on('tool.call', onToolCall)
542  on('session.end', onSessionEnd)
543  on('session.measure', onMeasure)
544  on('command.run', { command: 'fleet' }, onFleet)
545  on('command.run', { command: 'inbox' }, onInbox)
546  // GUARDS and BAND, below the wiring so each is one section of its own.
547  on('tool.call', { tool: 'Bash' }, onBash).catch(bashFailedClosed)
548  on('tool.call', { tool: /^mcp__/ }, onMcp).catch(mcpFailedClosed)
549  on('ui.render', { component: 'AbovePrompt' }, onBandRender)
550  on('prompt.submit', onPromptSubmit)
551  on('command.run', { command: 'ledger' }, onLedgerCommand)
552  // Spelled out, not TOOL.*: `claude plugin validate` reads a matcher only from its literal.
553  on('tool.call', { tool: 'mcp__ghostfleet__ledger_close' }, onLedgerTool)
554  on('tool.call', { tool: 'mcp__ghostfleet__ledger_drop' }, onLedgerTool)
555  on('tool.call', { tool: 'mcp__ghostfleet__ledger_add' }, onLedgerTool)
556}
557
558// ── GUARDS ──────────────────────────────────────────────────────────────────
559//
560// The fleet's refusals, in front of the tool, from inside the session.
561//
562// Until the mod, each of these was a shell hook or a check inside a command, and each could
563// only fail OPEN: a PreToolUse hook that cannot find jq exits 0 and the call goes on, which
564// is right for a hook that must never break a session and wrong for one whose whole job is
565// to say no. Here every guard is a `tool.call` hook registered with a `.catch` that refuses:
566// a hook that throws, answers a wrong shape, or outlasts its budget DENIES the call. An
567// observer (register.js) fails open; a guard fails closed.
568//
569//   JARVIS          the confirm-list (docs/jarvis.md): merge/push, stop/reclaim/force,
570//                   worktree and project removal, answering a worker's prompt, a second
571//                   worker per request. Bash and the ghostfleet MCP tools.
572//   MERGE           a worker does not merge its own PR, nor change its own boundaries
573//                   ("workers can merge", hooks/fleet-guard.sh). Bash and merge_pull_request.
574//   APPROVE         an agent does not approve another agent's tool call ("agents can approve
575//                   tool calls", bin/fleet-answer). fleet-answer in Bash and fleet_answer.
576//
577// ONE RULE, ASKED FROM HERE. Jarvis's proposals live behind a lock three processes share,
578// and fleet-answer reads a pane to decide; neither is something to write twice. So those two
579// ask the code that already decides (lib/mod-gate.mjs, `fleet-answer --check`) as a process,
580// and refuse on anything that is not a clear answer. The merge guard's rule is small enough
581// to hold here (./guard-shape.js, plain functions the suite runs with node) and its facts come from git, tmux, the fleet dir and gh.
582//
583// THE SHELL VERSIONS STAY, for every session without the mod: another agent, an older
584// Claude, an organization that blocks mods. Where both run, they agree: the shell guard
585// refuses what this refuses, and Jarvis's gate leaves a single-use relay so the door behind
586// this one passes the call the owner said yes to instead of spending his yes a second time.
587//
588// THE COST, for the call that is none of these. Every Bash call in every session comes
589// through the Bash hook, so it decides from the command text first: no process, no file,
590// unless the text could be a merge, a boundary write or a fleet-answer, or the session is
591// Jarvis's master (one small file read).
592
593const GUARD_MS = 15_000
594
595// A process call that rejects rather than settling to a fallback: a guard that could not
596// learn a fact refuses, and the throw is how it gets to the `.catch` that does. The bound is
597// the call's own timeout (it rejects), not a $.clock.sleep race: time inside $.process.run
598// is not the hook's, while a sleep's is, and a hook that outruns its 10s is skipped.
599async function guardRun($, argv, init = {}) {
600  const out = await $.process.run(argv, { ...init, timeoutMs: init.timeoutMs || GUARD_MS })
601  return { code: out.exitCode, out: String(out.stdout || ''), err: String(out.stderr || '') }
602}
603
604const bin = ($, name) => `${$.plugin.root}/../../bin/${name}`
605const lib = ($, name) => `${$.plugin.root}/../../lib/${name}`
606
607// ── JARVIS ──────────────────────────────────────────────────────────────────
608
609async function jarvisDir($) {
610  return (await $.env.get('CLAUDE_FLEET_JARVIS_DIR')) || `${await $.env.get('HOME')}/.config/ghostfleet`
611}
612
613// Is this session Jarvis's master? Cheaply, from the marker and the session's own
614// identity; lib/mod-gate.mjs asks again from the live $TMUX, exactly as the MCP door does,
615// so this only decides whether to ask at all. No marker is no Jarvis, as in the shell guard.
616// `command`, for a Bash call: also whether the confirm-list could act on it at all.
617async function maybeJarvis($, command) {
618  const dir = await jarvisDir($)
619  const file = `${dir}/jarvis`
620  if (!(await $.fs.exists(file))) return false
621  // Switched off (lib/jarvis.mjs enabled) is no Jarvis: nothing to ask the gate, which would
622  // otherwise refuse — it fails closed — on behalf of a Jarvis that is not there.
623  if (await $.fs.exists(`${file}.enabled`) && /^\s*off\s*$/.test(await $.fs.read(`${file}.enabled`))) return false
624  const sock = markerSock(await $.fs.read(file))
625  if (!sock) return false
626  if (command !== undefined && !jarvisMightAct(command, sock, dir)) return false
627  const who = await identity($, await ownRecord($))
628  return who.sock === sock && (!who.slot || who.slot === 'master')
629}
630
631// 0 = go, 2 = refused; anything else is no answer, which throws.
632async function askGate($, argv, stdin) {
633  const r = await guardRun($, ['node', lib($, 'mod-gate.mjs'), ...argv], { stdin })
634  if (r.code === 0) return { ok: true, granted: /\bgranted\b/.test(r.out) }
635  if (r.code === 2) return { ok: false, text: r.err.trim() }
636  throw new Error(`lib/mod-gate.mjs ${argv[0]} exited ${r.code}: ${r.err.trim().slice(0, 300)}`)
637}
638
639// ── MERGE ───────────────────────────────────────────────────────────────────
640
641// git -C dir rev-parse …: the value, or null when dir is not in a repository at all. Any
642// other failure (git missing, a timeout, a broken repo) throws.
643async function gitIn($, dir, args) {
644  const r = await guardRun($, ['git', '-C', dir, ...args])
645  if (r.code === 0) return r.out.trim()
646  if (/not a git repository|cannot change to|No such file/i.test(r.err)) return null
647  throw new Error(`git ${args.join(' ')} in ${dir}: ${r.err.trim().slice(0, 200)}`)
648}
649
650async function isLinked($, dir) {
651  if (!dir) return false
652  const gd = await gitIn($, dir, ['rev-parse', '--path-format=absolute', '--git-dir'])
653  if (gd === null) return false
654  const gcd = await gitIn($, dir, ['rev-parse', '--path-format=absolute', '--git-common-dir'])
655  return Boolean(gd && gcd && gd !== gcd)
656}
657
658// The registered project a checkout belongs to, as hooks/fleet-guard.sh registered_project
659// finds it: ~/.config/ghostfleet/projects and projects.<profile>, physical paths both sides.
660async function registeredProject($, gitroot) {
661  const dir = `${await $.env.get('HOME')}/.config/ghostfleet`
662  if (!(await $.fs.exists(dir))) return ''
663  const files = (await $.fs.list(dir)).map(f => f.name).filter(n => n === 'projects' || /^projects\.[A-Za-z0-9_-]+$/.test(n))
664  const home = await $.env.get('HOME')
665  for (const f of files) {
666    for (const line of (await $.fs.read(`${dir}/${f}`)).split('\n')) {
667      if (/^\s*#/.test(line)) continue
668      const [name, raw] = line.split('\t')
669      if (!name || !raw) continue
670      let root = raw.replace(/^~/, home).replace(/\/$/, '')
671      const phys = await guardRun($, ['/bin/sh', '-c', 'cd "$1" 2>/dev/null && pwd -P', 'sh', root])
672      if (phys.code === 0 && phys.out.trim()) root = phys.out.trim()
673      if (gitroot === root || gitroot.startsWith(`${root}/`)) return name
674    }
675  }
676  return ''
677}
678
679// The sessions whose <sock>.<child>.parent marker names `me`, and their branches.
680async function childBranches($, dir, sock, me) {
681  const kids = []
682  for (const f of await $.fs.list(dir)) {
683    if (!f.name.startsWith(`${sock}.`) || !f.name.endsWith('.parent')) continue
684    const parent = (await $.fs.read(`${dir}/${f.name}`)).split('\n')[0].trim()
685    if (parent === me) kids.push(f.name.slice(sock.length + 1, -'.parent'.length))
686  }
687  let manifest = ''
688  try { manifest = await $.fs.read(`${dir}/${sock}.manifest.tsv`) } catch {}
689  const branches = []
690  for (const k of kids) {
691    let b = ''
692    for (const line of manifest.split('\n')) {
693      const c = line.split('\t')
694      if (c[1] === k && c[2]) { b = c[2]; break }
695    }
696    if (!b) {
697      const p = await guardRun($, ['tmux', '-L', sock, 'display-message', '-p', '-t', k, '#{pane_current_path}'])
698      if (p.code === 0 && p.out.trim()) b = (await gitIn($, p.out.trim(), ['rev-parse', '--abbrev-ref', 'HEAD'])) || ''
699    }
700    if (b) branches.push(b)
701  }
702  return branches
703}
704
705// null = not this guard's business; otherwise { deny } or { ok }.
706async function mergeGuard($, e) {
707  const bash = e.tool === 'Bash'
708  const kind = !bash ? 'merge' : mergesAPr(e.command) ? 'merge' : changesABoundary(e.command) ? 'setting' : ''
709  if (!kind) return null
710  const cwd = await $.session.cwd()
711  const root = await $.session.root()
712  const gitroot = await gitIn($, cwd, ['rev-parse', '--show-toplevel'])
713  if (gitroot === null) return null                    // not a repo: nothing here to protect
714  // Is there a fleet here at all? Inside one, or beside a registered project's live one.
715  const who = await identity($, await ownRecord($))
716  let sock = who.sock
717  if (!sock) {
718    const proj = await registeredProject($, gitroot)
719    if (!proj) return null
720    if ((await guardRun($, ['tmux', '-L', `cf-${proj}`, 'list-sessions'])).code !== 0) return null
721    sock = `cf-${proj}`
722  }
723  // From the directory it was started in as well as the one it is in now, so a `cd` into
724  // the main checkout is not a way round it. The main checkout is the lead's: it merges.
725  const where = (await isLinked($, cwd)) ? cwd : (await isLinked($, root)) ? root : ''
726  if (!where) return null
727  if (kind === 'setting') return { deny: SETTING_REFUSAL }
728  const branch = (await gitIn($, where, ['rev-parse', '--abbrev-ref', 'HEAD'])) || ''
729  const dir = await fleetDir($)
730  const pane = await $.env.get('TMUX_PANE')
731  let sess = ''
732  if (pane) {
733    const r = await guardRun($, ['tmux', '-L', sock, 'display-message', '-p', '-t', pane, '#{session_name}'])
734    if (r.code === 0) sess = r.out.trim()
735  }
736  sess = sess || who.slot || (await $.env.get('CLAUDE_FLEET_SLOT')) || ''
737  const markers = new Set((await $.fs.list(dir)).map(f => f.name))
738  if (boundaryOn('workers-merge', sock, sess, n => markers.has(n))) return { ok: true }
739  // A SUB-LEAD MERGES ITS CHILDREN'S PRs INTO ITS OWN BRANCH (hooks/fleet-guard.sh says
740  // why): base = this session's branch AND head = one of its children's branches. Asked of
741  // GitHub; any failure to learn them refuses.
742  if (sess && branch && !markers.has(`${sock}.${sess}.parent`) && !markers.has(`${sock}.${sess}.workers-merge-off`)) {
743    const kids = await childBranches($, dir, sock, sess)
744    if (kids.length) {
745      const { sel, repo } = bash ? prSelector(e.command) : { sel: String(e.pullNumber ?? e.pull_number ?? ''), repo: '' }
746      const r = await guardRun($, ['gh', 'pr', 'view', ...(sel ? [sel] : []), ...(repo ? ['-R', repo] : []),
747        '--json', 'baseRefName,headRefName', '-q', '.baseRefName + "\\t" + .headRefName'], { cwd: where })
748      const [base, head] = r.out.trim().split('\t')
749      if (r.code === 0 && base === branch && head && kids.includes(head)) return { ok: true }
750    }
751  }
752  return { deny: mergeRefusal(where, branch, sock, sess) }
753}
754
755// ── APPROVE ─────────────────────────────────────────────────────────────────
756
757// fleet-answer's own decision for each fleet-answer the command runs. A command whose
758// words cannot be known from here (answerCalls null) is left to fleet-answer itself, which
759// still decides when the command runs: that is today's behaviour, not a gap this opens.
760async function answerGuardBash($, e) {
761  if (!/fleet-answer/.test(e.command)) return null
762  const calls = answerCalls(e.command)
763  if (!calls || !calls.length) return null
764  for (const argv of calls) {
765    const r = await guardRun($, [bin($, 'fleet-answer'), '--check', ...argv], { cwd: await $.session.cwd() })
766    if (r.code === 0 || r.code === 1) continue
767    if (r.code === 3 || r.code === 4) return { deny: r.err.trim() }
768    throw new Error(`fleet-answer --check exited ${r.code}: ${r.err.trim().slice(0, 300)}`)
769  }
770  return null
771}
772
773// ── the hooks ───────────────────────────────────────────────────────────────
774
775async function onBash($, e, next) {
776  // Jarvis first, as its hook is the first door today: a refused proposal ends it there.
777  if (await maybeJarvis($, e.command)) {
778    const g = await askGate($, ['jarvis-bash'], e.command)
779    if (!g.ok) return { deny: g.text }
780  }
781  const merge = await mergeGuard($, e)
782  if (merge && merge.deny) return { deny: merge.deny }
783  const answer = await answerGuardBash($, e)
784  if (answer && answer.deny) return { deny: answer.deny }
785  return next(e)
786}
787
788async function onMcp($, e, next) {
789  if (isMergeTool(e.tool)) {
790    const merge = await mergeGuard($, e)
791    if (merge && merge.deny) return { deny: merge.deny }
792    return next(e)
793  }
794  const name = fleetTool(e.tool)
795  if (!JARVIS_TOOLS.has(name)) return next(e)
796  const a = callArgs(e)
797  let granted = false
798  if (await maybeJarvis($)) {
799    const g = await askGate($, ['jarvis-mcp', name], JSON.stringify(a))
800    if (!g.ok) return { deny: g.text }
801    granted = g.granted
802  }
803  // The owner's yes to a fleet_answer IS the human approval: the MCP door adds
804  // --human-approved for exactly that call, so asking fleet-answer without it would refuse
805  // what he just said yes to.
806  if (name === 'fleet_answer' && !granted) {
807    const g = await askGate($, ['answer-mcp'], JSON.stringify(a))
808    if (!g.ok) return { deny: g.text }
809  }
810  return next(e)
811}
812
813// A guard that throws refuses. Where it had already called `next`, the call it judged has
814// run, and replaying that answer is the only honest thing left (the engine runs nothing
815// twice); every guard here judges before it calls `next`. A re-entry (the call raised
816// beneath one of this hook's own `$` calls) was judged by nobody, and is refused too.
817function whyFailed(next) {
818  const err = next.error || {}
819  return err.message || (err.kind === 're-entry' ? 'it was raised beneath the guard\'s own call' : err.kind) || 'the guard failed'
820}
821function bashFailedClosed($, e, next) {
822  return next.called ? next(e) : { deny: failedClosed('this command', whyFailed(next)) }
823}
824function mcpFailedClosed($, e, next) {
825  return next.called ? next(e) : { deny: failedClosed('this call', whyFailed(next)) }
826}
827
828// ── BAND ────────────────────────────────────────────────────────────────────
829//
830// A lead's team at a glance, above its prompt, without a turn.
831//
832// A lead asks "who needs me" by running fleet-inbox, or now /fleet: a question it has to
833// think to ask, in a session whose attention is on whatever it was doing. The band says it
834// without being asked, in one line above the prompt:
835//
836//     3 workers · 1 working · 1 need you · 2 PRs green
837//
838// Only for a LEAD: the session named `master` on its fleet socket, or a worker with children
839// (a sub-lead: some <sock>.<child>.parent names it). A worker without children draws nothing,
840// and a worker becomes a sub-lead's band the tick after its first child appears.
841//
842// CHEAP BY CONSTRUCTION. Nothing here starts a turn or calls a model. Every TICK_MS the
843// session lists its fleet dir (one directory read, which is all a non-lead ever does) and, a
844// lead only, asks tmux which sessions are alive and reads the records it has not read at
845// that mtime. PRs are GitHub's to say, so a lead asks `gh` every PR_MS, bounded, and says
846// `PRs ?` when it cannot. The band redraws only when what it says changes ($.state).
847//
848// An observer, like STATE above: a tick that fails leaves the band as it was,
849// and a draw that fails is skipped and the engine draws its own (nothing, for this band).
850
851const BAND_TICK_MS = 5_000
852const BAND_PR_MS = 120_000
853const GH_MS = 15_000
854
855// The one value the band draws, declared in ../types/index.d.ts.
856const BAND = /** @type {const} */ ({ plugin: 'ghostfleet', key: 'band' })
857
858let bandTick = null
859let prTick = null
860let lead = null          // { sock, me, team } while this session is a lead
861let prs                  // undefined: not read yet; null: could not; else the summary
862const seen = new Map()   // record file -> { mtimeMs, rec }
863
864const soon = ($, work, fallback, ms = IO_MS) => bounded($, work, ms, fallback)
865
866async function aliveSessions($, sock) {
867  const out = await soon($, $.process.run(['tmux', '-L', sock, 'list-sessions', '-F', '#{session_name}'], { timeoutMs: IO_MS }), null)
868  if (!out || out.exitCode !== 0) return null
869  return String(out.stdout || '').split('\n').map(s => s.trim()).filter(Boolean)
870}
871
872async function readTeamRecords($, dir, entries) {
873  const recs = []
874  for (const f of entries) {
875    if (f.kind !== 'file' || !f.name.endsWith('.json') || f.name.startsWith('.')) continue
876    const file = `${dir}/${f.name}`
877    const had = seen.get(file)
878    if (had && had.mtimeMs === f.mtimeMs) { recs.push(had.rec); continue }
879    let rec = null
880    try { rec = JSON.parse(await $.fs.read(file)) } catch {}
881    seen.set(file, { mtimeMs: f.mtimeMs, rec })
882    recs.push(rec)
883  }
884  for (const k of seen.keys()) if (!entries.some(f => `${dir}/${f.name}` === k)) seen.delete(k)
885  return recs
886}
887
888async function childrenOf($, dir, entries, sock, me) {
889  const kids = []
890  for (const f of entries) {
891    if (!f.name.startsWith(`${sock}.`) || !f.name.endsWith('.parent')) continue
892    const parent = await soon($, $.fs.read(`${dir}/${f.name}`), '')
893    if (String(parent).split('\n')[0].trim() === me) kids.push(f.name.slice(sock.length + 1, -'.parent'.length))
894  }
895  return kids
896}
897
898async function publish($, value) {
899  const cur = await soon($, $.state.get(BAND), null)
900  if (JSON.stringify(cur && cur.value) === JSON.stringify(value)) return
901  await soon($, $.state.set(BAND, value), null)
902}
903
904async function refresh($) {
905  const who = await identity($, await ownRecord($))
906  if (!who.sock || !who.slot) { lead = null; return publish($, null) }
907  const dir = await fleetDir($)
908  const entries = await soon($, $.fs.list(dir), null)
909  if (!entries) return
910  const kids = who.slot === 'master' ? [] : await childrenOf($, dir, entries, who.sock, who.slot)
911  if (who.slot !== 'master' && !kids.length) { lead = null; return publish($, null) }
912  const alive = await aliveSessions($, who.sock)
913  if (!alive) return
914  const team = teamOf(who.slot, alive, kids)
915  if (!team) { lead = null; return publish($, null) }
916  const wasLead = lead !== null
917  lead = { sock: who.sock, me: who.slot, team, dir }
918  if (!wasLead) refreshPrs($).catch(() => {})
919  const bySlot = latestBySlot(await readTeamRecords($, dir, entries), who.sock)
920  const s = summarize(team, bySlot, await $.clock.now())
921  await publish($, { ...s, prs })
922}
923
924async function refreshPrs($) {
925  if (!lead) return
926  const { me, dir, sock } = lead
927  const cwd = await $.session.cwd()
928  const out = await soon($, $.process.run(['gh', 'pr', 'list', '--state', 'open', '--limit', '100',
929    '--json', 'number,headRefName,baseRefName,statusCheckRollup'], { cwd, timeoutMs: GH_MS }), null, GH_MS + 1000)
930  let list = null
931  try { if (out && out.exitCode === 0) list = JSON.parse(String(out.stdout || '[]')) } catch {}
932  if (!Array.isArray(list)) { prs = null; return refresh($) }
933  let branch = ''
934  if (me !== 'master') {
935    const b = await soon($, $.process.run(['git', 'rev-parse', '--abbrev-ref', 'HEAD'], { cwd, timeoutMs: IO_MS }), null)
936    branch = b && b.exitCode === 0 ? String(b.stdout).trim() : ''
937  }
938  const manifest = String(await soon($, $.fs.read(`${dir}/${sock}.manifest.tsv`), ''))
939  const fleetBranches = manifest.split('\n').map(l => l.split('\t')[2]).filter(Boolean)
940  prs = prSummary(list, { me, branch, fleetBranches })
941  return refresh($)
942}
943
944// The team's row, then the ledger's (LEDGER, below), each only when it has something to say.
945async function onBandRender($, e, next) {
946  if (e.props.hasSurvey) return next(e)
947  const { value } = await $.state.get(BAND)
948  const team = value ? bandRuns(value, value.prs, e.props.bodyColumns) : null
949  const led = (await $.state.get(LEDGER)).value
950  const book = led ? ledgerRuns(led, led.asOf, e.props.bodyColumns) : null
951  if (!team && !book) return next(e)
952  const { Box, Text } = $.ui.resolve(e)
953  const row = (runs, k) => h(Box, { key: k, flexDirection: 'row' },
954    ...runs.map((r, i) => h(Text, {
955      key: String(i), wrap: 'truncate-end',
956      ...(r.color ? { color: r.color } : {}), ...(r.dim ? { dimColor: true } : {}), ...(r.bold ? { bold: true } : {}),
957    }, r.text)))
958  return h(Box, { flexDirection: 'column' }, ...(team ? [row(team, 'team')] : []), ...(book ? [row(book, 'ledger')] : []))
959}
960
961// Started from onSessionStart (one session.start hook per module), after the record exists.
962function startBand($) {
963  if (bandTick) bandTick.cancel()
964  if (prTick) prTick.cancel()
965  refresh($).catch(() => {})
966  bandTick = $.clock.every(BAND_TICK_MS, () => { refresh($).catch(() => {}); ledgerRefresh($).catch(() => {}) })
967  prTick = $.clock.every(BAND_PR_MS, () => { refreshPrs($).catch(() => {}) })
968}
969
970// ── LEDGER ──────────────────────────────────────────────────────────────────
971//
972// Every request made of this session, held open until a final message answers it.
973//
974// A person types three messages while a turn runs; the prompt tells the model to treat each
975// as queued work and never to end a turn with one neither done nor reported not-done. That
976// instruction is dropped often enough to matter, and nothing outside the model could see it
977// happen: the second message's answer is simply never written, and the person finds out
978// when they go looking. So does "I'll merge when it's green", said once and never done.
979// From in here both are visible: `prompt.submit` sees every message the moment Enter is
980// pressed (with the turn it was typed over), `turn.step` sees the text of every step of a
981// turn, and `turn.complete` sees how it ended.
982//
983//   RECORD   each request an item in <fleet dir>/<session_id>.ledger (./ledger.js has the
984//            shape), its open count in the status record (`ledger`), the oldest on the band
985//   JUDGE    at a main-loop turn.complete that ended with an answer, a small-model call per
986//            ten open items (when something is open, or the answer sounds like a promise):
987//            which open items the turn's text, all of it, addressed, and what its final text
988//            promised. A promise kept open through five judged turns closes as stale
989//   GATE     items still open after that get ONE re-prompt, ever, naming them; never an
990//            item the turn reported in progress, and never at all at the end of a turn the
991//            gate itself started, one that ends on a question to the person, one inside the
992//            cooldown, or a lead's while its workers are still at it (gateHold)
993//
994// A NAG, NOT A GUARD. It fails OPEN everywhere: a judge that errors, times out or answers
995// a wrong shape closes nothing and re-prompts nothing (the item stays open, the failure is
996// noted in the file and the debug log). It never gates a turn the person interrupted, a
997// subagent's run, a headless (-p) session, or after a queued message has already started
998// the next turn (that turn's own end is judged instead). The loop bound is in the data,
999// not in a counter that a reload would reset: an item carries `gated` once it has been
1000// re-prompted, and a gated item is never re-prompted again.
1001//
1002// Not retroactive: only messages submitted after the mod loaded. The judge runs after
1003// turn.complete has resolved, never inside it, so the turn's end never waits on a model.
1004
1005const LEDGER = /** @type {const} */ ({ plugin: 'ghostfleet', key: 'ledger' })
1006const JUDGE_MS = 30_000
1007
1008let ledgerCfg = null
1009let ledgerQueue = Promise.resolve()
1010let currentTurn = ''
1011let judging = false
1012let judgeNext = null     // a turn.complete that arrived while the judge was busy
1013let turnsStarted = 0     // main-loop turn.starts, so a verdict can tell it went stale
1014let answers = []         // the last few judged turns: { at, turnId, blocks }
1015let stepTexts = new Map() // turnId -> the text each of its main-loop steps wrote, in order
1016let ledgerShown = ''     // what the band and the record last said
1017let ledgerAsOf = 0
1018let gateTurns = []       // the last few turns the gate's own re-prompt started
1019let choiceTurn = ''      // the last turn, when it ended on a numbered question (ledger.js foldReply)
1020
1021async function ledgerConfigOf($) {
1022  if (ledgerCfg) return ledgerCfg
1023  // Each name spelled out: the engine lists what a module reads from its literal names.
1024  const env = {
1025    CLAUDE_FLEET_LEDGER: await bounded($, $.env.get('CLAUDE_FLEET_LEDGER'), IO_MS, undefined),
1026    CLAUDE_FLEET_LEDGER_GATE: await bounded($, $.env.get('CLAUDE_FLEET_LEDGER_GATE'), IO_MS, undefined),
1027    CLAUDE_FLEET_LEDGER_PROMISES: await bounded($, $.env.get('CLAUDE_FLEET_LEDGER_PROMISES'), IO_MS, undefined),
1028    CLAUDE_FLEET_LEDGER_MODEL: await bounded($, $.env.get('CLAUDE_FLEET_LEDGER_MODEL'), IO_MS, undefined),
1029  }
1030  ledgerCfg = ledgerConfig(k => env[k])
1031  return ledgerCfg
1032}
1033
1034async function ledgerPath($) {
1035  const sid = await $.session.id()
1036  return sid ? ledgerFile(await fleetDir($), sid) : ''
1037}
1038
1039// A missing file is an empty ledger; one that could not be read (a stall, a permission) is
1040// null, and a change against null is skipped: written over, it would wipe the history.
1041const UNREAD = Symbol('unread')
1042async function readLedger($, file) {
1043  const text = await bounded($, (async () => ((await $.fs.exists(file)) ? $.fs.read(file) : ''))(), IO_MS, UNREAD)
1044  return text === UNREAD ? null : parseLedger(text)
1045}
1046
1047// One change at a time, read-modify-write against the FILE, never a copy held here:
1048// fleet-ledger closes items from outside, and a copy would undo it on the next write.
1049function changeLedger($, change) {
1050  const run = ledgerQueue.then(() => bounded($, applyLedger($, change), IO_MS * 3, null))
1051  ledgerQueue = run.then(() => undefined, () => undefined)
1052  return run
1053}
1054
1055async function applyLedger($, change) {
1056  const file = await ledgerPath($)
1057  if (!file) return null
1058  const cur = await readLedger($, file)
1059  if (!cur) return null
1060  const next = change(cur)
1061  if (!next) return null
1062  const dir = file.slice(0, file.lastIndexOf('/'))
1063  const tmp = `${dir}/.${file.slice(dir.length + 1)}.tmp`
1064  await $.fs.write(tmp, JSON.stringify(next))
1065  const moved = await $.process.run(['mv', '-f', tmp, file], { timeoutMs: IO_MS })
1066  if (moved.exitCode !== 0) return null
1067  await showLedger($, next)
1068  return next
1069}
1070
1071// The band's row and the record's count, rewritten only when what they say changed. The
1072// band's "oldest 4m" is drawn against `asOf`, a minute bucket, so the age moves once a
1073// minute rather than redrawing every tick.
1074async function showLedger($, ledger) {
1075  const nowMs = await $.clock.now()
1076  const s = ledgerSummary(ledger, nowMs)
1077  const asOf = Math.floor(nowMs / 60_000) * 60_000
1078  const said = JSON.stringify(s)
1079  if (said === ledgerShown && asOf === ledgerAsOf) return
1080  const recChanged = said !== ledgerShown
1081  ledgerShown = said
1082  ledgerAsOf = asOf
1083  await bounded($, $.state.set(LEDGER, (s.open || s.promises || s.judgeFailing) ? { ...s, asOf } : null), IO_MS, null)
1084  if (recChanged) {
1085    const field = {
1086      open: s.open, promises: s.promises, ...(s.oldest ? { oldest_at: Math.floor(s.oldest.at / 1000) } : {}),
1087      ...(s.judgeFailing ? { judge_failing: s.judgeFailing } : {}),
1088    }
1089    await patchRecord($, rec => ({ ...rec, ledger: field }))
1090  }
1091}
1092
1093async function ledgerStart($) {
1094  const cfg = await ledgerConfigOf($)
1095  if (!cfg.on) return
1096  await bounded($, Promise.all([
1097    $.command.register({
1098      name: 'ledger', description: "This session's open requests and promises; close <id>, clear (no turn)", immediate: true,
1099    }),
1100    // Not deferred: a tool the agent has to go looking for is a tool it forgets to call, and
1101    // the three schemas together are a few hundred characters.
1102    $.tool.register({
1103      name: 'ledger_close', isDeferred: false,
1104      description: "Close one of this session's ledger items (the open requests and promises the prompt's ledger note lists) once it is finished. The proof is required: a path, link, commit, PR number or command result that shows it is done.",
1105      inputSchema: { type: 'object', properties: { id: { type: 'string', description: 'The item id, as the ledger note gives it' }, proof: { type: 'string', description: 'What shows it is done: a path, link, commit, PR number or command result' } }, required: ['id', 'proof'] },
1106    }),
1107    $.tool.register({
1108      name: 'ledger_drop', isDeferred: false,
1109      description: 'Drop a ledger item that is not a real ask, or that the person cancelled. The reason is required.',
1110      inputSchema: { type: 'object', properties: { id: { type: 'string' }, reason: { type: 'string' } }, required: ['id', 'reason'] },
1111    }),
1112    $.tool.register({
1113      name: 'ledger_add', isDeferred: false,
1114      description: "Track an ask from the person's latest message that the ledger note did not list.",
1115      inputSchema: { type: 'object', properties: { text: { type: 'string', description: 'The ask, in the person\'s words' } }, required: ['text'] },
1116    }),
1117  ]), IO_MS, null)
1118  ledgerShown = ''
1119  ledgerAsOf = 0
1120  await ledgerRefresh($)
1121}
1122
1123// The band tick rereads the file, so a close made from outside shows within a tick.
1124async function ledgerRefresh($) {
1125  const cfg = await ledgerConfigOf($)
1126  if (!cfg.on) return
1127  const file = await ledgerPath($)
1128  const l = file ? await readLedger($, file) : null
1129  if (l) await showLedger($, l)
1130}
1131
1132// Recorded BEFORE `next`, so the note the prompt carries can name its own items by id; the
1133// turn they belong to is stamped after, once `next` has started it. A slash command is the
1134// harness's, and carries nothing.
1135async function onPromptSubmit($, e, next) {
1136  const cfg = await ledgerConfigOf($)
1137  if (!cfg.on || String(e.text || '').trimStart().startsWith('/')) return next(e)
1138  const before = currentTurn
1139  const at = await $.clock.now()
1140  const source = sourceOf(e)
1141  const ids = []
1142  const made = []
1143  let window = 0
1144  let cur = source ? await changeLedger($, l => {
1145    window = Number(l.window) || 0
1146    return addPrompt(l, { text: e.text, at, turnId: e.turnId || '', source, queued: Boolean(e.turnId), choiceTurn }, ids, made)
1147  }) : null
1148  if (!cur) {
1149    const file = await ledgerPath($)
1150    cur = file ? await readLedger($, file) : null
1151  }
1152  const note = cur ? contextNote(cur, at) : ''
1153  const r = await next(note ? { ...e, context: [...(e.context || []), note] } : e)
1154  if (!ids.length) return r
1155  if (!r || r.drop !== undefined) {
1156    // It never entered: its items go, and the window goes back to the one before. An item it
1157    // only touched (a resend, a reply) was there before it, and stays.
1158    await changeLedger($, l => ({ ...dropItems(l, made), window }))
1159    return r
1160  }
1161  // Typed over a running turn, it carries that turn's id. Submitted idle, `next` resolves
1162  // once its own turn started: a turn.start since is that turn; failing that, the turn's
1163  // start names it (ledgerTurnStart), whichever of the two lands second.
1164  const turnId = e.turnId || (currentTurn !== before ? currentTurn : '')
1165  if (turnId && !e.turnId) await stampItems($, ids, turnId)
1166  return r
1167}
1168
1169async function stampItems($, ids, turnId) {
1170  if (!ids.length || !turnId) return
1171  await changeLedger($, l => (l.items.some(i => ids.includes(i.id) && !i.turnId)
1172    ? { ...l, items: l.items.map(i => (ids.includes(i.id) && !i.turnId ? { ...i, turnId } : i)) } : null))
1173}
1174
1175// ledger_close, ledger_drop and ledger_add: the agent's own hand on its items (./ledger.js).
1176async function onLedgerTool($, e) {
1177  const cfg = await ledgerConfigOf($)
1178  if (!cfg.on) return { result: 'ledger: off (CLAUDE_FLEET_LEDGER=off)' }
1179  const a = callArgs(e)
1180  const ctx = { nowMs: await $.clock.now(), turnId: currentTurn }
1181  const act = e.tool === TOOL.close ? l => closeByAgent(l, a.id, a.proof, ctx)
1182    : e.tool === TOOL.drop ? l => dropByAgent(l, a.id, a.reason, ctx)
1183      : l => addByAgent(l, a.text, ctx)
1184  let said = 'ledger: the file could not be read just now; nothing changed'
1185  await changeLedger($, l => { const r = act(l); said = r.said; return r.ledger })
1186  return { result: said }
1187}
1188
1189async function ledgerTurnStart($, e) {
1190  const cfg = await ledgerConfigOf($)
1191  if (!cfg.on || !e.text) return
1192  if (isGateTurn(e.text)) gateTurns = [...gateTurns, e.turnId].slice(-4)
1193  await changeLedger($, l => stampTurn(l, e.text, e.turnId))
1194}
1195
1196// A prompt fleet-send handed over, as DELIVERY claims it: one item (a brief is not split into
1197// its sentences) in a window of its own, unless it is a nudge. Its turn.start stamps the item
1198// with the turn and arms the note (ledgerNoteOnTool).
1199async function ledgerDelivery($, p) {
1200  const cfg = await ledgerConfigOf($)
hooks/shape.js 80 lines
1// What the mod writes, as plain functions of what the engine handed it: no `$`, no I/O.
2//
3// Kept apart from register.js so the suite can hold the record's shape to its readers
4// without a Claude session (test/run.sh imports this file with node), and so the next
5// phase reads the vocabulary here rather than in the middle of the hooks.
6
7export const VERSION = '0.1.0'
8
9// The fields the mod owns in a status record. hooks/fleet-event.sh rewrites the record
10// on every event and carries exactly these forward; test/run.sh holds the two lists to
11// each other, so a field added here and forgotten there goes red instead of vanishing
12// on the next shell event.
13export const MOD_FIELDS = ['source', 'state', 'turnId', 'mod', 'usage', 'ledger']
14
15// The state words are the fleet's own (bin/fleet-grid.mjs's STATUS table), so a reader
16// needs no translation:
17//   working      a model turn is running
18//   ready        the turn ended with an answer (or an error) and the prompt is free
19//   interrupted  the person cut the turn short (Esc); it is waiting on them
20//   need-you     a dialog is up that only a person can answer
21//   idle         a session that has not had a turn yet
22export const STATES = ['working', 'ready', 'interrupted', 'need-you', 'idle']
23
24export const stateAfterTurn = reason => (reason === 'aborted' ? 'interrupted' : 'ready')
25
26// Whether a tool.check verdict puts a real call in front of a person: `ask`, on a call
27// the model made (it has a tool_use_id; a `$.tool.check` query has none).
28export function asksAPerson(e, verdict) {
29  return Boolean(e && e.tool_use_id && verdict && verdict.decision === 'ask')
30}
31
32// The state, merged into the record the shell hook wrote. `status` is set too, so a
33// reader that only knows `status` sees the same word; `source` and `mod` are what let a
34// reader decide whether to believe it (lib/mod-status.mjs).
35export function withState(rec, state, { nowMs, pid, turnId }) {
36  return {
37    ...rec,
38    ...(turnId ? { turnId } : {}),
39    status: state,
40    state,
41    source: 'mod',
42    ts: Math.floor(nowMs / 1000),
43    mod: { v: VERSION, pid, hb: nowMs, at: nowMs },
44  }
45}
46
47// An ISO timestamp as epoch seconds, so a shell reader compares it with `date +%s` and
48// needs no date parser.
49const epoch = iso => {
50  const ms = iso ? Date.parse(iso) : NaN
51  return Number.isFinite(ms) ? Math.floor(ms / 1000) : undefined
52}
53
54// `session.measure` (or `$.session.usage()`) as the record keeps it. Each window keeps
55// the moment it resets beside its figure: within one window usage only rises, so a
56// reading whose window has not reset is a true lower bound however old it is, and one
57// whose window has reset describes nothing. That is the whole of what bin/fleet-governor
58// needs to decide whether to believe it.
59export function usageRecord(m, nowMs) {
60  const limits = {}
61  for (const w of m.rateLimits || []) {
62    if (!w || typeof w.kind !== 'string') continue
63    limits[w.kind] = { pct: w.percentUsed, resets: epoch(w.resetsAt) }
64  }
65  return {
66    at: Math.floor(nowMs / 1000),
67    context: { tokens: m.context?.tokens, window: m.context?.window, percent: m.context?.percent },
68    limits,
69    ...(m.cost ? { cost_usd: m.cost.usd } : {}),
70  }
71}
72
73// The fleet socket named by $TMUX ("<socket path>,<server pid>,<session>"), when it is
74// a fleet's (cf-*): the server this pane is on, which cannot go stale behind a
75// long-running --resume the way an exported CLAUDE_FLEET_SOCK can.
76export function sockOfTmux(tmux) {
77  const server = String(tmux || '').split(',')[0].split('/').pop() || ''
78  return server.startsWith('cf-') ? server : ''
79}
80
hooks/guard-shape.js 201 lines
1// What the guards decide from, as plain functions of strings: no `$`, no I/O.
2//
3// Kept apart from guards.js for the reason shape.js is: test/run.sh imports this file with
4// node and holds it to the shell guard it stands in for (hooks/fleet-guard.sh), command for
5// command, so the two cannot drift into two answers to "is this a merge".
6
7// ── the merge guard's patterns, from hooks/fleet-guard.sh ───────────────────
8//
9// The shell's POSIX classes spelled out. Whitespace is folded first, as `tr '\n\t' '  '`
10// folds it there, so a merge split across lines is still one.
11const fold = cmd => String(cmd || '').replace(/[\n\t]/g, ' ')
12
13const MERGES = [
14  // `gh pr merge`, with --auto too: that is a merge scheduled for later
15  /(^|[^A-Za-z0-9_.-])gh\s([^|;&]*\s)?pr\s+merge(\s|$)/,
16  // the REST endpoint, which is what a model reaches for when the porcelain is refused
17  /(^|[^A-Za-z0-9_.-])gh\s([^|;&]*\s)?api\s[^|;&]*pulls\/[^\s/]+\/merge/,
18  /mergePullRequest|enablePullRequestAutoMerge/,
19]
20export const mergesAPr = cmd => MERGES.some(re => re.test(fold(cmd)))
21
22const BOUNDARY_WRITES = [
23  /(^|[^A-Za-z0-9_.-])fleet-project\s+set(\s|$)/,
24  /\.(workers-merge|agents-approve)(-off)?([^A-Za-z0-9_-]|$)/,
25]
26export const changesABoundary = cmd => BOUNDARY_WRITES.some(re => re.test(fold(cmd)))
27
28// The MCP tools the merge guard stands in front of: any server's merge_pull_request.
29export const isMergeTool = tool => /^mcp__.+__merge_pull_request$/.test(String(tool || ''))
30
31// Which PR a merge command names: a REST call carries it in the path; `gh pr merge` takes
32// it as the first bare word after `merge`, and with none it means the current branch's PR.
33// `repo` is a -R/--repo, when given.
34export function prSelector(cmd) {
35  const flat = fold(cmd)
36  let sel = (flat.match(/pulls\/([0-9]+)\/merge/) || [])[1] || ''
37  if (!sel) {
38    const w = flat.split(/\s+/).filter(Boolean)
39    for (let i = 1; i < w.length - 1 && !sel; i++) {
40      if (w[i] !== 'merge' || w[i - 1] !== 'pr') continue
41      for (let j = i + 1; j < w.length; j++) {
42        if (/^[;&|]/.test(w[j])) break
43        if (!w[j].startsWith('-')) { sel = w[j]; break }
44      }
45      break
46    }
47  }
48  const repo = (flat.match(/.*(?:-R|--repo)[ =]([^ ]+)/) || [])[1] || ''
49  return { sel, repo }
50}
51
52// "Workers can merge" / "agents can approve tool calls" (lib/boundary.sh): most specific
53// wins. `has(name)` says whether a marker of that name is in the fleet dir.
54export function boundaryOn(setting, sock, sess, has) {
55  if (!setting || !sock) return false
56  if (sess) {
57    if (has(`${sock}.${sess}.${setting}-off`)) return false
58    if (has(`${sock}.${sess}.${setting}`)) return true
59  }
60  return has(`${sock}.${setting}`)
61}
62
63const LABEL = { 'workers-merge': 'workers can merge', 'agents-approve': 'agents can approve tool calls' }
64export function boundaryHow(setting, sock, sess) {
65  const lines = [
66    `"${LABEL[setting]}" is off. A lead or a human can turn it on:`,
67    `      fleet-project set -s ${sock} ${setting} on                 # the whole project (or the grid's , page)`,
68  ]
69  if (sess) lines.push(`      fleet-project set -s ${sock} ${setting} on --session ${sess}   # this session only`)
70  return lines.join('\n')
71}
72
73// The refusals, word for word the shell guard's, so a session reads one rule whichever
74// door refused it. Each begins `ghostfleet:` as the shell's do.
75export const SETTING_REFUSAL = [
76  'ghostfleet: a worker does not change its own boundaries.',
77  '  "workers can merge" and "agents can approve tool calls" are set by the lead (from the',
78  "  main checkout) or a human (the grid's , page) — never by a session in a linked worktree,",
79  '  which is the session they bound. Ask the lead if your task needs one.',
80].join('\n')
81
82export function mergeRefusal(where, branch, sock, sess) {
83  return [
84    'ghostfleet: a worker does not merge its own PR — the LEAD merges.',
85    `  This session runs in a linked worktree (${where}${branch ? `, branch ${branch}` : ''}), which makes`,
86    '  it a worker. The lead scans what you opened and merges it from the main checkout;',
87    '  a green check is its signal to look, not yours to merge.',
88    '',
89    '  What to do instead: push, make sure the PR is open against the integration branch,',
90    '  report the PR number, and end your turn.',
91    '',
92    boundaryHow('workers-merge', sock, sess).split('\n').map(l => `  ${l}`).join('\n'),
93  ].join('\n')
94}
95
96// Every refusal from a guard that could not decide. A guard that cannot tell refuses:
97// that is the whole difference from the shell version, which lets the call through.
98export const failedClosed = (what, why) =>
99  `ghostfleet: ${what} could not be checked, so it is refused (a guard fails closed): ${why}. ` +
100  'Nothing ran. If this repeats, the fleet\'s own commands (fleet-answer, fleet-jarvis, gh, git) ' +
101  'are not answering from this session; tell the lead or a human rather than working around it.'
102
103// ── fleet-answer, as a Bash command ─────────────────────────────────────────
104//
105// Each `fleet-answer` the command runs, as the argv it would get, so the mod can ask
106// `fleet-answer --check` the same question first. Words are split the way a shell splits
107// plain quoting ('…', "…", \x). Anything a shell would EXPAND ($, `, a subshell, a
108// redirect) cannot be known from here: such a command answers null and is left to
109// fleet-answer's own check, which still runs when the command does.
110export function answerCalls(cmd) {
111  const words = shellWords(String(cmd || ''))
112  if (!words) return null
113  const calls = []
114  let start = true
115  for (let i = 0; i < words.length; i++) {
116    const w = words[i]
117    if (w.op) { start = true; continue }
118    if (start && /^[A-Za-z_][A-Za-z0-9_]*=/.test(w.text)) continue
119    if (start && /(^|\/)fleet-answer$/.test(w.text)) {
120      const argv = []
121      for (i++; i < words.length && !words[i].op; i++) argv.push(words[i].text)
122      i--
123      calls.push(argv)
124    }
125    start = false
126  }
127  return calls
128}
129
130// [{text}|{op}] or null when the line holds something only a shell can expand.
131function shellWords(s) {
132  const out = []
133  let cur = null
134  const push = () => { if (cur !== null) out.push({ text: cur }); cur = null }
135  for (let i = 0; i < s.length; i++) {
136    const c = s[i]
137    if (c === "'") {
138      const j = s.indexOf("'", i + 1)
139      if (j < 0) return null
140      cur = (cur ?? '') + s.slice(i + 1, j); i = j; continue
141    }
142    if (c === '"') {
143      let t = ''
144      for (i++; i < s.length && s[i] !== '"'; i++) {
145        if (s[i] === '$' || s[i] === '`') return null
146        if (s[i] === '\\' && i + 1 < s.length && '"\\$`\n'.includes(s[i + 1])) i++
147        t += s[i]
148      }
149      if (i >= s.length) return null
150      cur = (cur ?? '') + t; continue
151    }
152    if (c === '\\') { if (i + 1 >= s.length) return null; cur = (cur ?? '') + s[++i]; continue }
153    if ('$`()<>{}'.includes(c)) return null
154    if (c === ';' || c === '|' || c === '&' || c === '\n') {
155      push()
156      while (i + 1 < s.length && (s[i + 1] === '|' || s[i + 1] === '&')) i++
157      out.push({ op: true }); continue
158    }
159    if (c === ' ' || c === '\t') { push(); continue }
160    cur = (cur ?? '') + c
161  }
162  push()
163  return out
164}
165
166// ── Jarvis ──────────────────────────────────────────────────────────────────
167//
168// The MCP tools lib/jarvis.mjs mcpConfirmSpec names, and the server they belong to. Only
169// these are asked about; every other call costs nothing.
170export const JARVIS_TOOLS = new Set([
171  'fleet_stop', 'fleet_worktree_remove', 'fleet_project_remove', 'fleet_answer',
172  'fleet_spawn', 'fleet_companion', 'fleet_send',
173])
174export function fleetTool(tool) {
175  const m = /^mcp__ghostfleet__(fleet_[a-z_]+)$/.exec(String(tool || ''))
176  return m ? m[1] : ''
177}
178
179// The tool's own arguments: the envelope keys the engine adds are not the call's.
180const ENVELOPE = new Set(['tool', 'tool_use_id', 'agentId', 'consent'])
181export const callArgs = e => Object.fromEntries(Object.entries(e || {}).filter(([k]) => !ENVELOPE.has(k)))
182
183// Could lib/jarvis.mjs bashSpec act on this command at all? A strict SUPERSET of its rules
184// (test/run.sh holds it to that), so the gate is asked only when it might say no. Every
185// rule there names gh, git, tmux, a fleet- command, Jarvis's own files or verbs, or Jarvis's
186// socket after -L/-s; anything else it answers `ok`. Without this, Jarvis's every `ls` would
187// need node and the gate, and one broken gate would refuse the whole shell.
188export function jarvisMightAct(cmd, sock, jdir) {
189  const c = String(cmd || '')
190  if (/\b(gh|git|tmux|jarvis)\b|fleet-|\.config\/ghostfleet/.test(c)) return true
191  if (jdir && c.includes(jdir)) return true
192  const esc = String(sock || '').replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
193  return Boolean(esc) && new RegExp(`-[Ls]\\s*${esc}\\b`).test(c)
194}
195
196// The marker's sock= line (lib/jarvis.mjs readMarker reads the rest).
197export function markerSock(text) {
198  const m = /^sock=(.*)$/m.exec(String(text || ''))
199  return m ? m[1].trim() : ''
200}
201
hooks/band-shape.js 131 lines
1// What the lead's band says, as plain functions: no `$`, no I/O. test/run.sh imports this
2// with node and renders it at every width it claims to fit.
3
4// The grid's colours (bin/fleet-grid.mjs C: 203 red, 80 cyan, 114 green), so a state reads
5// the same on the band as on the card.
6export const COLOR = { need: '#ff5f5f', working: '#5fd7d7', green: '#87d787', red: '#ff5f5f' }
7
8// A record's state for the band: the mod's while it is still being written (the same
9// heartbeat rule as lib/mod-status.mjs, without the pid probe the mod cannot make), else the
10// shell hook's `status`.
11export const MOD_STALE_MS = 150_000
12export function recordState(rec, nowMs) {
13  if (!rec) return ''
14  if (rec.source === 'mod' && rec.state && rec.mod && nowMs - (Number(rec.mod.hb) || 0) <= MOD_STALE_MS) return rec.state
15  return String(rec.status || '')
16}
17
18// Who is on this lead's team, from the sessions alive on its socket:
19//   master    every session but itself and the terminal tabs (`_term-…`, never a worker)
20//   sub-lead  its children: the sessions whose <sock>.<child>.parent names it
21// Anything else is not a lead and gets no band.
22export function teamOf(me, alive, children) {
23  if (me === 'master') return alive.filter(s => s !== 'master' && !s.startsWith('_'))
24  if (children.length) return alive.filter(s => children.includes(s))
25  return null
26}
27
28// The newest record per session name on this socket.
29export function latestBySlot(records, sock) {
30  const by = new Map()
31  for (const r of records) {
32    if (!r || r.sock !== sock || !r.slot) continue
33    const prev = by.get(r.slot)
34    if (!prev || (Number(r.ts) || 0) >= (Number(prev.ts) || 0)) by.set(r.slot, r)
35  }
36  return by
37}
38
39export function summarize(team, bySlot, nowMs) {
40  let working = 0, need = 0
41  for (const s of team) {
42    const st = recordState(bySlot.get(s), nowMs)
43    if (st === 'working') working++
44    else if (st === 'need-you') need++
45  }
46  return { workers: team.length, working, need }
47}
48
49// `gh pr list --json headRefName,baseRefName,statusCheckRollup` reduced to what the band
50// says. A PR is green when every check finished and none failed, red when any failed,
51// pending otherwise (and when it has no checks at all: nothing has said it is green).
52const FAILED = new Set(['FAILURE', 'CANCELLED', 'TIMED_OUT', 'ERROR', 'ACTION_REQUIRED', 'STARTUP_FAILURE'])
53const PASSED = new Set(['SUCCESS', 'NEUTRAL', 'SKIPPED'])
54export function checkState(rollup) {
55  const checks = Array.isArray(rollup) ? rollup : []
56  if (!checks.length) return 'pending'
57  let done = true
58  for (const c of checks) {
59    const v = String(c.conclusion || c.state || '').toUpperCase()
60    if (FAILED.has(v)) return 'red'
61    if (!PASSED.has(v)) done = false
62  }
63  return done ? 'green' : 'pending'
64}
65
66// Which PRs are this lead's: a sub-lead's are the ones INTO its branch (its children's);
67// master's are the ones FROM a branch its fleet spawned (the manifest), whatever became of
68// the session since — a finished worker's green PR is exactly what master is waiting on.
69export function prSummary(prs, { me, branch, fleetBranches }) {
70  const mine = (prs || []).filter(p => me === 'master'
71    ? fleetBranches.includes(p.headRefName)
72    : Boolean(branch) && p.baseRefName === branch)
73  const out = { green: 0, red: 0, pending: 0 }
74  for (const p of mine) out[checkState(p.statusCheckRollup)]++
75  return out
76}
77
78// The band as text runs, the longest form that fits `columns`. The order is the brief's
79// ("3 workers · 1 working · 1 need you · 2 PRs green") while there is room; as it narrows,
80// words shorten, and below that `need you` moves first, since it is the one thing a lead
81// must not miss and the right end is what a narrow pane cuts.
82//   prs: undefined = not read yet (say nothing), null = could not read (`PRs ?`).
83// A run is { text, color?, dim?, bold? }; groups are joined by ` · `, or a space when tight.
84// `w` is workers wherever it is short: the band never says anything else with a w.
85export function bandRuns(s, prs, columns) {
86  if (!s) return null
87  if (s.workers === 0 && !(prs && (prs.green || prs.red || prs.pending))) return null
88  const cols = Math.max(1, Number(columns) || 80)
89  const n = (k, one, many) => `${k} ${k === 1 ? one : many}`
90  const need = t => s.need ? [{ text: t, color: COLOR.need, bold: true }] : null
91  const busy = t => s.working ? [{ text: t, color: COLOR.working }] : null
92  const team = t => [{ text: t, dim: true }]
93  const forms = [
94    [' · ', [team(n(s.workers, 'worker', 'workers')), busy(`${s.working} working`), need(`${s.need} need you`), ...prGroups(prs, 'long')]],
95    [' · ', [team(n(s.workers, 'worker', 'workers')), busy(`${s.working} working`), need(`${s.need} need you`), ...prGroups(prs, 'short')]],
96    [' · ', [need(`${s.need} need you`), busy(`${s.working} busy`), team(`${s.workers}w`), ...prGroups(prs, 'tight')]],
97    [' · ', [need(`${s.need} need`), busy(`${s.working} busy`), team(`${s.workers}w`)]],
98    [' ', [need(`${s.need} need`), team(`${s.workers}w`)]],
99    [' ', [s.need ? need(`${s.need}!`) : team(`${s.workers}w`)]],
100  ]
101  let runs = null
102  for (const [sep, groups] of forms) {
103    runs = groups.filter(Boolean).flatMap((g, i) => (i ? [{ text: sep, dim: true }, ...g] : g))
104    if (width(runs) <= cols) return runs
105  }
106  return runs
107}
108
109function prGroups(prs, form) {
110  if (prs === undefined) return []
111  if (prs === null) return [[{ text: 'PRs ?', dim: true }]]
112  const green = { text: '', color: COLOR.green }, red = { text: '', color: COLOR.red }
113  if (form === 'long') return [
114    prs.green ? [{ ...green, text: `${prs.green} ${prs.green === 1 ? 'PR' : 'PRs'} green` }] : null,
115    prs.red ? [{ ...red, text: `${prs.red} red` }] : null,
116    prs.pending ? [{ text: `${prs.pending} pending`, dim: true }] : null,
117  ]
118  const bits = [
119    prs.green ? { ...green, text: `${prs.green}✓` } : null,
120    prs.red ? { ...red, text: `${prs.red}✗` } : null,
121    form === 'short' && prs.pending ? { text: `${prs.pending}…`, dim: true } : null,
122  ].filter(Boolean)
123  if (!bits.length) return []
124  const spaced = bits.flatMap((b, i) => (i ? [{ text: ' ' }, b] : [b]))
125  return [form === 'short' ? [{ text: 'PRs ', dim: true }, ...spaced] : spaced]
126}
127
128// Cells, counting each code point as one: every glyph the band draws is narrow.
129export function width(runs) { return (runs || []).reduce((k, r) => k + [...r.text].length, 0) }
130export const plain = runs => (runs || []).map(r => r.text).join('')
131
hooks/ledger.js 951 lines
1// The request ledger's vocabulary, as plain functions: no `$`, no I/O. The LEDGER section
2// of register.js uses them; bin/fleet-ledger reads and writes the same file through them,
3// and test/run.sh imports this file with node.
4//
5// <fleet dir>/<session_id>.ledger   (JSON, but deliberately NOT named *.json: eight readers
6//                                    glob <fleet dir>/*.json as status records)
7//   { v: 1, seq, prompt, window, items: [ { id, text, at, turnId, state, source, ... } ], judge? }
8//
9//   state    open | done | not-done | stale (a promise no judged turn addressed, see STALE_TURNS)
10//            | dropped (the agent said it was not a real ask, or the person cancelled it)
11//            | waiting (a judged turn said it waits on the PERSON: off the open list and the
12//            gate until they speak to it, see waitsOnPersonNote)
13//            | expired (stale or waiting, and untouched for EXPIRE_DAYS: retired, not open)
14//            stale and waiting are DORMANT: not open, but a turn that mentions one has it
15//            judged again (revisit), so work that finished later still closes it
16//   source   user     typed at the prompt (or the phone's bridge), idle or mid-turn
17//            fleet    a prompt fleet-send handed to the mod (DELIVERY)
18//            promise  a commitment the agent made in a final message ("I'll merge when green")
19//   gated    true once the gate has re-prompted about it: at most once per item, ever
20//   progress { at, turnId, reason }: a judged turn reported the item's state and said the
21//            work goes on elsewhere (a worker, a build, CI) or waits on the person. It stays
22//            open, listed and judged, and the gate never names it (gateTargets)
23//   queued   typed over a running turn; interrupted: its turn was stopped (Esc). Either may
24//            never have reached the model, and the gate asks the transcript first. A resend
25//            within RESEND_MS of the stop is folded into the interrupted item (resendOf)
26//   replies  [{ at, text }]: bare answers to a numbered question the agent asked about it
27//   prompt   the number of the prompt that made it (ledger.prompt counts them); `window` is
28//            the first prompt of the latest one, and only items from `window` on are gated.
29//            An item from before this field existed has none, and is never gated again
30//   closedBy agent (ledger_close / ledger_drop, with `proof` or `reason`) | judge |
31//            person (/ledger close, fleet-ledger close; `hand` in a file written before)
32
33export const LEDGER_VERSION = 1
34export const KEEP_ITEMS = 200                 // the file keeps the newest 200
35export const BAND_DAYS = 7                    // older than this drops off the band and the gate
36export const EXCERPT = 240                    // a request's text as kept
37const DAY_MS = 86_400_000
38
39export const ledgerFile = (dir, sessionId) => `${dir}/${sessionId}.ledger`
40
41export const emptyLedger = () => ({ v: LEDGER_VERSION, seq: 0, items: [] })
42
43// A file that is missing, torn or someone else's shape reads as empty, never as a throw.
44export function parseLedger(text) {
45  try {
46    const l = JSON.parse(text)
47    if (l && typeof l === 'object' && Array.isArray(l.items)) return { ...emptyLedger(), ...l, items: l.items.filter(i => i && i.id) }
48  } catch {}
49  return emptyLedger()
50}
51
52// The switches, from the environment (a settings file's `env` block lands there too).
53//   CLAUDE_FLEET_LEDGER=off               the whole feature
54//   CLAUDE_FLEET_LEDGER_GATE=off          record and show, never re-prompt
55//   CLAUDE_FLEET_LEDGER_PROMISES=show|gate|off   (default show)
56export function ledgerConfig(get) {
57  const off = v => /^(off|0|false|no)$/i.test(String(v || '').trim())
58  const p = String(get('CLAUDE_FLEET_LEDGER_PROMISES') || 'show').trim().toLowerCase()
59  return {
60    on: !off(get('CLAUDE_FLEET_LEDGER')),
61    gate: !off(get('CLAUDE_FLEET_LEDGER_GATE')),
62    promises: p === 'gate' || p === 'off' ? p : 'show',
63    model: String(get('CLAUDE_FLEET_LEDGER_MODEL') || 'haiku').trim() || 'haiku',
64  }
65}
66
67const oneLine = s => String(s || '').replace(/\s+/g, ' ').trim()
68export const excerpt = (s, n = EXCERPT) => {
69  const t = oneLine(s)
70  return t.length > n ? `${t.slice(0, n - 1)}…` : t
71}
72
73// What a message asks, in the person's own words. A message is often mostly material: a
74// pasted transcript or log with a line of the person's around it. Kept as typed, the item's
75// excerpt was the paste's first lines, the person's words were cut off past the excerpt,
76// and the judge, shown a pasted draft and a pasted ledger reminder, judged THOSE: measured
77// live, "u see what it just did <a pasted turn> its like reminding literally the last
78// response" was re-prompted as an open request. So the pastes are set aside (marked, so the
79// judge knows something was pasted) and so is any ledger reminder quoted in the text: it is
80// this mod's own words, never the person's request. A message that is nothing but a quoted
81// reminder is no request at all ('').
82const PASTE = /<pasted_content\b[^>]*>[\s\S]*?(?:<\/pasted_content\b[^>]*>|$)/g
83const PASTE_TAG = /<\/?pasted_content\b[^>]*>/g
84const REMINDER = [
85  /(?:The ghostfleet plugin sent a message:\s*)?\[ghostfleet ledger\][\s\S]*?(?:it will not be asked again\.\)|$)/g,
86  /This is how Claude Code surfaces a prompt a plugin submits between turns[^\n]*/g,
87  /\[ghostfleet ledger: open items\][\s\S]*?(?:for an ask this list missed\.|$)/g,
88]
89const unquote = t => REMINDER.reduce((a, re) => a.replace(re, ' '), t)
90export function requestText(text) {
91  const pastes = []
92  const own = oneLine(unquote(String(text || '').replace(PASTE, m => { pastes.push(m.replace(PASTE_TAG, ' ')); return ' ' })))
93  if (!pastes.length) return own
94  if (own) return `${own} [+ pasted text]`
95  const pasted = oneLine(unquote(pastes.join(' ')))
96  return pasted ? `[pasted] ${pasted}` : ''
97}
98
99// A request as an item keeps its start AND its end. A paste the composer shows inline carries
100// no marker, and the person's own words come after it: measured live, a three-line draft and
101// "what do u think" was kept as the draft's opening lines, the judge read the request as
102// "write the draft", and an answered question was re-prompted. The start stays the longer
103// part (the withdrawn check matches on an item's opening words).
104const ITEM_HEAD = 140
105export function requestItem(text) {
106  const t = requestText(text)
107  return t.length > EXCERPT ? `${t.slice(0, ITEM_HEAD - 1)}… ${t.slice(-(EXCERPT - ITEM_HEAD - 1))}` : t
108}
109
110// Which submitted prompts are requests, and whose. Only the person's: composer, the phone's
111// bridge, and what the engine cannot attest (`unclassified`). This mod's own submits are
112// never read here: a fleet-send handoff is recorded by DELIVERY at the turn it started (it
113// knows the turn exactly), and the gate's re-prompt must never become an item of its own,
114// which would be a loop with extra steps. Everything else (a background task's
115// notification, a /loop firing, a peer's message) is not a request somebody is waiting on.
116// A slash command is an instruction to the harness, not work for the agent.
117export function sourceOf(e) {
118  const text = String(e && e.text || '')
119  if (!requestText(text) || text.trimStart().startsWith('/') || isNudge(text)) return null
120  const o = (e && e.origin) || { kind: 'composer' }
121  return o.kind === 'composer' || o.kind === 'bridge' || o.kind === 'unclassified' ? 'user' : null
122}
123
124// The fleet's own wake-ups, by their words. fleet-send --nudge marks one on the handoff
125// (`kind: "nudge"`), and that marker is the first test; this one catches the nudge that came
126// without it: one that fell back to the paste and arrived as typed text, and one an older
127// fleet-send handed over unmarked. Measured on one lead's week: ten of its fourteen fleet items
128// were the same "a worker finished, run fleet-inbox ... no need to reply to it" line, each
129// judged, each listed. A message that says it needs no reply is not a request. Both halves,
130// so a [fleet] message that relays a question still is one.
131export const isNudge = text => /^\s*\[fleet\]/.test(String(text || '')) && /\bno need to reply\b/i.test(String(text || ''))
132
133// The asks in one message, each an item of its own, so each can be closed on its own proof.
134// A message of three asks kept as one item could only close when all three were done, and
135// the agent closing it had to vouch for the two it did not mention. Split only where the
136// split is plain: two or more sentences or list lines that each read as an ask (a list line,
137// a question, a sentence that opens with a verb of work or a "can you"). A message with
138// fewer is one item, exactly as it always was, and so is one with a paste in it (the paste's
139// sentences are not the person's asks) or one long enough to be a pasted brief. The cheap
140// side of the trade is deliberate: a miss is an ask the agent adds with ledger_add, while a
141// false split is an item nobody asked for, which the gate would then re-prompt.
142const ASK_VERB = /^(please\b|pls\b|can you|could you|would you|will you|can we|could we|let'?s|make sure|i need you|i want you|we need to|add|fix|build|write|rewrite|update|remove|delete|rename|run|rerun|re-run|test|check|review|merge|push|pull|open|close|create|make|send|show|tell|explain|find|look (at|into)|move|bump|change|refactor|document|deploy|publish|release|draft|summari[sz]e|list|compare|measure|verify|install|set up|clean|revert|commit|ship|wire|port|split|reply|answer|investigate|debug|profile|benchmark|translate|describe|generate|implement|try|shorten|trim|cut|edit|polish|format|lint|simplify|tighten|extend|convert|replace|swap|post|upload|share|save|schedule|plan|design|outline|research|read|search|fetch|download|start|stop|restart|retry|resend|confirm|count)\b/i
143const ASK_ANYWHERE = /\b(please|can you|could you|need you to|want you to)\b/i
144const LEAD_IN = /^(and|also|then|plus|so|oh and|and also)[, ]+/i
145const RULE = /^(do not|don'?t|never|avoid|without|no need)\b/i
146const STILL_ASKS = /^(do not|don'?t|never) forget\b/i
147const LISTED = /^\s*(\d+[.)]|[-*•])\s+/
148const SPLIT_MAX = 4000
149const ASKS_MAX = 8
150export function requestAsks(text) {
151  const raw = String(text || '')
152  const whole = requestItem(raw)
153  if (!whole) return []
154  if (PASTE.test(raw) || raw.length > SPLIT_MAX) { PASTE.lastIndex = 0; return [whole] }
155  PASTE.lastIndex = 0
156  const own = REMINDER.reduce((a, re) => a.replace(re, ' '), raw)
157  const parts = own.split(/\n+/).flatMap(line => {
158    const listed = LISTED.test(line)
159    return line.replace(LISTED, '').split(/(?<=[.?!])\s+/).map((t, k) => ({ t: oneLine(t), listed: listed && k === 0 }))
160  }).filter(x => x.t)
161  const asks = []
162  for (const { t, listed } of parts) {
163    if (t.length < 6 || t.length > 300) continue
164    const bare = t.replace(LEAD_IN, '')
165    if (RULE.test(bare) && !STILL_ASKS.test(bare)) continue
166    if (listed || t.endsWith('?') || STILL_ASKS.test(bare) || ASK_VERB.test(bare) || ASK_ANYWHERE.test(t)) asks.push(excerpt(t))
167    if (asks.length >= ASKS_MAX) break
168  }
169  return asks.length >= 2 ? asks : [whole]
170}
171
172// A message, as items: one per ask (requestAsks), all carrying the message's prompt number.
173// A message typed idle starts a new window, the one the gate may re-prompt about; one typed
174// over a running turn joins the window that turn belongs to, since that turn's end is not
175// gated (a queued message has started the next) and the next turn answers both.
176// `ids`, when given, is filled with the new items' ids.
177//
178// Before any item is made: a bare answer to the agent's own numbered question (`choiceTurn`,
179// the turn that asked) is folded into the item that turn was about (foldReply); a resend of a
180// message stopped moments ago updates the item the stop left (resendOf); and a waiting item
181// the message speaks to is the agent's to act on again (wakeWaiting).
182// `made`, when given, is filled with only the items it created (a resend or a reply touches
183// one that was there before, and undoing the prompt must not delete it).
184export function addPrompt(ledger, { text, at, turnId, source, queued, whole = false, choiceTurn = '' }, ids = [], made = []) {
185  if (isNudge(text)) return null
186  const folded = !queued && choiceTurn ? foldReply(ledger, text, { at, choiceTurn }) : null
187  if (folded) { ids.push(folded.id); return folded.ledger }
188  const asks = whole ? [requestItem(text)].filter(Boolean) : requestAsks(text)
189  if (!asks.length) return null
190  const prompt = (Number(ledger.prompt) || 0) + 1
191  const window = queued && ledger.window ? ledger.window : prompt
192  let next = { ...ledger, prompt, window }
193  for (const ask of asks) {
194    const again = resendOf(next, ask, { at, source })
195    if (again) {
196      next = {
197        ...next,
198        items: next.items.map(i => {
199          if (i !== again) return i
200          const { interrupted, interruptedAt, turnId: _t, queued: _q, ...rest } = i
201          return { ...rest, text: ask, at, ...(turnId ? { turnId } : {}), ...(queued ? { queued: true } : {}), prompt, resent: (Number(i.resent) || 0) + 1 }
202        }),
203      }
204      ids.push(again.id)
205      continue
206    }
207    next = addItem(next, { text: ask, at, turnId, source, queued, prompt, asIs: true })
208    ids.push(next.items[next.items.length - 1].id)
209    made.push(next.items[next.items.length - 1].id)
210  }
211  return wakeWaiting(next, text, at) || next
212}
213
214// THE RESEND OF A STOPPED MESSAGE. The person sends, stops the turn (Esc), and sends the same
215// words again, or the same words edited at the end, or extended, seconds later: one message to
216// their mind, and it was two items. Measured on one lead's week: three such pairs, 3 to 13
217// seconds apart, one identical, one sharing 154 of 159 characters, one the first message with
218// a sentence added. `withdrawn` drops the rewound copy, but only at a gate, and only when the
219// transcript holds one copy; most of the time both stayed open and both were judged. So a new
220// ask within RESEND_MS of an interrupted, still-open item of the same source, whose words are
221// the same or nearly (sameWords), IS that item.
222export const RESEND_MS = 60_000
223export function resendOf(ledger, ask, { at, source }) {
224  const near = ledger.items.filter(i => i.state === 'open' && i.interrupted && i.source === source
225    && Number(at) - (Number(i.interruptedAt) || Number(i.at) || 0) <= RESEND_MS && sameWords(i.text, ask))
226  return near.length ? near[near.length - 1] : null
227}
228// Equal; one the start of the other; or sharing most of their opening; or most of their
229// words. An item's text is an excerpt ("head… tail"), so the cut is set aside first.
230export function sameWords(a, b) {
231  const n = t => oneLine(t).toLowerCase().replace(/…/g, ' ').replace(/\s+/g, ' ').trim()
232  const x = n(a), y = n(b)
233  if (!x || !y) return false
234  if (x === y) return true
235  const [short, long] = x.length <= y.length ? [x, y] : [y, x]
236  if (short.length >= 12 && long.startsWith(short)) return true
237  let k = 0
238  while (k < short.length && short[k] === long[k]) k++
239  if (short.length >= 20 && k >= 0.8 * short.length) return true
240  const wx = new Set(x.split(/\W+/).filter(Boolean)), wy = new Set(y.split(/\W+/).filter(Boolean))
241  const shared = [...wx].filter(w => wy.has(w)).length
242  return wx.size + wy.size > 0 && shared >= 4 && shared / new Set([...wx, ...wy]).size >= 0.8
243}
244
245// A BARE ANSWER TO THE AGENT'S OWN QUESTION. The agent ends a turn on "1. … 2. … which one?"
246// and the person answers "2", "yes 1", "ok go with 2", a version number. Measured: eight such
247// replies in one week, each its own item, each judged on its own and read as an ask with no
248// subject. It is the item the question was about, answered: folded in as a reply (`replies`,
249// which the judge is shown), and a waiting item is the agent's again. Only when the asking
250// turn ended on a numbered choice (endsOnChoice, read where the turn is known) and only into
251// an item that is still owed: one already closed leaves the reply to be an ask of its own.
252const CHOICE_WORD = new Set('yes yeah yep y no n ok okay sure go do pick option opt the with both all none first second third one that this'.split(' '))
253const CHOICE = /^(?:[#(]?\d+(?:\.\d+)*[).,]?|[a-e][).]?|both|all|none|first|second|third|yes|yeah|yep|y|no|n)$/
254export function isBareChoice(text) {
255  if (PASTE.test(String(text || ''))) { PASTE.lastIndex = 0; return false }
256  PASTE.lastIndex = 0
257  const t = requestText(text).toLowerCase().replace(/[.!]+$/, '')
258  if (!t || t.length > 24) return false
259  const words = t.split(/[\s,]+/).filter(Boolean)
260  return words.length <= 4 && words.some(w => CHOICE.test(w)) && words.every(w => CHOICE.test(w) || CHOICE_WORD.has(w))
261}
262export function endsOnChoice(answer) {
263  const tail = String(answer || '').slice(-800)
264  return (tail.match(/^\s*\(?\d+[.)]\s+\S/gm) || []).length >= 2 && tail.includes('?')
265}
266const OWED = new Set(['open', 'waiting', 'stale'])
267export function foldReply(ledger, text, { at, choiceTurn }) {
268  if (!choiceTurn || !isBareChoice(text)) return null
269  const of = ledger.items.filter(i => i.turnId === choiceTurn && OWED.has(i.state))
270  const it = of.filter(i => i.source !== 'promise').pop() || of.pop()
271  if (!it) return null
272  const reply = { at, text: excerpt(requestText(text), 40) }
273  const items = ledger.items.map(i => (i === it ? { ...reopened(i), replies: [...(i.replies || []), reply].slice(-3) } : i))
274  return { id: it.id, ledger: { ...ledger, items } }
275}
276
277// A dormant item back to open, its closing fields cleared. A waiting item loses its progress
278// note too: the person has moved, and the note said the move was theirs.
279function reopened(i) {
280  if (i.state === 'open') return i
281  const { closedAt, closedBy, reason, keptOpen, ...rest } = i
282  const { progress, ...bare } = rest
283  return { ...(i.state === 'waiting' ? bare : rest), state: 'open' }
284}
285
286// The person speaks to a waiting item (their message mentions it): it is open again.
287export function wakeWaiting(ledger, text, at) {
288  const said = requestText(text)
289  const woke = ledger.items.filter(i => i.state === 'waiting' && mentions(i.text, said, { loose: true }))
290  if (!woke.length) return null
291  return { ...ledger, items: ledger.items.map(i => (woke.includes(i) ? { ...reopened(i), woke: at } : i)) }
292}
293
294// A request submitted idle names its turn at that turn's start, which carries its text: every
295// item of the newest message with those words that has no turn yet.
296export function stampTurn(ledger, text, turnId) {
297  const t = String(text || '').trim()
298  if (!t) return null
299  const asks = new Set([requestItem(t), ...requestAsks(t)])
300  const fits = ledger.items.filter(x => x.state === 'open' && !x.turnId && x.source !== 'promise' && asks.has(x.text))
301  if (!fits.length) return null
302  // An item from before prompts were numbered has none: the first match, as it always was.
303  const newest = Math.max(...fits.map(x => Number(x.prompt) || 0))
304  const pick = new Set(newest ? fits.filter(x => Number(x.prompt) === newest).map(x => x.id) : [fits[0].id])
305  return { ...ledger, items: ledger.items.map(x => (pick.has(x.id) ? { ...x, turnId } : x)) }
306}
307
308// `queued`: typed over a running turn. Such a message can still be pulled back out of the
309// queue (Up edits it) and never reach the model; see `withdrawn` below.
310// `prompt`: the message it came from (addPrompt). `asIs`: the text is already an item's.
311export function addItem(ledger, { text, at, turnId, source, queued, prompt, by, asIs }) {
312  const seq = (Number(ledger.seq) || 0) + 1
313  const words = asIs ? String(text) : source === 'promise' ? excerpt(text) : requestItem(text)
314  const item = {
315    id: String(seq), text: words, at, ...(turnId ? { turnId } : {}), state: 'open', source,
316    ...(queued ? { queued: true } : {}), ...(prompt ? { prompt } : {}), ...(by ? { addedBy: by } : {}),
317  }
318  const items = [...ledger.items, item].slice(-KEEP_ITEMS)
319  return { ...ledger, seq, items }
320}
321
322const fresh = (i, nowMs) => nowMs - (Number(i.at) || 0) <= BAND_DAYS * DAY_MS
323export const openItems = (ledger, nowMs) => ledger.items.filter(i => i.state === 'open' && fresh(i, nowMs))
324
325// What the record and the band say: open requests, open promises, the oldest open of each.
326export function ledgerSummary(ledger, nowMs) {
327  const open = openItems(ledger, nowMs)
328  const req = open.filter(i => i.source !== 'promise')
329  const prom = open.filter(i => i.source === 'promise')
330  const oldest = list => list.length ? { id: list[0].id, text: excerpt(list[0].text, 80), at: list[0].at } : null
331  // A failure is shown while something is open: with nothing open it has cost nothing, and
332  // a hand-cleared ledger would otherwise go on saying so until the next judged turn.
333  const j = req.length || prom.length ? ledger.judge : null
334  return {
335    open: req.length, promises: prom.length, oldest: oldest(req), oldestPromise: oldest(prom),
336    judgeFailing: j && j.ok === false ? excerpt(j.why, 80) : null,
337  }
338}
339
340// Is there anything for the judge? Open items, or an answer that sounds like a commitment.
341// The regex is only a cheap door in front of the model call, never the decision: it lets a
342// turn that promises nothing go by without one.
343const PROMISE_WORDS = /\b(I'll|I will|I'm going to|I am going to|next,? I|then I|once .{1,60}(I'll|I will)|when .{1,60}(I'll|I will)|later|after (that|this|CI|the))\b/i
344export const soundsLikeAPromise = answer => PROMISE_WORDS.test(String(answer || ''))
345
346// What a turn said: every text block it wrote, in order, one per model step that wrote any.
347// `turn.complete`'s `answer` is only the LAST of them, and judged alone it lost the work:
348// a turn wrote a post in its first block, ran two commands, and ended "the draft is above",
349// and the judge, shown that line with nothing above it, kept the request open and the gate
350// re-prompted for a reply the person had just read. `steps` are the texts the turn's steps
351// returned; `answer` is the turn's final text, the whole record when the steps were missed
352// (the module reloaded mid-turn) and appended when the last step did not end on it.
353export function turnBlocks(steps, answer) {
354  const blocks = (steps || []).map(s => String(s || '')).filter(s => s.trim())
355  const last = String(answer || '')
356  if (last.trim() && (!blocks.length || blocks[blocks.length - 1].trim() !== last.trim())) blocks.push(last)
357  return blocks
358}
359
360// The turn as the judge reads it: each block labelled with its place, and a long turn cut
361// from the MIDDLE. The start is where the work tends to be (the draft, the answer) and the
362// end is where the turn reports; a tail-only cut drops exactly the half the report points at.
363const HEAD_SHARE = 0.4
364export function middleCut(s, n) {
365  const a = String(s || '')
366  if (a.length <= n) return a
367  const head = Math.floor(n * HEAD_SHARE)
368  const tail = n - head
369  return `${a.slice(0, head)}\n[… ${a.length - head - tail} characters from the middle of the turn left out …]\n${a.slice(-tail)}`
370}
371export function turnText(blocks, n) {
372  const list = typeof blocks === 'string' ? [blocks] : blocks || []
373  const text = list.length > 1 ? list.map((b, k) => `[block ${k + 1} of ${list.length}]\n${b}`).join('\n\n') : String(list[0] || '')
374  return middleCut(text, n)
375}
376
377// The one judge call: which open items the turn addressed, and what it promised. Inputs are
378// truncated: item texts to EXCERPT, the turn to ANSWER_CHARS, an earlier turn to EARLIER_CHARS.
379// `turn` is the turn's blocks (turnBlocks), or one string for a turn of one block.
380export const ANSWER_CHARS = 6000
381export const EARLIER_CHARS = 1500
382export function judgePrompt(items, turn, { promises, earlier = [], openPromises = [] }) {
383  const blocks = typeof turn === 'string' ? [turn] : turn || []
384  const tail = turnText(blocks, ANSWER_CHARS)
385  const final = blocks.length > 1 ? `the LAST block (${blocks.length} of ${blocks.length})` : 'the message'
386  const before = earlier.slice(-2).map(t => turnText(t, EARLIER_CHARS))
387  const list = items.length
388    ? items.map(i => `${i.id} [${i.source === 'promise' ? 'promise the agent made' : 'request to the agent'}]: ${excerpt(i.text)}${
389      (i.replies || []).map(r => ` (the person answered: "${r.text}")`).join('')}`).join('\n')
390    : '(none)'
391  return [
392    'You audit an AI coding agent. Below are items it owes, and everything it wrote in the turn it just ended.',
393    '',
394    'ITEMS:',
395    list,
396    '',
397    ...(before.length ? ['EARLIER TURNS (oldest first; an item answered here is answered):', ...before.map(t => `<<<\n${t}\n>>>`), ''] : []),
398    `THIS TURN (every text block the agent wrote, in order; its tool calls and their output ran between blocks and are left out; ${final} is how it ended):`,
399    '<<<',
400    tail,
401    '>>>',
402    '',
403    'For EACH item decide:',
404    '- "done": the turn (any block of it) or an earlier turn did it, answered it, or reports it completed. Work written in an earlier block counts: "the draft is above" in the last block refers to a draft in an earlier one.',
405    '- "done" also, with reason "reported: waiting on <what>", when the agent did everything the item asks of it and says plainly that only something outside its control remains (a registry or deploy propagating, a review) with nothing more for the agent to do.',
406    '- "in-progress": the turn reports THIS item\'s current state and says the work is still going on elsewhere or waits on something, with a step still owed after it. E.g. "dry run done; the build is running in a worker, I\'ll ship it when it lands", "CI is running on the PR", "waiting on your pick between A and B". Work the agent could do now and simply did not is not this: it is "open". When what it waits on is the PERSON (their pick, their files, their action), the reason says so: "waits on the person: <what>".',
407    '- "not-done": the agent explicitly says THIS item was not or cannot be done AND gives a reason. A refusal with no reason, or one that does not say which request it means, is "open".',
408    '- "open": the turn did not address the item: not mentioned, or only acknowledged ("on it"), or partly done with no word on the rest. E.g. two requests, and the turn only answers the first: the second is "open".',
409    'Judge an item by what it asked for NOW: a part it explicitly put off ("not in this reply", "later", "after X") is not owed yet.',
410    'An item may open with material the person pasted with no marker (a draft, a log, a transcript) and end with their own words: judge what THOSE words ask. A question ("what do you think?") is "done" once the agent answers it; an answer that ends by offering more or asking something back does not reopen it.',
411    'An item is the person\'s own words. "[+ pasted text]" means they also pasted material (a transcript, a log, an earlier reply) as context for those words: the material is not a request of its own, and a "[ghostfleet ledger]" reminder quoted in it is this tool talking, never a request. Judge what the person\'s own words ask; a remark about the paste ("see what it did") asks for the agent to look at it, and is done once the agent has.',
412    'An item that only approves, confirms or thanks ("go ahead", "yes", "thanks") asks for no work of its own: it is "done" once the agent acts on what it approved, or if there is nothing to act on. An item that confirms AND asks ("done, now draft the post") is judged by what it asks.',
413    ...(promises === 'off'
414      ? ['Return "promises": [] always.']
415      : [
416        `Also list "promises", from ${final} only: things the AGENT says IT WILL DO LATER in this session ("I'll merge once CI is green", "next I'll add the tests"), each as a short imperative phrase of at most 12 words. Only a firm commitment to a specific action: not work it already did, not suggestions for the user, not questions, not offers that wait on the user ("I can do X if you'd like"), not statements about how it will behave in general ("I'll keep responding normally").`,
417        'A promise is something the AGENT will do. What it asks the PERSON to do is never a promise: "you run X", "type X", "waiting on you", and every line of a list under "still waiting on you" or "for you to do". If you list one anyway, mark it "by":"person".',
418        'Waiting is never a promise: "I\'ll wait for your reply", "awaiting your answer", "once you decide I\'ll proceed" are the agent waiting on the person. Nor is the follow-through of an item you judged "in-progress" ("I\'ll ship it when the worker lands" for that item): give that item\'s id as "same".',
419        ...(openPromises.length
420          ? ['ALREADY OPEN PROMISES (one commitment is one promise, however it is worded):',
421            ...openPromises.map(i => `${i.id}: ${excerpt(i.text, 120)}`),
422            'A promise in this turn that restates one of these (the same follow-up in other words, or narrower or wider) is that promise: give its id as "same". Only a different commitment has "same":"".']
423          : []),
424        '[] if none.',
425      ]),
426    '',
427    'Also say "waitingOnPerson": true when the turn ENDS by asking the person a question or waiting on their decision or action ("which do you want?", "pick one of A, B, C", "tell me when it is deployed"); false otherwise, and false for an answer that merely closes with an offer ("want me to do more?").',
428    '',
429    'Reply with ONLY this JSON, no prose, no code fence:',
430    `{"items":[{"id":"<id>","status":"done|in-progress|not-done|open","reason":"<at most 12 words>"}],"waitingOnPerson":false,"promises":[${promises === 'off' ? '' : '{"text":"<at most 12 words>","by":"agent|person","same":"<open promise or in-progress item id, or empty>"}'}]}`,
431  ].join('\n')
432}
433
434// The judge's reply, held to the shape asked for. null when nothing in it has that shape: the
435// gate fails OPEN on null (nothing closes, nothing is re-prompted).
436//
437// A reply cut off by its token budget still carries every item object it finished. Measured
438// live: a ledger of 46 open items asked for 46 verdicts in 700 tokens, the reply stopped
439// partway through, and dropping the whole reply on its missing brace closed nothing, so the
440// backlog only grew and every later turn failed the same way. So the finished objects are
441// kept, `partial` says the reply was cut, and an item it never reached is simply not judged.
442const ITEM_OBJ = /\{[^{}]*"id"[^{}]*\}/g
443const STATUSES = ['done', 'in-progress', 'not-done', 'open']
444export function parseVerdict(text, ids) {
445  const s = String(text || '')
446  const a = s.indexOf('{'), b = s.lastIndexOf('}')
447  if (a < 0) return null
448  let v = null
449  if (b > a) try { v = JSON.parse(s.slice(a, b + 1)) } catch {}
450  let partial = false
451  if (!v || typeof v !== 'object' || !Array.isArray(v.items)) {
452    const list = s.indexOf('"items"', a)
453    if (list < 0) return null
454    const found = []
455    for (const m of s.slice(list).matchAll(ITEM_OBJ)) { try { found.push(JSON.parse(m[0])) } catch {} }
456    if (!found.length) return null
457    // the promises list, when the reply got as far as closing it
458    const pm = s.match(/"promises"\s*:\s*(\[[^\]]*\])/)
459    let promises = []
460    if (pm) try { promises = JSON.parse(pm[1]) } catch {}
461    v = { items: found, promises, waitingOnPerson: /"waitingOnPerson"\s*:\s*true/.test(s) }
462    partial = true
463  }
464  const known = new Set(ids)
465  const items = []
466  for (const it of v.items) {
467    if (!it || !known.has(String(it.id))) continue
468    const status = String(it.status || '')
469    if (!STATUSES.includes(status)) continue
470    items.push({ id: String(it.id), status, reason: excerpt(it.reason, 120) })
471  }
472  if (partial && !items.length) return null
473  // Each promise as { text, same? }: a plain string (the shape before `same`) is a new one, and
474  // one the judge says is the PERSON's to do is not a promise at all.
475  const promises = (Array.isArray(v.promises) ? v.promises : [])
476    .map(p => (p && typeof p === 'object' ? p : { text: p }))
477    .filter(p => String(p.by || 'agent').toLowerCase() !== 'person')
478    .map(p => ({ text: excerpt(p.text, 120), ...(p.same ? { same: String(p.same) } : {}) }))
479    .filter(p => p.text && !addressedToPerson(p.text) && !waitsOnPerson(p.text)).slice(0, 3)
480  return { items, promises, waitingOnPerson: v.waitingOnPerson === true, ...(partial ? { partial: true } : {}) }
481}
482
483// The judge asks about at most JUDGE_BATCH items per call, the newest first. One verdict is
484// one {"id","status","reason"} object per item. Measured on haiku: 46 items in one call took
485// 1,737 output tokens (38 an item) against the 700 the call allowed, so it was cut off.
486// Batches of ten took 325-343, and the first batch, the one that also reads promises, 589:
487// 84% of 700, too close. So ten a call, and 1,500 tokens each, over twice the worst measured.
488// The budget is a ceiling, not a cost: a call is billed for what it writes.
489export const JUDGE_BATCH = 10
490export const JUDGE_TOKENS = 1500
491export function judgeBatches(items, n = JUDGE_BATCH) {
492  const newest = [...items].sort((x, y) => (Number(y.at) || 0) - (Number(x.at) || 0) || Number(y.id) - Number(x.id))
493  const out = []
494  for (let k = 0; k < newest.length; k += n) out.push(newest.slice(k, k + n))
495  return out
496}
497
498// A promise is not gated by default, it is only shown, and one no turn ever addresses would
499// stay on the band for the full BAND_DAYS. So a promise the judge was shown and kept open in
500// STALE_TURNS judged turns closes as `stale`. Five: a "once CI is green" spans a turn or two
501// of other work; five turns that never mention it is a commitment the session has dropped.
502export const STALE_TURNS = 5
503
504// One commitment is one promise. Measured live: four open promises were one follow-up in
505// four phrasings, added on three consecutive turns ("read the ledgers after the next turns",
506// "watch for re-prompt closure in acme-api and acme-web", "check acme-api, acme-web, toolbox
507// ledgers after next turns", "read acme-api, acme-web, toolbox ledgers ..."): the judge was
508// never told which promises were open, kept the old one open (correctly) and extracted the
509// same commitment again in new words, and the only check was exact text. The judge now sees
510// the open promises and names the one a phrase restates (`same`); this is the backstop for
511// when it does not. Two phrasings are one promise when they share at least two content
512// words and those are at least SAME_SHARE of the shorter one's. Verbs of looking are one
513// verb, and a plural is its singular. On the four above, any two linked through a third:
514// the first and second share only the verb (1 of 4). So a promise keeps the phrasings folded
515// into it (`said`, the last SAID_KEPT) and a new one is matched against all of them; and when
516// a new phrasing matches two open promises, they were one all along and fold into the older.
517export const SAME_SHARE = 0.6
518const SAID_KEPT = 4
519const STOP = new Set('a an the to of in on at for and or then once when after before with by from it its is be this that these those any all i ill will we me my our up out as so just again'.split(' '))
520const LOOK = new Set(['read', 'check', 'watch', 'look', 'review', 'verify', 'inspect', 'monitor', 'confirm', 'see'])
521export function promiseWords(text) {
522  return new Set(String(text || '').toLowerCase().replace(/[’']/g, '').split(/[^a-z0-9.\-/]+/)
523    .map(w => w.replace(/^[.\-/]+|[.\-/]+$/g, ''))
524    .filter(w => w && !STOP.has(w))
525    .map(w => (LOOK.has(w) ? 'check' : w.length > 3 && w.endsWith('s') && !w.endsWith('ss') ? w.slice(0, -1) : w)))
526}
527export function samePromise(a, b) {
528  const x = promiseWords(a), y = promiseWords(b)
529  const shared = [...x].filter(w => y.has(w)).length
530  return shared >= 2 && shared / Math.min(x.size, y.size) >= SAME_SHARE
531}
532
533// What the agent asks the PERSON to do is not its promise. Measured live: "Run npm login &&
534// npm publish" and "Type /reload-plugins between turns" became promises, read off a closing
535// "Still waiting on you:" list. The prompt says so; this catches a phrase that names the
536// person outright.
537export const addressedToPerson = text => /\b(you|your|yourself)\b/i.test(String(text || ''))
538
539// Waiting on the person is not a promise either: "wait for the user's reply" kept on the band
540// as something the agent owes is the person's move dressed as the agent's, and it would stay
541// open until it went stale. The prompt says so; this catches the phrasings that name no
542// "you" for the test above to find ("await the user's answer", "once they decide").
543const WAITS = /\b(wait(?:ing)?|await(?:ing)?|hear(?:ing)? back|stand(?:ing)? by)\b(?:(?![.;]).)*\b(user|person|owner|reply|replies|answer|answers|decision|decides?|response|confirm\w*|go-?ahead|approv\w*|input|pick|choice)\b/i
544const UPON = /^(once|when|after|if|until) (the )?(user|person|owner|they) (decides?|repl(y|ies)|answers?|confirms?|picks?|chooses?|approves?|responds?)\b/i
545export const waitsOnPerson = text => WAITS.test(String(text || '')) || UPON.test(String(text || '').trim())
546
547// At most PROMISE_CAP open promises: a new one past it stales the oldest. Promises are shown,
548// not gated, and five is already more than a band row or a person can keep in view.
549export const PROMISE_CAP = 5
550
551// The verdict applied: judged items close, promises join as items of their own. A promise
552// the judge says restates an open one (`same`), or that reads as one (samePromise), is that
553// promise, never a second; its newer words replace the older ones only when the judge said so.
554// An item judged in-progress stays open and carries `progress`, which the gate reads: it is
555// being worked, and naming it again only gets the same report back. A promise whose words
556// are the follow-through of such an item ("ship it when the worker lands") is that item.
557export function applyVerdict(ledger, verdict, { nowMs, turnId, promises }) {
558  const by = new Map(verdict.items.map(i => [i.id, i]))
559  let next = {
560    ...ledger,
561    items: ledger.items.map(i => {
562      const v = by.get(i.id)
563      if (!v) return i
564      if (DORMANT.has(i.state)) return revisited(i, v, nowMs, turnId)
565      if (i.state !== 'open') return i
566      // Not a turn that ignored it: its count towards going stale starts again. Measured: a
567      // promise reported on ("#12 merged; #13 awaiting") went stale five turns later on the
568      // count it had before the report, and from stale nothing could close it.
569      if (v.status === 'in-progress') {
570        const { keptOpen, ...rest } = i
571        const progress = { at: nowMs, ...(turnId ? { turnId } : {}), ...(v.reason ? { reason: v.reason } : {}) }
572        return waitsOnPersonNote(v.reason) ? { ...rest, state: 'waiting', progress } : { ...rest, progress }
573      }
574      if (v.status === 'open') {
575        if (i.source !== 'promise') return i
576        const kept = (Number(i.keptOpen) || 0) + 1
577        return kept < STALE_TURNS ? { ...i, keptOpen: kept }
578          : { ...i, keptOpen: kept, state: 'stale', closedAt: nowMs, closedBy: 'judge', reason: `no turn addressed it in ${kept} judged turns` }
579      }
580      return { ...i, state: v.status, closedAt: nowMs, closedBy: 'judge', ...(v.reason ? { reason: v.reason } : {}) }
581    }),
582  }
583  if (promises === 'off') return next
584  const openP = () => next.items.filter(i => i.source === 'promise' && i.state === 'open')
585  const close = (ids, reason) => {
586    next = { ...next, items: next.items.map(i => (ids.includes(i.id) ? { ...i, state: 'stale', closedAt: nowMs, closedBy: 'judge', reason } : i)) }
587  }
588  const working = next.items.filter(i => i.state === 'open' && i.source !== 'promise' && i.progress)
589  for (const p of verdict.promises) {
590    if (p.same && working.some(i => i.id === p.same)) continue
591    if (working.some(i => samePromise(i.text, p.text))) continue
592    const named = p.same && openP().find(i => i.id === p.same)
593    if (named) {
594      next = { ...next, items: next.items.map(i => (i === named ? { ...i, text: excerpt(p.text) } : i)) }
595      continue
596    }
597    const said = i => [i.text, ...(i.said || [])]
598    const like = openP().filter(i => said(i).some(t => t.toLowerCase() === p.text.toLowerCase() || samePromise(t, p.text)))
599    if (like.length) {
600      // The oldest keeps the commitment, and every phrasing of it; the others it bridges were
601      // the same one all along.
602      const keep = like[0]
603      const words = [...new Set([...(keep.said || []), ...like.slice(1).flatMap(said), p.text])].filter(t => t !== keep.text).slice(-SAID_KEPT)
604      next = { ...next, items: next.items.map(i => (i.id === keep.id ? { ...i, said: words } : i)) }
605      if (like.length > 1) close(like.slice(1).map(i => i.id), `same as promise ${keep.id}`)
606      continue
607    }
608    next = addItem(next, { text: p.text, at: nowMs, turnId, source: 'promise', prompt: Number(next.prompt) || 0 })
609  }
610  const over = openP().length - PROMISE_CAP
611  if (over > 0) close(openP().slice(0, over).map(i => i.id), `over the cap of ${PROMISE_CAP} open promises`)
612  return next
613}
614
615// DORMANT ITEMS STAY JUDGEABLE. `stale` was a dead end: the judge reads only open items, so a
616// promise that went stale was never judged again, and work that visibly finished later left it
617// stale for good. Measured on one lead's week: 23 stale promises, among them a "merge and
618// deploy #12 and #13 when CI passes" whose last note was "#12 merged; #13 awaiting", with both
619// merged a few turns on. Twenty of the 23 had gone stale over PROMISE_CAP, not over a count of
620// turns. So a stale or waiting item a turn MENTIONS (mentions) is shown to the judge with the
621// open ones, at most JUDGE_BATCH of them, newest first; one nobody mentions costs nothing.
622// A stale item untouched for EXPIRE_DAYS is retired (expireDormant): `expired`, never open,
623// never revisited. A waiting item is the person's, and waits as long as the band keeps it.
624//
625// WAITING ON THE PERSON. A turn that reports an item in progress because it waits on the
626// person ("the assembly waits on the user taking the screenshots") left it open, listed, in the prompt's
627// note, and named in reminders the agent could only answer with the same report. Such an item
628// is `waiting`: off every open count and the gate, until the person's message mentions it
629// (wakeWaiting) or answers the question about it (foldReply).
630export const DORMANT = new Set(['stale', 'waiting'])
631export const EXPIRE_DAYS = 3
632const PERSON = String.raw`(?:you\b|your\b|the\s+(?:user|person|owner|human)\b|(?:user|person|owner|human)\b)`
633const WAITS_NOTE = [
634  new RegExp(String.raw`\b(?:wait(?:s|ing|ed)?|await(?:s|ing|ed)?|blocked|depend(?:s|ing|ent)?|pending)\s+(?:on|for|upon)\s+${PERSON}`, 'i'),
635  new RegExp(String.raw`\bawait(?:s|ing)?\s+${PERSON}`, 'i'),
636  /\b(?:the\s+)?(?:user|person|owner)\s+(?:must|has to|needs to)\b/i,
637]
638export const waitsOnPersonNote = reason => WAITS_NOTE.some(re => re.test(String(reason || '')))
639
640// Does `text` speak to the item? Content words, with plural and tense set aside ("merged" is
641// "merge"). Loose (the person's own message): two shared words. Strict (a whole turn, which
642// shares two words with nearly anything): a shared number such as a PR's, or half the item.
643const stem = w => (w.length > 4 ? w.replace(/(?:ing|ed|es|e|s)$/, '') : w)
644const mentionWords = t => new Set([...promiseWords(t)].map(stem).filter(w => w.length >= 2))
645export function mentions(itemText, text, { loose = false } = {}) {
646  const x = mentionWords(itemText)
647  if (!x.size) return false
648  const y = mentionWords(text)
649  const shared = [...x].filter(w => y.has(w))
650  if (shared.length < 2) return false
651  return loose || shared.some(w => /\d/.test(w)) || shared.length >= 0.5 * x.size
652}
653const lastTouch = i => {
654  const t = [i.at, i.progress && i.progress.at, i.woke].filter(x => typeof x === 'number')
655  return t.length ? Math.max(...t) : 0
656}
657export function revisit(ledger, nowMs, text, n = JUDGE_BATCH) {
658  const t = String(text || '')
659  if (!t.trim()) return []
660  return ledger.items.filter(i => DORMANT.has(i.state) && fresh(i, nowMs)
661    && (i.state !== 'stale' || nowMs - lastTouch(i) <= EXPIRE_DAYS * DAY_MS) && mentions(i.text, t))
662    .sort((a, b) => Number(b.id) - Number(a.id)).slice(0, n)
663}
664export function expireDormant(ledger, nowMs) {
665  const old = ledger.items.filter(i => i.state === 'stale' && nowMs - lastTouch(i) > EXPIRE_DAYS * DAY_MS)
666  if (!old.length) return null
667  return {
668    ...ledger,
669    items: ledger.items.map(i => (old.includes(i)
670      ? { ...i, state: 'expired', expiredAt: nowMs, reason: `stale, untouched for ${EXPIRE_DAYS} days` } : i)),
671  }
672}
673// A verdict on a dormant item: done and not-done close it; in progress reopens it, or keeps it
674// waiting when what it waits on is still the person; "open" leaves it where it was.
675function revisited(i, v, nowMs, turnId) {
676  if (v.status === 'done' || v.status === 'not-done') return { ...i, state: v.status, closedAt: nowMs, closedBy: 'judge', ...(v.reason ? { reason: v.reason } : {}) }
677  if (v.status !== 'in-progress') return i
678  const progress = { at: nowMs, ...(turnId ? { turnId } : {}), ...(v.reason ? { reason: v.reason } : {}) }
679  return waitsOnPersonNote(v.reason) ? { ...i, state: 'waiting', progress } : { ...reopened(i), progress }
680}
681
682// The items the gate may re-prompt about: open, fresh, never gated before, from the latest
683// prompt's window (addPrompt); promises only when promises gate. An older item stays on the
684// band and in /ledger, closable by the agent, the judge or the person, and is never named
685// again: a session that moved on from it was answering what it was asked next, and a gate
686// that reached back made every turn's end about the backlog instead of the turn.
687//
688// An item a turn reported in progress (`progress`, applyVerdict) is never a target: "open"
689// lumped together the item a turn ignored and the item it reported on while the work went on
690// in a worker, and the gate re-prompted both. Seen live: the person picked options with a
691// three-word reply, the agent dispatched a worker to build them and ended on "dry run done,
692// the build is in progress in a worker, I'll ship it when it lands"; the judge kept it open
693// (correctly, it was not finished), the gate said "finish it now", and all the agent could do
694// was repeat the same report. Only the ignored item is owed a nudge.
695export function gateTargets(ledger, nowMs, { promises }) {
696  const from = Number(ledger.window) || 0
697  return openItems(ledger, nowMs).filter(i => !i.gated && !i.progress && from && Number(i.prompt) >= from
698    && (i.source !== 'promise' || promises === 'gate'))
699}
700
701// When a turn's end is not re-prompted at all, whatever is open; '' when the gate may go on.
702// Each is a turn whose re-prompt could only be answered with the report it just gave:
703//   gate-turn     the turn the gate's own re-prompt started. Its items are already gated, but
704//                 one judged open in the same prompt window would be named in a second
705//                 re-prompt straight after the first: the nag answering itself
706//   waiting       the turn ended asking the person something, or waiting on their decision
707//                 (the judge's `waitingOnPerson`): the next move is theirs, and a re-prompt
708//                 lands on top of the question they are reading
709//   cooldown      a re-prompt went out less than GATE_COOLDOWN_MS ago
710//   workers       a lead whose workers are still working, or waiting on a person (the band's
711//                 count): the report is the work's state, and it moves without the agent
712// NOT the session's own background shells. The engine hands them to Stop hooks
713// (`background_tasks`), but `classic.Stop` never reaches a user-tier mod: measured, the debug
714// log reads "ghostfleet: classic.Stop bypassed by cc-plugin-sec-default (tier user)" on every
715// turn, while the harness delivers it and a test of it passes. The footer's "1 shell still
716// running" is a pane regex, which is the guess this mod exists to replace.
717// Five minutes: a re-prompt's own turn and the one after it come well inside that, while a
718// separate ask the person makes later in the session is still owed its nudge. The window is
719// read from the items' `gatedAt`, so a reload does not reset it.
720export const GATE_COOLDOWN_MS = 5 * 60_000
721export const lastGateAt = ledger => Math.max(0, ...ledger.items.map(i => Number(i.gatedAt) || 0))
722export function gateHold({ gateTurn, waitingOnPerson, lastGate = 0, nowMs, workers = 0 }) {
723  if (gateTurn) return 'gate-turn'
724  if (waitingOnPerson) return 'waiting'
725  if (lastGate && nowMs - lastGate < GATE_COOLDOWN_MS) return 'cooldown'
726  if (workers > 0) return 'workers'
727  return ''
728}
729
730// The turn the gate's re-prompt started, by its text: what the gate submits opens with this
731// head, and a plugin's framed submit may arrive with its frame in front.
732export const GATE_HEAD = '[ghostfleet ledger]'
733export const isGateTurn = text => {
734  const t = String(text || '').trimStart()
735  return t.startsWith(GATE_HEAD) || /^The ghostfleet plugin sent a message:\s*\[ghostfleet ledger\]/.test(t)
736}
737
738// The queued items the model never received. A message typed over a running turn fires
739// prompt.submit at Enter and is then queued; Up pulls it back into the composer, and nothing
740// raises an event for that. Measured: the gate then re-prompted about a message the model
741// had never seen, and the model rightly said it was never asked. So before a re-prompt, a
742// queued item has to be found among the session's user messages; one that is not, with the
743// session idle and no later turn started, was withdrawn. (Resubmitted, it is a new item.)
744// Matched on the item's opening words: the item keeps an excerpt, the transcript the whole.
745//
746// An INTERRUPTED item is asked the same. Esc before the turn wrote anything rewinds the
747// message out of the conversation and hands it back to the composer; sent again, edited or
748// not, it is a second prompt.submit and so a second item. Measured live: one message the
749// person sent once (to their mind) was two items with the same excerpt, and the gate named
750// both. The transcript held one copy, the resend; the first was a sibling of it, off the
751// conversation. So one message in the transcript accounts for one item: an item is
752// withdrawn when the items from it onward that carry its words outnumber the messages that
753// do, and the newest keep the messages. Two sends of the same words that both reached the
754// model are two messages, and stay two items.
755//   `all`: every item in the ledger, which the later items are counted from.
756export function withdrawn(items, userTexts, all = items) {
757  const norm = t => oneLine(t).toLowerCase()
758  const texts = userTexts.map(t => norm(requestText(t)))
759  const asks = all.filter(i => i.source !== 'promise')
760  return items.filter(i => (i.queued || i.interrupted) && i.source !== 'promise').filter(i => {
761    const head = norm(i.text).replace(/…$/, '').split('…')[0].slice(0, 80)
762    if (!head) return false
763    const said = texts.filter(t => t.includes(head)).length
764    const from = asks.filter(x => Number(x.id) >= Number(i.id) && norm(x.text).includes(head)).length
765    return said < from
766  }).map(i => i.id)
767}
768
769// The person's items of a turn that was interrupted: the gate asks the transcript about
770// them before naming any (see `withdrawn`).
771export function markInterrupted(ledger, turnId, nowMs) {
772  if (!turnId || !ledger.items.some(i => i.turnId === turnId && i.state === 'open' && i.source !== 'promise')) return null
773  return {
774    ...ledger,
775    items: ledger.items.map(i => (i.turnId === turnId && i.state === 'open' && i.source !== 'promise'
776      ? { ...i, interrupted: true, ...(nowMs ? { interruptedAt: nowMs } : {}) } : i)),
777  }
778}
779
780export const dropItems = (ledger, ids) => ({ ...ledger, items: ledger.items.filter(i => !ids.includes(i.id)) })
781
782export function gatePrompt(items) {
783  const lines = items.map(i => `${i.id}. ${i.source === 'promise' ? '(you said you would) ' : ''}"${excerpt(i.text, 160)}"`)
784  return [
785    `${GATE_HEAD} ${items.length === 1 ? 'One request is' : `${items.length} requests are`} still open from this session:`,
786    ...lines,
787    `Finish each one now and close it with ${TOOL.close} and its proof, or say for each that it is not done and why (${TOOL.drop} if it was not a real ask; ${VIA_CLI}). (Asked once per item; it will not be asked again.)`,
788  ].join('\n')
789}
790
791export const markGated = (ledger, ids, nowMs) => ({
792  ...ledger,
793  items: ledger.items.map(i => (ids.includes(i.id) ? { ...i, gated: true, gatedAt: nowMs } : i)),
794})
795
796// ── the agent's own hand: the tools ledger_close, ledger_drop, ledger_add ──────
797//
798// The judge reads the turn's text and never its work: it cannot see that a commit landed or a
799// file was written, only whether the prose said so, and it costs a model call every turn that
800// leaves anything open. The agent knows what it did. So the agent closes its own items as it
801// finishes them, each with the proof that it is done, and the judge reads only what is still
802// open after that (register.js, judgeTurn): a turn whose agent closed everything costs no call.
803export const TOOL = { close: 'mcp__ghostfleet__ledger_close', drop: 'mcp__ghostfleet__ledger_drop', add: 'mcp__ghostfleet__ledger_add' }
804// The same three from Bash. A mod's tools are registered once, at session start, and
805// /reload-plugins reloads its code but not its tools: a session older than the tools was
806// told to call tools it did not have, and had no way to close anything. bin/fleet-ledger
807// edits the same file through the same functions, so the reminders name both.
808export const CLI = { close: 'fleet-ledger close <id> "<proof>"', drop: 'fleet-ledger drop <id> "<reason>"', add: 'fleet-ledger add "<ask>"' }
809const VIA_CLI = `no such tools in this session? the same from Bash: ${CLI.close}, ${CLI.drop}, ${CLI.add}`
810export const PROOF = 240
811
812// Open, and the dormant and retired states too: a stale promise whose work did land is
813// closed with its proof like any other.
814const CLOSABLE = new Set(['open', 'waiting', 'stale', 'expired'])
815// Each answers { ledger, said }: `ledger` null when nothing changed, `said` what the agent
816// reads back. A close needs proof, a drop a reason: an empty one is refused, not defaulted,
817// since "closed, because I say so" is the judge's failure in the agent's hand.
818function closeAs(ledger, id, state, field, why, { nowMs, turnId }) {
819  const it = ledger.items.find(i => i.id === String(id ?? '').trim())
820  if (!it) return { ledger: null, said: `ledger: no item ${id}` }
821  if (!CLOSABLE.has(it.state)) return { ledger: null, said: `ledger: item ${it.id} is already ${it.state}` }
822  const closed = { ...it, state, closedAt: nowMs, closedBy: 'agent', [field]: excerpt(why, PROOF), ...(turnId ? { closedTurn: turnId } : {}) }
823  return { ledger: { ...ledger, items: ledger.items.map(i => (i === it ? closed : i)) }, said: `ledger: ${it.id} ${state === 'done' ? 'closed' : 'dropped'}` }
824}
825export function closeByAgent(ledger, id, proof, ctx) {
826  if (!oneLine(proof)) return { ledger: null, said: `ledger: ${id} not closed: proof is required (a path, link, commit, PR number or command result)` }
827  return closeAs(ledger, id, 'done', 'proof', proof, ctx)
828}
829export function dropByAgent(ledger, id, reason, ctx) {
830  if (!oneLine(reason)) return { ledger: null, said: `ledger: ${id} not dropped: a reason is required` }
831  return closeAs(ledger, id, 'dropped', 'reason', reason, ctx)
832}
833// An ask the split missed joins the latest prompt's window, so the gate covers it too.
834export function addByAgent(ledger, text, { nowMs, turnId }) {
835  const t = excerpt(text)
836  if (!t) return { ledger: null, said: 'ledger: nothing added: the text was empty' }
837  const next = addItem(ledger, { text: t, at: nowMs, turnId, source: 'user', prompt: Number(ledger.prompt) || 0, by: 'agent', asIs: true })
838  return { ledger: next, said: `ledger: tracking ${next.seq}` }
839}
840
841// The note a prompt carries to the model, never shown the person: what is open, by id, and
842// the rule. Requests first, newest first (the message just sent is the one most likely to be
843// worked on), then promises; NOTE_ITEMS at most, each cut to NOTE_TEXT, so the note stays
844// under ~1.5k characters however long the backlog grows; the rest is a count and /ledger.
845// '' when nothing is open: a session with a clean ledger reads nothing extra.
846export const NOTE_ITEMS = 8
847export const NOTE_TEXT = 100
848export const NOTE_HEAD = '[ghostfleet ledger: open items]'
849export function contextNote(ledger, nowMs) {
850  const open = openItems(ledger, nowMs)
851  if (!open.length) return ''
852  const newest = (a, b) => Number(b.id) - Number(a.id)
853  const req = open.filter(i => i.source !== 'promise').sort(newest)
854  const prom = open.filter(i => i.source === 'promise').sort(newest)
855  const shown = [...req, ...prom].slice(0, NOTE_ITEMS)
856  const more = open.length - shown.length
857  return [
858    NOTE_HEAD,
859    ...shown.map(i => `${i.id} ${i.source === 'promise' ? '(you said you would)' : '(asked)'}: ${excerpt(i.text, NOTE_TEXT)}`),
860    ...(more > 0 ? [`+${more} more open (/ledger lists them)`] : []),
861    `When one is finished, call ${TOOL.close} with its id and the proof (a path, link, commit, PR number or command result). ${TOOL.drop} with a reason if it is not a real ask or the person cancelled it (${VIA_CLI}); ${TOOL.add} for an ask this list missed.`,
862  ].join('\n')
863}
864
865// By hand: `fleet-ledger close <id>` and `/ledger close <id>`. null when there is no such
866// open item.
867export function closeByHand(ledger, id, nowMs) {
868  const it = ledger.items.find(i => i.id === String(id))
869  if (!it || !CLOSABLE.has(it.state)) return null
870  return {
871    ...ledger,
872    items: ledger.items.map(i => (i === it ? { ...i, state: 'done', closedAt: nowMs, closedBy: 'person' } : i)),
873  }
874}
875
876// `clear` closes every open item by hand; the history stays in the file.
877export const clearOpen = (ledger, nowMs) => ({
878  ...ledger,
879  items: ledger.items.map(i => (i.state === 'open' ? { ...i, state: 'done', closedAt: nowMs, closedBy: 'person' } : i)),
880})
881
882const ago = ms => {
883  const s = Math.max(0, Math.round(ms / 1000))
884  return s < 60 ? `${s}s` : s < 3600 ? `${Math.round(s / 60)}m` : s < 86400 ? `${Math.round(s / 3600)}h` : `${Math.round(s / 86400)}d`
885}
886
887// The listing both the CLI and /ledger print.
888export function listing(ledger, nowMs, { all = false } = {}) {
889  const rows = (all ? ledger.items : openItems(ledger, nowMs))
890  const held = all ? 0 : ledger.items.filter(i => i.state === 'waiting' && fresh(i, nowMs)).length
891  const waits = held ? [`+${held} waiting on the person (all lists them)`] : []
892  const j = ledger.judge
893  const judged = !j ? [] : [j.ok
894    ? `last judge: ok${j.items ? `, ${j.items} item${j.items === 1 ? '' : 's'} in ${j.calls || 1} call${(j.calls || 1) === 1 ? '' : 's'}` : ''} (${ago(nowMs - j.at)} ago)`
895    : `last judge: FAILING, failed open: ${j.why} (${ago(nowMs - j.at)} ago)`]
896  if (!rows.length) return [all ? 'ledger: empty' : 'ledger: nothing open', ...waits, ...judged].join('\n')
897  const out = rows.map(i => {
898    const tag = i.source === 'promise' ? 'promise' : i.source
899    const by = i.state !== 'open' && i.closedBy ? `${i.closedBy === 'hand' ? 'person' : i.closedBy}: ` : ''
900    const said = i.proof || i.reason
901    const why = said || by ? `  (${by}${said ? excerpt(said, 80) : ''})`.replace(': )', ')') : ''
902    const working = i.state === 'open' && i.progress ? `  [in progress${i.progress.reason ? `: ${excerpt(i.progress.reason, 60)}` : ''}]` : ''
903    return `${i.id.padStart(3)}  ${i.state.padEnd(8)} ${tag.padEnd(7)} ${ago(nowMs - i.at).padStart(4)}  ${excerpt(i.text, 100)}${i.gated ? '  [gated]' : ''}${working}${why}`
904  })
905  return [...out, ...waits, ...judged].join('\n')
906}
907
908// The band's ledger row as text runs, the longest form that fits `columns`:
909//   ledger · 2 open · oldest 4m "fix the login redirect…" · promise: merge when green
910// Narrower, the quote goes, then the promise's words, then everything but the counts. A judge
911// whose last call failed says so first, at every width: a failing judge closes nothing, and
912// a count that only grows was all the band showed of it.
913//   ledger · judge failing: reply was not the JSON asked for · 24 open · …
914export const LEDGER_COLOR = { open: '#ffd75f', promise: '#87afd7', failing: '#ff5f5f' }
915export function ledgerRuns(s, nowMs, columns) {
916  if (!s || (!s.open && !s.promises && !s.judgeFailing)) return null
917  const cols = Math.max(1, Number(columns) || 80)
918  const sep = { text: ' · ', dim: true }
919  const head = { text: 'ledger', dim: true }
920  const open = s.open ? { text: `${s.open} open`, color: LEDGER_COLOR.open, bold: true } : null
921  const fail = n => (s.judgeFailing
922    ? { text: n ? `judge failing: ${excerpt(s.judgeFailing, n)}` : 'judge failing', color: LEDGER_COLOR.failing, bold: true }
923    : null)
924  const age = s.oldest ? ago(nowMs - s.oldest.at) : ''
925  const quote = n => (s.oldest ? { text: `oldest ${age} “${excerpt(s.oldest.text, n)}”`, dim: true } : null)
926  const prom = n => (s.promises
927    ? { text: n && s.oldestPromise ? `promise: ${excerpt(s.oldestPromise.text, n)}${s.promises > 1 ? ` +${s.promises - 1}` : ''}`
928      : `${s.promises} ${s.promises === 1 ? 'promise' : 'promises'}`, color: LEDGER_COLOR.promise }
929    : null)
930  const tiny = [
931    s.judgeFailing ? { text: '✗', color: LEDGER_COLOR.failing, bold: true } : null,
932    s.open ? { ...open, text: `${s.open}○` } : null,
933    s.promises ? { text: `${s.promises}◇`, color: LEDGER_COLOR.promise } : null,
934  ]
935  const forms = [
936    [head, fail(60), open, quote(48), prom(40)],
937    [head, fail(40), open, quote(24), prom(24)],
938    [head, fail(24), open, s.oldest ? { text: `oldest ${age}`, dim: true } : null, prom(0)],
939    [head, fail(0), open, prom(0)],
940    [fail(0), open, prom(0)],
941    tiny,
942    [tiny.find(Boolean)],
943  ]
944  let runs = null
945  for (const parts of forms) {
946    runs = parts.filter(Boolean).flatMap((r, i) => (i ? [sep, r] : [r]))
947    if (runs.reduce((k, r) => k + [...r.text].length, 0) <= cols) return runs
948  }
949  return runs
950}
951
hooks/handoff.js 52 lines
1// The handoff spool's vocabulary, as plain functions: no `$`, no I/O. The DELIVERY section
2// of register.js uses them; bin/fleet-send and lib/mod-target.mjs write and read the same
3// names, and test/run.sh imports this file with node to hold the three to each other.
4//
5// <fleet dir>/<session_id>.handoff/
6//   <id>.json     a prompt fleet-send left for this session: { id, text, reply? }
7//   <id>.taken    claimed by the mod, being submitted
8//   <id>.done     the receipt: { id, turnId } once its turn started, or { dropped | error }
9//   <id>.revoked  fleet-send took it back unclaimed and pasted it instead
10//   .ready        the pid of the mod process that delivers from here
11// <id> starts with the epoch milliseconds it was written at, so names sort in send order.
12
13export const spoolOf = (dir, sessionId) => `${dir}/${sessionId}.handoff`
14
15const ID = /^[0-9]+[0-9A-Za-z._-]*$/
16export const entryId = (name, ext) =>
17  typeof name === 'string' && name.endsWith(ext) && ID.test(name.slice(0, -ext.length))
18    ? name.slice(0, -ext.length) : null
19
20// The prompts waiting, oldest first.
21export const waiting = entries => entries
22  .filter(e => e && e.kind === 'file').map(e => entryId(e.name, '.json')).filter(Boolean).sort()
23
24// A receipt is kept for an hour, then cleared by the next claim.
25export const KEEP_DONE_MS = 3_600_000
26export const staleReceipts = (entries, nowMs) => entries
27  .filter(e => e && e.kind === 'file' && entryId(e.name, '.done'))
28  .filter(e => nowMs - Number(e.name.match(/^[0-9]+/)[0]) > KEEP_DONE_MS)
29  .map(e => e.name)
30
31// The reply address an entry carries, or null. fleet-send validated it; it arrives here
32// through a file, so it is validated again with fleet-send's own charset.
33const NAME = /^[A-Za-z0-9._~-]+$/
34export function replyOf(entry) {
35  const r = entry && entry.reply
36  if (!r || !NAME.test(String(r.sock || '')) || !NAME.test(String(r.sess || ''))) return null
37  if (typeof r.dir !== 'string' || !r.dir.startsWith('/') || /[\n\x1f]/.test(r.dir)) return null
38  return { sock: r.sock, sess: r.sess, dir: r.dir }
39}
40
41// hooks/fleet-event.sh's reply-to marker and its arming, as that hook reads them: the
42// address as three \x1f-separated fields, and the arming as the transcript line the turn
43// starts at, with `turn <id>` on a second line, which tells the hook this arming is
44// exact and not to be redone by a prompt typed into the same turn.
45export const replyMarker = r => `${r.sock}\x1f${r.sess}\x1f${r.dir}\n`
46export const armedMarker = (lines, turnId) => `${lines}\nturn ${turnId}\n`
47
48// Whether a turn.start is the turn a submitted prompt began: the engine hands the hook the
49// user's text as the turn proceeds with it.
50export const isTurnOf = (pending, text) =>
51  Boolean(pending && typeof text === 'string' && text.trim() === String(pending.text).trim())
52
types/index.d.ts 29 lines
1// The values the ghostfleet mod keeps in $.state, as `claude plugin validate` holds them.
2
3/** What the lead's band draws (hooks/band.js): its team's counts and its PRs' checks. */
4export type Band = {
5  workers: number
6  working: number
7  need: number
8  /** undefined: not read yet; null: gh could not say. */
9  prs?: { green: number; red: number; pending: number } | null
10}
11
12/** What the ledger's row draws (hooks/ledger.js ledgerSummary), against `asOf`, a minute. */
13export type LedgerItemRef = { id: string; text: string; at: number }
14export type Ledger = {
15  open: number
16  promises: number
17  oldest: LedgerItemRef | null
18  oldestPromise: LedgerItemRef | null
19  /** Why the judge's last call failed open; null while it is working. */
20  judgeFailing: string | null
21  asOf: number
22}
23
24declare module 'claude-code' {
25  interface PluginState {
26    ghostfleet: { band: Band | null; ledger: Ledger | null }
27  }
28}
29