Claude Code agents that work like a company, with Jev picking the right model for each task to keep cost down.

<img src="docs/brand/flow-horizontal-color.svg" alt="flow" width="280">
flow is a Claude Code plugin that works through a batch of software tasks in parallel, inside your session. Managers plan each task. Workers build it, each in its own git worktree, and open pull requests. A reviewer merges them, runs your checks, cuts the release and deploys. You only make the decisions.
<a href="docs/demo/flow-demo.mp4"> <img src="docs/demo/flow-demo.gif" alt="flow demo: the Flow pane runs a crew of managers and workers in parallel; a question reaches your inbox, you answer it with one key, and everyone keeps going." width="800"> </a>
you ── main session
├── manager: csv-export one per task: plans, reviews, hands PRs over
│ ├── worker: csv-endpoint one per piece of work, in its own worktree
│ └── worker: csv-button
├── manager: login-redirect
│ └── worker: redirect-fix
└── reviewer merges PRs, runs the full check, deploys
<img src="docs/diagrams/architecture-light.svg" alt="flow architecture: you talk to the main session, which starts one manager per task; managers brief workers in their own worktrees, workers open PRs, and the reviewer merges them in batches. Below, the plugin's hooks: the mcp__flow__* tools, hooks/register.tsx, the inbox, the reviewer start, terminal sessions for mode orca or tmux, and the state in .git/flow.">
The parts: agents on top, the plugin's hooks and the state it keeps in .git/flow below. Interactive version (open the file in a browser for search, focus and the code links).
<img src="docs/diagrams/task-lifecycle-light.svg" alt="Life of a flow task: your request, a manager's pre-flight round, a worker's PR with a verification section, review and handover, the reviewer_delay wait, the reviewer batch (merge, full check, release, push), deploy gates and the report back; questions go to the inbox, and cleanup runs after each merged PR.">
One task, from your request to the report, with the inbox on the side. Interactive version; the steps and their code are in Life of a task.
In a Claude Code session:
/plugin marketplace add Ying-Kai-Liao/flow
/plugin install flow@flow
Run /flow init. It walks you through how flow works, shows a demo (a free replay in the Flow pane, or a real run that uses tokens) and sets the few settings that matter, detecting your test command and base branch for you. Run it again any time to see or change your settings.
Then ask for work in your main session:
Add CSV export to the reports page, and fix the login redirect loop.
Here is what happens next:
Type /flow to open a pane that shows who is doing what. For a single change, "start a worker to fix X" is enough.
| Command | What it does | ||
|---|---|---|---|
/flow init | A walkthrough, a demo and your settings. /flow init settings and /flow init demo jump to a part (the replay is free; /flow init demo live runs it for real and uses tokens). | ||
/flow | Opens the pane: managers, workers, and what needs you first. | ||
/flow inbox | Lists what waits for you: a summary line, the questions (blocking first, deploy/push/env marked NEEDS YOU), the decisions agents made as one flat table (newest 15; worker-size / manager-size decisions are filed already kept and only show in the archive, and those of finished agents are folded into one line; /flow inbox decisions lists all, /flow inbox d12 one item in full) and what standing answers did. /flow inbox archive lists the answered questions and kept or undone decisions, newest first (50; /flow inbox archive all lists every one). | ||
| `/flow ok [d10 d11 \ | owner \ | topic]` | Keeps decisions (no words: every open decision) or takes the default of an ordinary question. Never answers a deploy, push, env or guard item. |
/flow no d12 [what instead] | Undoes a decision; the agent is told what to do instead. | ||
/flow answer q3 <choice> | Answers any question addressed to main (option letter, number, text, or your own words), deploy, push and env items included. | ||
/flow checks | Lists the after-deploy checks that only a person can do as one table (id, PR, title, what it needs, age). /flow checks <id> shows one in full; pass, fail and skip <id...> <why> close them. | ||
/flow approve <n> | Approves PR n when it is waiting for you. | ||
/flow reject <n> [reason] | Turns down PR n while it awaits approval or is pending (alias /flow drop). The manager is told; the GitHub PR and branch are left alone. | ||
/flow push | Pushes the batch the reviewer built and checked, when push_mode is confirm. /flow push back <pr> returns one PR, /flow push drop all of them. | ||
/flow hold <target> / /flow release <target> | Keeps a deploy target from deploying, or lets it go again. | ||
/flow lite <task> | Runs one task in lite mode: just a manager and its workers, no pre-flight and no reviewer agent, to save tokens (see Lite mode in docs/how-it-works.md). | ||
/flow resume | Picks up unfinished work after a restart. | ||
/flow clean | Lists leftover worktrees and branches. Add --yes to remove them. |
With ask_cards on (the default), the main session is also told to show blocking questions, env changes and deploy approvals as AskUserQuestion cards; set it to off for plain text. Questions, approvals and checks also show up in the pane and as notifications. With anything open, press i in the pane to read and answer the inbox there (j/k move, a digit or letter picks an option, y takes the default or keeps a decision, w keeps all decisions, n undoes, r types an answer); you may answer any question, a manager's too. Pressing a row (or an open question or decision in the pane's tree) opens it as a large card with its full text, why, who asked and for whom, the asking agent's status and every option as a button (digits and letters are hotkeys, y the default or keep, n undoes a decision, the input takes your own words; b goes back, j/k move to the next item). The routine decisions sit in one folded row (y keeps all of them, x or pressing the row lists them) and v opens the archive. The key row sits at the pane's bottom.
The Reviewer section's PR lines are buttons too. Pressing one (or the "N awaiting approval" summary when the section is folded) opens the PR card: title, status, branch, head, who handed it over, why it waits for you, the manager's verified line, pending decisions, the after-deploy check, the stored evidence (Ran, Exercised, Not verified), env changes, and the changed files with +/- counts and the URL (read from gh in the background; "details unavailable" if gh fails). On a PR awaiting approval, a approves, r rejects (the input is an optional reason) and g opens it on GitHub; these run exactly what /flow approve and /flow reject run. Pressing the "ready to push" batch line opens the batch card: its PRs (press one for its card), p pushes, d drops, and send back then y returns one PR, as /flow push, /flow push drop and /flow push back <pr> do. b goes back.
flow works with no setup. Most people set a few things in .claude/flow.json at the repo root:
{
"test_command": "pnpm test",
"full_check_command": "pnpm check",
"deploy_targets": [{ "name": "staging", "deploy": ["./deploy.sh staging"] }],
"merge_mode": "confirm",
"max_workers": 3
}
| Setting | Set it when |
|---|---|
test_command | your repo has a test command workers should run for the files they change |
full_check_command | you have a full check (lint, build, the whole suite) the reviewer should run once per batch |
deploy_targets | you want the reviewer to deploy after merging. For one target, deploy_command is the shortcut |
merge_mode | you want to approve each handed-over PR yourself (confirm) instead of merging automatically |
push_mode | you want to approve each batch before it is pushed (confirm) |
release | you want each merged batch to bump the version and cut a changelog section |
manager_model, worker_model, max_workers | you want other models for managers or workers, or more or fewer parallel workers |
Anything you leave out is skipped and reported. flow never guesses a command. Everything else, with defaults, is in the reference.
mode orca or tmux, workers can also run in other coding tools, such as Codex. See Workers in other harnesses.mode orca or tmux. See Managers and the reviewer in a terminal.flow is a hooks module. It runs inside your Claude Code session and reaches the outside only through the engine's $ calls. This section lists what it sends, runs, writes and changes.
| To | What | When |
|---|---|---|
GitHub, through gh | reads PRs and their files, labels and diffs; creates the flow:confirm / flow:auto labels and puts them on a PR; creates a GitHub Release | the pane's PR list, handovers, /flow resume, /flow clean, a release with release_github on |
your origin, through git | git fetch; pushes a release tag; deletes a merged PR's branch, only once the merge is in origin/<base> | fetches as it works; the tag with release_github on; the delete when the reviewer reports a PR done |
| an OpenAI-compatible API | the brief or task text (its Size: line removed, at most 8000 characters), a fixed sizing question and its options, sent to openai_base_url (default https://api.openai.com/v1) with your openai_api_key | only when decision_api is openai, once per manager or worker start |
| TypeSafe's Jev | the same text and question, sent to jev_base_url (default https://api.typesafe.ai) with your typesafe_api_key | only when decision_api is jev, once per manager or worker start |
| OpenRouter (Jev route) | the same text and question, sent to openrouter_base_url (default https://openrouter.ai/api) with your openrouter_api_key | only when decision_api is jev, typesafe_api_key is empty and openrouter_api_key is set |
the same provider (jev or openai) | an inbox decision's text, or a worker's handoff note (at most 8000 characters), with a fixed question and its options | only when decide_inbox / decide_handoff is on and decision_api is jev or openai, once per recorded decision or handoff |
| its own agents in this session | messages, through $.session.send (see below) | while they run |
The two API calls go through the engine's $.http.fetch. With decision_api at off, the default, flow makes no HTTP request at all. The keys are /config options marked sensitive, so they are kept in secure storage; flow never reads them from your environment or a file, and they never appear in a note, log or prompt.
The hosts flow contacts:
api.openai.com, the default openai_base_url, only with decision_api at openai.api.typesafe.ai, the default jev_base_url, only with decision_api at jev.openrouter.ai, the default openrouter_base_url, only with decision_api at jev and only openrouter_api_key set.github.com, through gh and git (or wherever your origin points).The base URLs can be changed in /config; flow then contacts the host you set instead.
The agents flow starts do their own pushing and merging with git and gh, as their prompts say: workers push their branch and open a PR, the reviewer merges and pushes <base>.
The plugin runs these programs through $.process.run, each with a fixed argument list:
git: branches, worktrees (git worktree add/list/remove), fetch, log, diff, merge-base, a fast-forward of your main checkout after a batch (never a stash, reset or force), the release tag push and the merged-branch delete.gh: the PR, label and release calls in the table above.sh -c with a fixed script and the values passed as separate arguments: create or empty its state directories, append to its log, read $HOME to expand ~ in attachment paths, find a harness program on PATH.mkdir, rm, test, tail, find, ps: its own state files, and to tell a live worktree from a leftover in /flow clean.tmux or orca: only in mode orca or tmux, where every manager, worker and the reviewer is a terminal. They create the terminal, type the brief and messages into it, read its screen, and close it.claude --permission-mode bypassPermissions, codex --dangerously-bypass-approvals-and-sandbox, gemini --yolo or opencode, or the command you put in harnesses. The built-ins start with permission checks turned off. Such a worker runs unattended in its own worktree, and nobody sits at that terminal to approve a git push. This happens only in mode orca or tmux. In the default agent mode workers are in-session agents, and they keep the session's normal permission mode.quota command from your harnesses setting, to read how much quota is left.uname -s, once, and then open, xdg-open or explorer with a PR's URL: only when you press the PR card's open key in the pane.Your own commands are run by flow's agents through their Bash tool, under your permission mode, not by the plugin: test_command by workers, full_check_command and the deploy steps (deploy_command, deploy_targets, each target's env_command) by the reviewer.
hooks/guards.ts only reads the text of a shell command an agent is about to run, including what it runs through sh -c or eval, to refuse broad kills, remote-branch deletes and writes to the main checkout. It never downloads or runs anything.
flow writes these files on purpose:
.git/flow/ (shared by all worktrees, never committed): handovers, the inbox, the log, handoff digests, manager notes, person checks, deploy and push gates, the cost ledger, test-slot grant files and session worker prompt and report files. The full list is in the reference..git/flow/config.json, your personal settings: flow adds to it when you keep a standing answer (always), accept a seed or accept a suggested guard-test mapping. It removes a standing answer from .claude/flow.json only when you ask it to remove that rule. It never writes other settings..claude/worktrees/ for session workers. In-session workers and the reviewer get theirs from Claude Code.release on, done by the reviewer through mcp__flow__release): the changelog (changelog_file, default CHANGELOG.md) and the version in release_files (default package.json). Those are build files; flow changes them because cutting the release is its job.$.prompt.submit sends text to the main session as if typed: reports from the reviewer and managers, pre-flight rounds, new questions, plan and dependency notices, session worker reports, after-deploy checks for a new version, and what /flow resume, /flow lite and /flow-tasks ask the main session to do.$.prompt.fill puts a "Send a message to …" line in your prompt box when you press m on an agent in the pane. You send it or not.$.session.send sends messages to flow's own agents: a worker's questions to its manager, answers from you or main, decisions you undid, reviewer results, plan notices and the context wrap-up ("commit, push and hand off").flow:manager, flow:worker and flow:reviewer agent definitions in hooks/prompts.ts, filled with your settings. A session worker gets the worker rules and the brief in a prompt file.Size: line, or the decision API).| Hook | What it does |
|---|---|
session.start | Loads its state and settings, registers /flow, /flow-tasks, its agent types and its mcp__flow__* tools, starts its timers, then passes the event on. |
command.run (/flow, /flow-tasks) | Answers its own two commands. |
agent.offer (flow:continue) | Keeps the continue type offered, so its own rewrite below can start it. |
agent.spawn | Refuses: a model's own flow:continue spawn; a planned agent whose dependencies are not done; a worker whose manager has not filed its pre-flight; a Fable model; an attachment that does not exist. Changes: the prompt (lite rules, absolute attachment paths), the model (size routing; explore_model for a flow agent's Explore sub-agent with no model), a Continue on branch: worker into flow:continue in the old worktree, and a retry on the plain model when a [1m] model is refused. Then passes the spawn on. |
tool.call (every tool) | Refuses: pkill, killall and kills of pid -1, 0, 1 or a non-listening lsof lookup; a subagent's git push that deletes a remote branch; Edit and Write by a manager; with main_checkout_guard on, Edit, Write and shell writes aimed at the repo's main checkout (for the main session only while flow has a worktree or live agent in the repo). Answers a reviewer's SendMessage to an ended manager or a repeat to main itself. Otherwise records the call for the pane and passes it on unchanged. |
tool.call (mcp__flow__*) | Answers flow's own tools. It stands in for no built-in tool. |
turn.step | Delivers messages held for that agent, then measures its context and cost. |
turn.complete | Logs the agent's report, relays a reviewer's or manager's report to main, records a worker's handoff and starts a new reviewer when work is left. Passes the event on. |
config.set (theme) | Redraws the pane after a theme change. The setting itself passes on unchanged. |
ui.focus, ui.render | Draw the Flow pane and move its focus. |
/flow resume picks them up in a new session.claude --plugin-dir . # a session with your working copy loaded
npm ci # install TypeScript
npm run typecheck # must report 0 errors
npm run validate # must pass
npm run check # typecheck, validate and the plugin tests
Add your changelog lines under ## [Unreleased] in CHANGELOG.md. Don't change the version; the reviewer does that at merge. More in the reference.
MIT. See LICENSE.
hooks/register.tsx 3004 lines1// This file is the wiring only: atoms, `on(...)` hooks, `$.tool.register` calls, and io builders whose
2// closures spell out each `$.noun.event(...)` call. New logic goes into a module under hooks/, either
3// pure or taking an io object of closures (deliver.ts; pane-run.tsx holds the pane's hook bodies this way).
4// Which module holds each hook's body: docs/reference.md, "Where code goes".
5// The engine's rules: `$` never crosses an import (no imported function taking `$`, no `$`-taking closure
6// passed as an argument); a module may register its own hooks with an exported registerX(on, ctx) when
7// everything its hooks call with `$` is in that same file; atoms are declared with literal refs in each
8// file that uses them (the same key is the same state).
9import { atom, read, update } from 'claude-code'
10import { startSession } from './startup-run'
11import type { StartupIo } from './startup-run'
12import { parseMode } from './mergemode'
13import type { AgentInfo, EngineInterface, Register } from 'claude-code'
14
15import type { Activity, AgentRow, Breaker, Ledger, EnvChange, Handover, HandoffRecord, Leftovers, LogEvent, OpenPr, PrCache, Session, SlotEntry, TestSlots } from '../types'
16import { grantFile, grantSlots, reapSlots } from './slots'
17import { grantTypecheck, reapTypecheck, typecheckDir } from './typecheck-slots'
18import type { Evidence } from './evidence'
19import type { RunWork } from './mainff'
20import { NO_FAILS, type TestFails } from './testfail'
21import { occasionalDue, sweep as sweepTo } from './clean'
22import type { CleanInputs, CleanIo, Kept, PrRow, Sweep } from './clean'
23import { gatherLeftovers as gatherLeftoversTo } from './resume'
24import type { Gathered, Leftover, ResumeIo } from './resume'
25import { deliver as deliverTo, flushAgent as flushTo, holdForReviewer as holdTo, resetDelivery, ENDED, type DeliverIo, type DeliverOptions } from './deliver'
26import { addStep, addTurn, baseName, entriesOfBranch } from './cost'
27import { changeLedger as changeLedgerTo, costLines as costLinesTo, loadLedger as loadLedgerTo, mainKey as mainKeyTo, withCost as withCostTo } from './cost-run'
28import type { CostIo } from './cost-run'
29import { countStep, countTurn, meterStep, type UsageIo } from './usage-run'
30import { beforeStep, completeTurn } from './turn-run'
31import type { TurnIo } from './turn-run'
32import { backNote, effortFor } from './routing'
33import { sizeWith } from './spawn'
34import type { SizeJev } from './spawn'
35import { decide, DECIDE_TIMEOUT_MS, sourceOf } from './decide'
36import type { DecideIo, DecideSettings, FetchLike } from './decide'
37import { handoffLean } from './decide-use'
38import type { SpawnIo } from './spawn'
39import { onSpawn } from './spawn-run'
40import type { SpawnHookIo } from './spawn-run'
41import { agentFor, asksQuestion, noticeText, settle } from './dag'
42import type { AgentFact, Facts, Notice, Plan } from './dag'
43import {
44 answerMessage, EMPTY_INBOX, findItem, markAnswered, overridesManager, paneRows, needsMessage, normalizeInbox, notesOwner, endedOwners, FOLD_KEY,
45} from './inbox'
46import type { PaneRow } from './inbox'
47import {
48 closeStale, deliverRound, denyText, doneManagers, EMPTY_PREFLIGHT, gateOf, normalizePreflight, renderRound,
49} from './preflight'
50import type { Preflight } from './preflight'
51import { deployToolAccess, EMPTY_LITE, isLiteName, normalizeLite, releaseToolAccess, reviewerToolAccess } from './lite'
52import type { LiteState, ToolCaller } from './lite'
53import {
54 addChecks, anyMatch, EMPTY_CHECKS, normalizeChecks, parseNeeds,
55 SKIP_NOTE, versionInSteps,
56} from './checks'
57import type { Check, Checks } from './checks'
58import type { Inbox, Marked, Question } from './inbox'
59import { addGuardTest, dismissSuggestionIds, loadRules, offerSeedsOnce, offerSuggestionsOnce, paneSuggestions, standingTool, suggestGuardTests } from './standing-run'
60import type { StandingIo } from './standing-run'
61import { decideEvalTool } from './decide-eval-run'
62import { sizeAbTool } from './size-ab'
63import { armHidden, armsTool } from './bestof'
64import type { ArmsIo } from './bestof'
65import type { DecideEvalIo } from './decide-eval-run'
66import { DEMO_TOOL, SETTINGS_TOOL } from './init-tools'
67import { ANSWER_TOOL, ASK_TOOL, CHECK_TOOL, CLEAN_TOOL, DECIDE_EVAL_TOOL, DEPLOY_TOOL, FYI_TOOL, GUARD_TESTS_TOOL, HANDOVER_TOOL, MIGRATIONS_TOOL, NOTE_TOOL, PLAN_TOOL, PREFLIGHT_TOOL, PUSH_TOOL, RELEASE_TOOL, ARMS_TOOL, reviewerTool, SESSION_TOOL, SIZE_AB_TOOL, STANDING_TOOL, STATUS_TOOL, TEST_SLOT_TOOL } from './tools'
68import { detect as initDetect, firstRun, HINT as INIT_HINT, settingsTool, writeMarker } from './init'
69import type { InitIo } from './init'
70import { demoArm, demoMove, demoStart, demoStop, demoTool } from './demo-run'
71import type { DemoIo } from './demo-run'
72import type { DemoState } from './demo-replay'
73import { NO_SCROLL, paneDraw, paneFocus, paneScroll } from './pane-run'
74import type { PaneEvent, PaneFocusIo, PaneIo, PaneScrollIo } from './pane-run'
75import { approvePr, platformOfUname, rejectPr } from './prcard'
76import type { DetailsCache } from './prcard'
77import { ROLE } from './pane'
78import {
79 fill, REVIEWER_PROMPT, REVIEWER_SESSION_RULES_AUTO,
80 REVIEWER_SESSION_RULES_CONFIRM,
81} from './prompts'
82import type { Settings } from './prompts'
83import { deployTargetsOf, stateFileOf, targetsOf } from './prompts'
84import { renameOptions, settingsOf } from './settings'
85import { releaseTool } from './release-run'
86import type { ReleaseIo } from './release-run'
87import { FORWARDED_RIDS, mainHasAnswer as mainHasAnswerTo, managerFinished as managerFinishedTo, RELAY_DELAY_MS, resolveReportTo as resolveReportToTo, reviewerReport, reviewerSendGuard } from './reviewer-route'
88import type { Forwarded, RouteIo } from './reviewer-route'
89import { noteReached, noteReviewerEnd, onReviewerAnswer as onReviewerAnswerTo, releaseHalt as releaseHaltTo, reviewerToolRun, startQueue } from './reviewer-run'
90import { reconcileStale } from './stale-handovers'
91import type { StaleIo } from './stale-handovers'
92import type { BreakerIo, QueueIo, QueueWhy, ReviewerIo } from './reviewer-run'
93import { EMPTY_BREAKER, REVIEWER_KIND } from './reviewer-breaker'
94import { handoverTool } from './handover-run'
95import type { HandoverIo } from './handover-run'
96import { answerQuestionTo, noteText, paneInboxRowsTo, sizeBackNoteTo, tellMainTo, tellManagerTo, type MessagingIo } from './messaging-run'
97import { askTool, answerTool, fyiTool, preflightTool } from './inbox-run'
98import type { InboxIo } from './inbox-run'
99import { checkTool } from './checks-run'
100import type { ChecksIo } from './checks-run'
101import { isManagerOf, liveManagers, planOwner, refreshTo, syncPlansTo } from './roster-run'
102import type { RosterIo } from './roster-run'
103import { planTool } from './plan-run'
104import type { PlanIo } from './plan-run'
105import { testSlotTool } from './slots-run'
106import type { SlotsIo } from './slots-run'
107import { migrationsTool } from './migrations-run'
108import type { MigrationsIo } from './migrations-run'
109import { statusTool } from './status-run'
110import type { StatusIo, Unhanded } from './status-run'
111import { flowCommand } from './command'
112import type { CommandIo } from './command'
113import { elapsed, tokensDown, labelOf, thresholdOf, wrapUpText } from './meter'
114export { elapsed, tokensDown } from './meter'
115import { afterToolCall, beforeToolCall, guardTestsCase, mainCheckoutGuard as mainCheckoutGuardTo } from './toolcall-run'
116import type { GuardIo, GuardTestsCaseIo, ToolCallIo } from './toolcall-run'
117import { flowCatch, toolCatch } from './toolguard'
118import {
119 ago, harnessesOf, roleAgents, runsOutIn, sessionLive, sessionRow,
120} from './sessions'
121import type { HarnessSpec, Limit } from './sessions'
122import { sendToSession, sessionTool as sessionToolTo, startRoleSession, stopIdleSessions, watchSessions as watchSessionsTo } from './session-run'
123import { relayCall } from './relay'
124import type { MainIdentity, PumpIo, RelayIo } from './relay'
125import { alreadyForwardedTo, deliverToSessionTo, pumpOnceTo, relayToolCallTo } from './relay-run'
126import type { RelayExecIo, RelayMode, RelayRunIo } from './relay-run'
127import { adoptSessionsTo, durableSessions, identityTo, myRelaySessionsTo, normalizeSessions, onRoleGoneTo, onRoleReportTo, ownsSessionTo, persistSessionsTo, roleState } from './role-session-run'
128import type { RoleIo } from './role-session-run'
129
130import type { Caller, IdleIo, Ran, SessionIo } from './session-run'
131import { branchOwners, noteKey } from './state'
132import { ADD_OPTION } from './guardtests'
133import {
134 EMPTY_PUSH,
135} from './pushgate'
136import type { PushState } from './pushgate'
137import { onPushAnswer as onPushAnswerTo, pushAct as pushActTo, pushLines, recordReady as recordReadyTo, settleBatch as settleBatchTo } from './pushgate-run'
138import type { PushAct, PushIo } from './pushgate-run'
139import {
140 EMPTY_DEPLOYS, ENV_KIND,
141 release,
142} from './deploy'
143import { cap, CONTINUE, DEFAULT_WORKER_MODEL, isReviewer, LOG_MAX, MANAGER, mirror, NOTES_MAX, PANE, POLL_MS, TEXT_MAX, WORKER, WORKERS } from './core'
144import type { Deploys, Draft, Hold, TargetInfo } from './deploy'
145import {
146 closeReturnedEnv as closeReturnedEnvTo, deployTool as deployToolTo, envSettled as envSettledTo, holdTarget as holdTargetTo, onDeployAnswer as onDeployAnswerTo, onEnvAnswer as onEnvAnswerTo,
147 openHandoverEnv as openHandoverEnvTo, refreshBehind as refreshBehindTo, releaseTarget as releaseTargetTo,
148} from './deploy-run'
149import type { DeployIo } from './deploy-run'
150
151// The orca-flow pattern inside one Claude Code session. The main session is the super manager
152// (the `dispatch` skill); it starts `flow:manager` agents, which start
153// `flow:worker` agents in worktrees of their own and hand approved PRs to the
154// `flow:reviewer` agent through this plugin's tools. The pane in main shows the tree.
155
156
157const roster = atom({ plugin: 'flow', key: 'roster' } as const, [] as AgentRow[])
158const activity = atom({ plugin: 'flow', key: 'activity' } as const, {} as Record<string, Activity>)
159const selected = atom({ plugin: 'flow', key: 'selected' } as const, null as string | null)
160// The highlighted card of the tree (an agent id), and the collapse the person chose per card: true
161// is one row with its children hidden, false is expanded even when the tree is crowded. Absent =
162// the role's default (managers and the reviewer collapsed), else automatic. MERGE_QUEUE_KEY is the
163// Reviewer section's entry.
164const cursor = atom({ plugin: 'flow', key: 'cursor' } as const, null as string | null)
165const folded = atom({ plugin: 'flow', key: 'folded' } as const, {} as Record<string, boolean>)
166// Following the chat view: the view (an agent id, null for main) in which the person last acted in
167// the pane. While the view differs from it, the pane shows the viewed agent; written by handlers only.
168const overrideView = atom({ plugin: 'flow', key: 'overrideView' } as const, undefined as string | null | undefined)
169// Set once the first card click has told the person how to see that agent's chat.
170const hinted = atom({ plugin: 'flow', key: 'hinted' } as const, false)
171const now = atom({ plugin: 'flow', key: 'now' } as const, 0)
172const handovers = atom({ plugin: 'flow', key: 'handovers' } as const, {} as Record<string, Handover>)
173// The decision inbox, mirrored from <state dir>/inbox.json.
174// The last status and answer seen per agent name, so an agent the host drops from its list keeps its
175// last known state instead of reading as never started.
176const seenAgents = atom({ plugin: 'flow', key: 'seen-agents' } as const, {} as Record<string, AgentFact>)
177const inbox = atom({ plugin: 'flow', key: 'inbox' } as const, EMPTY_INBOX as Inbox)
178// Pre-flight records, mirrored from <state dir>/preflight.json.
179const preflight = atom({ plugin: 'flow', key: 'preflight' } as const, EMPTY_PREFLIGHT as Preflight)
180// Managers started in lite mode (lite.ts), mirrored from <state dir>/lite.json.
181const lite = atom({ plugin: 'flow', key: 'lite' } as const, EMPTY_LITE as LiteState)
182const checks = atom({ plugin: 'flow', key: 'checks' } as const, EMPTY_CHECKS as Checks)
183// Tokens spent per agent and model, mirrored (throttled) to <state dir>/ledger.json. Never forgets an ended agent.
184const ledger = atom({ plugin: 'flow', key: 'ledger' } as const, {} as Ledger)
185// Set once the disk history is merged into the ledger atom; the atom outlives a plugin reload, so this must too.
186const ledgerLoaded = atom({ plugin: 'flow', key: 'ledgerLoaded' } as const, false)
187// What this process counted since its last save, and the epoch of the file its base came from (see cost-run.ts).
188const ledgerDelta = atom({ plugin: 'flow', key: 'ledgerDelta' } as const, {} as Ledger)
189const ledgerEpoch = atom({ plugin: 'flow', key: 'ledgerEpoch' } as const, '')
190const handoffs = atom({ plugin: 'flow', key: 'handoffs' } as const, {} as Record<string, HandoffRecord>)
191const queueRuns = atom({ plugin: 'flow', key: 'queueRuns' } as const, 0)
192// When the reviewer_delay wait ends (0: no wait): the atom outlives a hook reload, which cancels the wait's timer.
193const reviewerDelayUntil = atom({ plugin: 'flow', key: 'reviewerDelayUntil' } as const, 0)
194// The reviewer respawn circuit breaker, mirrored from <state dir>/reviewer-breaker.json.
195const reviewerBreaker = atom({ plugin: 'flow', key: 'reviewerBreaker' } as const, EMPTY_BREAKER as Breaker)
196// The open PRs gh listed last, so the 3 s refresh never calls gh itself.
197const prCache = atom({ plugin: 'flow', key: 'prCache' } as const, { prs: [], fetchedAt: 0 } as PrCache)
198// The last dry cleanup sweep, refreshed with the PR list so a render never runs git.
199const sessions = atom({ plugin: 'flow', key: 'sessions' } as const, {} as Record<string, Session>)
200// What the reviewer routing already sent main, so a retried or repeated report reaches it once:
201// Scoped to the sending reviewer run (its agent id), so a later run's different outcome is never swallowed.
202// `keys` maps "reviewer|manager|PR numbers" to the needs-a-person / pending-decisions lines forwarded for it,
203// `lines` is, per reviewer id, every line forwarded (normalized). Persisted: plugins reload mid-session.
204const forwarded = atom({ plugin: 'flow', key: 'forwarded' } as const, { keys: {}, lines: {} } as Forwarded)
205const harnessLimits = atom({ plugin: 'flow', key: 'harnessLimits' } as const, [] as Limit[])
206const armed = atom({ plugin: 'flow', key: 'armed' } as const, null as { key: string; at: number } | null)
207const leftovers = atom({ plugin: 'flow', key: 'leftovers' } as const, { worktrees: 0, branches: 0, needsLook: 0 } as Leftovers)
208// Deploy gates, mirrored from <state dir>/deploys.json.
209const deploys = atom({ plugin: 'flow', key: 'deploys' } as const, EMPTY_DEPLOYS as Deploys)
210// Commits each target is behind the base, from git off the 3 s refresh path (refreshBehind).
211const behind = atom({ plugin: 'flow', key: 'behind' } as const, {} as Record<string, number>)
212// The ready batch awaiting the user's push, mirrored from <state dir>/push.json.
213const pushState = atom({ plugin: 'flow', key: 'push' } as const, EMPTY_PUSH as PushState)
214
215const PR_POLL_MS = 5 * 60_000
216// A worker that just ended: its manager is probably reviewing the PR.
217const GRACE_MS = 20 * 60_000
218const infosOf = (s: Parameters<typeof targetsOf>[0]): TargetInfo[] => targetsOf(s).map(t => ({ name: t.name, mode: t.mode, ...(t.envCommand !== undefined ? { envCommand: t.envCommand } : {}) }))
219
220
221// Open flow/* PRs that nobody handed to the reviewer and nobody is working on any more.
222// A draft is a WIP handoff, a pending/taken/done handover is in hand, a returned one needs a
223// manager again. The worker is the agent named like the branch, or its continuation (-2, -3).
224export function unhandedPrs(
225 prs: OpenPr[], handovers: Record<string, Handover>, roster: AgentRow[],
226 activity: Record<string, Activity>, t: number, graceMs = GRACE_MS, armPr?: (branch: string) => boolean,
227): Unhanded[] {
228 const out: Unhanded[] = []
229 for (const p of prs) {
230 if (p.isDraft || !p.headRefName.startsWith('flow/')) continue
231 const ho = handovers[String(p.number)]
232 if (ho !== undefined && ho.status !== 'returned') continue
233 // A best-of-N arm waits for its pick: not forgotten while the group is open, never owed once it lost.
234 if (armPr?.(p.headRefName) === true) continue
235 const slug = p.headRefName.slice('flow/'.length)
236 const mine = roster.filter(a => a.name === slug || (a.name?.startsWith(`${slug}-`) === true && /^\d+$/.test(a.name.slice(slug.length + 1))))
237 if (mine.some(a => !ENDED.has(a.status))) continue
238 const endedAt = Math.max(...mine.map(a => activity[a.id]?.endedAt ?? activity[a.id]?.lastAt ?? 0))
239 if (mine.length > 0 && endedAt > 0 && t - endedAt < graceMs) continue
240 const last = mine.length > 0 ? mine.reduce((x, y) => (activity[y.id]?.endedAt ?? 0) >= (activity[x.id]?.endedAt ?? 0) ? y : x) : undefined
241 const note = ho !== undefined ? `returned: ${ho.reason ?? ''}`
242 : last === undefined ? 'no agent in this session'
243 : `no handover, worker ${labelOf(last)} ended${endedAt > 0 ? ` ${ago(t - endedAt)} ago` : ''}`
244 out.push({ pr: p.number, title: p.title, branch: p.headRefName, note })
245 }
246 return out
247}
248
249async function currentUnhanded($: EngineInterface): Promise<Unhanded[]> {
250 if (!mirror.queueOn) return []
251 const clockNow = $.clock.now()
252 const [cache, hs, rows, acts, t] = await Promise.all([
253 read($, prCache), read($, handovers), read($, roster), read($, activity), clockNow,
254 ])
255 await loadLedger($)
256 const l = await read($, ledger)
257 // The log is read only once an arm exists: this runs on every pane tick.
258 const armLog = Object.values(l).some(r => r.arm !== undefined) ? await readLog($) : []
259 const armPr = armHidden(l, armLog, name => rows.some(a => a.name !== undefined && baseName(a.name) === baseName(name) && !ENDED.has(a.status)))
260 return unhandedPrs(cache.prs, hs, rows, acts, t, undefined, armPr)
261}
262const plan = atom({ plugin: 'flow', key: 'plan' } as const, {} as Plan)
263// The pane draws the agents as a tree of cards or as the dependency graph; the graph's highlight is a node id.
264const viewMode = atom({ plugin: 'flow', key: 'viewMode' } as const, 'tree' as 'tree' | 'graph' | 'inbox' | 'card' | 'archive' | 'pr' | 'batch')
265// The PR card (prcard.ts) and the batch card: the PR shown, where Back goes, the PR picked to send back, and the gh details by PR and head.
266const prShown = atom({ plugin: 'flow', key: 'prShown' } as const, null as number | null)
267const prBack = atom({ plugin: 'flow', key: 'prBack' } as const, 'tree' as 'tree' | 'batch')
268const batchPick = atom({ plugin: 'flow', key: 'batchPick' } as const, null as number | null)
269const prDetails = atom({ plugin: 'flow', key: 'prDetails' } as const, {} as DetailsCache)
270// The inbox view: the highlighted row's key, the typed answer and the last result line.
271const inboxCursor = atom({ plugin: 'flow', key: 'inboxCursor' } as const, null as string | null)
272// The card view: the highlighted id is inboxCursor; Back returns to where the card was opened from.
273const cardBack = atom({ plugin: 'flow', key: 'cardBack' } as const, 'inbox' as 'tree' | 'inbox' | 'archive')
274// Which inbox cards are open, by fold key (grp:<owner>, fold): true is open; a key not here takes the card's default.
275const inboxFolds = atom({ plugin: 'flow', key: 'inboxFolds' } as const, {} as Record<string, boolean>)
276// Which inbox items are expanded into cards, by item id; a key not here is collapsed. Ids of items that left the list linger harmlessly.
277const inboxOpen = atom({ plugin: 'flow', key: 'inboxOpen' } as const, {} as Record<string, boolean>)
278const inboxDraft = atom({ plugin: 'flow', key: 'inboxDraft' } as const, '')
279const inboxNote = atom({ plugin: 'flow', key: 'inboxNote' } as const, '')
280const graphFocus = atom({ plugin: 'flow', key: 'graphFocus' } as const, null as string | null)
281// The scrolled offset of a large card's body, by card (pane-run.tsx paneScroll).
282const cardScroll = atom({ plugin: 'flow', key: 'cardScroll' } as const, NO_SCROLL as { key: string; top: number })
283const testSlots = atom({ plugin: 'flow', key: 'testSlots' } as const, { holders: [], waiters: [] } as TestSlots)
284// Its own key, so state persisted before this pool existed loads as empty.
285const typecheckSlots = atom({ plugin: 'flow', key: 'typecheckSlots' } as const, { holders: [], waiters: [] } as TestSlots)
286
287// <git-common-dir>/flow/test-slots, set at session start; undefined when not in a git repo.
288let slotDir: string | undefined
289// A declared function, not a closure in the startup io: no io hands out a closure assigning an outer variable (plain-names check 10).
290function setSlotDir(dir: string | undefined): void {
291 slotDir = dir
292}
293
294// Applies `pre`, reaps, grants, and signals: a grant file and a message per new holder, the files
295// of everyone who left the line removed. Every slot change goes through here, inside one update().
296async function settleSlots($: EngineInterface, rows: AgentRow[], t: number, pre: (s: TestSlots) => TestSlots = s => s, me?: string): Promise<void> {
297 const notes: string[] = []
298 let granted: SlotEntry[] = []
299 let left: string[] = []
300 await update($, testSlots, st => {
301 notes.length = 0
302 const r = reapSlots(pre(st), rows, t)
303 const g = grantSlots(r.state, mirror.slotLimit, t)
304 notes.push(...r.notes, ...g.notes)
305 // The caller of acquire is here to hear it: its grant is confirmed on the spot, with no signal.
306 const state = me === undefined ? g.state
307 : { ...g.state, holders: g.state.holders.map(holder => holder.key === me ? { ...holder, claimed: true } : holder) }
308 granted = g.granted.filter(holder => holder.key !== me)
309 const stay = new Set([...state.holders, ...state.waiters].map(e => e.key))
310 left = [...st.holders, ...st.waiters].map(e => e.key).filter(k => !stay.has(k))
311 return state
312 })
313 for (const n of notes) $.ui.toast(n)
314 await signalSlots($, granted, left)
315}
316
317async function sh($: EngineInterface, script: string, ...args: string[]) {
318 try {
319 return await $.process.run(['sh', '-c', script, 'sh', ...args], { timeoutMs: 5_000 })
320 } catch {
321 return undefined
322 }
323}
324
325async function signalSlots($: EngineInterface, granted: SlotEntry[], left: string[], kind: 'test' | 'typecheck' = 'test'): Promise<void> {
326 const dir = kind === 'test' ? slotDir : typecheckDir(slotDir)
327 for (const key of left) {
328 const f = grantFile(dir, key)
329 if (f) await sh($, 'rm -f "$1"', f)
330 }
331 for (const g of granted) {
332 const f = grantFile(dir, g.key)
333 if (f) await sh($, 'mkdir -p "$(dirname "$1")" && : > "$1"', f)
334 if (g.key !== 'main') {
335 const text = kind === 'test' ? `flow: your test slot is granted (${g.label}). Call mcp__flow__test_slot acquire to confirm, run, then release.` : `flow: your typecheck slot is granted (${g.label}). Call mcp__flow__test_slot kind "typecheck" action "acquire" to confirm, run, then release.`
336 try {
337 await deliver($, g.key, text, { onGone: () => undefined })
338 } catch {
339 // The grant file is the signal; a lost message is only a missed nudge.
340 }
341 }
342 }
343}
344
345// settleSlots for the typecheck pool: the same steps, its own state, limit and lease.
346async function settleTypecheck($: EngineInterface, rows: AgentRow[], t: number, pre: (s: TestSlots) => TestSlots = s => s, me?: string): Promise<void> {
347 const notes: string[] = []
348 let granted: SlotEntry[] = []
349 let left: string[] = []
350 await update($, typecheckSlots, st => {
351 notes.length = 0
352 const r = reapTypecheck(pre(st), rows, t)
353 const g = grantTypecheck(r.state, heldSettings?.typecheckSlots ?? 1, t)
354 notes.push(...r.notes, ...g.notes)
355 const state = me === undefined ? g.state
356 : { ...g.state, holders: g.state.holders.map(holder => holder.key === me ? { ...holder, claimed: true } : holder) }
357 granted = g.granted.filter(holder => holder.key !== me)
358 const stay = new Set([...state.holders, ...state.waiters].map(e => e.key))
359 left = [...st.holders, ...st.waiters].map(e => e.key).filter(k => !stay.has(k))
360 return state
361 })
362 for (const n of notes) $.ui.toast(n)
363 await signalSlots($, granted, left, 'typecheck')
364}
365
366// A command in `cwd` when one is given; an `if`, so each $ call stays a whole return value.
367function execIn($: EngineInterface, argv: string[], cwd: string | undefined) {
368 if (cwd === undefined) return $.process.run(argv)
369 return $.process.run(argv, { cwd })
370}
371
372async function writeText($: EngineInterface, path: string, text: string): Promise<void> {
373 await $.fs.write(path, text)
374}
375
376// The $ calls whose failure has a fallback, each in a try/catch rather than a chained .then/.catch: the plugin
377// directory reads a $ call that is not a whole statement or value as not plain (MOD_CAPABILITY_USE_NOT_PLAIN).
378// $.env.get takes a literal name (the engine lists the variables a module reads), hence the switch.
379async function envOf($: EngineInterface, key: 'FLOW_ROLE' | 'FLOW_NAME' | 'FLOW_RELAY' | 'CLAUDE_CODE_EFFORT_LEVEL'): Promise<string | undefined> {
380 try {
381 switch (key) {
382 case 'FLOW_ROLE': return await $.env.get('FLOW_ROLE')
383 case 'FLOW_NAME': return await $.env.get('FLOW_NAME')
384 case 'FLOW_RELAY': return await $.env.get('FLOW_RELAY')
385 case 'CLAUDE_CODE_EFFORT_LEVEL': return await $.env.get('CLAUDE_CODE_EFFORT_LEVEL')
386 }
387 } catch {
388 return undefined
389 }
390}
391
392async function usageOf($: EngineInterface) {
393 try {
394 return await $.session.usage()
395 } catch {
396 return undefined
397 }
398}
399
400async function existsQuietly($: EngineInterface, path: string): Promise<boolean> {
401 try {
402 const found = await $.fs.exists(path)
403 return Boolean(found)
404 } catch {
405 return false
406 }
407}
408
409async function readQuietly($: EngineInterface, path: string): Promise<string | undefined> {
410 try {
411 const text = await $.fs.read(path)
412 return String(text)
413 } catch {
414 return undefined
415 }
416}
417
418// The last batch the release tool cut, so a retried push does not release twice. Held by property: releaseIoOf's
419// setLast writes it there and assigns no outer variable (plain-names check 10).
420const releaseMemo: { last: { key: string; version: string } | undefined } = { last: undefined }
421
422function releaseIoOf($: EngineInterface): ReleaseIo {
423 return {
424 exec: (argv, cwd) => execIn($, argv, cwd),
425 sleep: ms => $.clock.sleep(ms),
426 now: () => $.clock.now(),
427 fileExists: path => $.fs.exists(path),
428 readFile: path => $.fs.read(path),
429 writeFile: (path, text) => writeText($, path, text),
430 stateDir: () => stateDir($),
431 readJson: path => readJson($, path),
432 writeJsonAtomic: (path, obj) => writeJsonAtomic($, path, obj),
433 getLast: () => releaseMemo.last,
434 setLast: last => { releaseMemo.last = last },
435 handovers: () => read($, handovers),
436 batch: async () => (await read($, pushState)).batch,
437 }
438}
439
440function handoverIoOf($: EngineInterface, options: Record<string, unknown>): HandoverIo {
441 return {
442 run: argv => $.process.run(argv),
443 now: () => $.clock.now(),
444 handovers: () => read($, handovers),
445 putHandover: async (pr, ho) => { await update($, handovers, hs => ({ ...hs, [pr]: ho })) },
446 resolveReportTo: (given, callerId) => resolveReportTo($, given, callerId),
447 openEnv: (ho, drafts, prev, at) => openHandoverEnv($, options, ho, drafts, prev, at),
448 best: (what, fn) => best($, what, fn),
449 saveHandover: ho => saveHandover($, ho),
450 appendLog: event => appendLog($, event),
451 toast: text => { $.ui.toast(text) },
452 refresh: () => refresh($),
453 arms: async () => { await loadLedger($); return { ledger: await read($, ledger), log: await readLog($) } },
454 ensureQueue: why => ensureQueue($, why),
455 liteManager: agentId => liteManagerOf($, agentId),
456 }
457}
458
459function planIoOf($: EngineInterface): PlanIo {
460 return {
461 refresh: () => refresh($),
462 plans: () => read($, plan),
463 planOwner: (plans, name) => planOwner(plans, name),
464 limitsLine: (rows, workers) => limitsLine(rows, workers),
465 syncPlans: (rows, edit, quietOwner) => syncPlans($, rows, edit, quietOwner),
466 }
467}
468
469function inboxIoOf($: EngineInterface): InboxIo {
470 return {
471 standing: standingIoOf($),
472 refresh: () => refresh($),
473 deliver: (id, text, opts) => deliver($, id, text, opts),
474 toast: text => { $.ui.toast(text) },
475 ownerNameOf: id => ownerNameOf($, id),
476 answerQuestion: (wanted, choice, by, options, user) => answerQuestion($, wanted, choice, by, options, user),
477 withPreflight: fn => withPreflight($, fn),
478 preflightTick: rows => preflightTick($, rows),
479 submitLater: text => { toMain($, text) },
480 paneOpen: () => flowPaneOpen($),
481 net: decideIoOf($),
482 }
483}
484
485function checksIoOf($: EngineInterface): ChecksIo {
486 return {
487 agents: () => agentsOf($),
488 checks: () => read($, checks),
489 now: () => $.clock.now(),
490 withChecks: fn => withChecks($, fn),
491 }
492}
493
494function slotsIoOf($: EngineInterface): SlotsIo {
495 return {
496 refresh: () => refresh($),
497 now: () => $.clock.now(),
498 sleep: ms => $.clock.sleep(ms),
499 slots: () => read($, testSlots),
500 settleSlots: (rows, t, pre, me) => settleSlots($, rows, t, pre, me),
501 best: (what, fn) => best($, what, fn),
502 testFails: () => read($, testFails),
503 setTestFails: async state => { await update($, testFails, () => state) },
504 appendLog: event => appendLog($, event),
505 slotDir: () => slotDir,
506 typecheckSlots: () => read($, typecheckSlots),
507 settleTypecheck: (rows, t, pre, me) => settleTypecheck($, rows, t, pre, me),
508 sessions: () => read($, sessions),
509 agents: () => $.agent.list(),
510 exec: argv => $.process.run(argv),
511 cwd: () => $.session.cwd(),
512 }
513}
514
515function armsIoOf($: EngineInterface): ArmsIo {
516 return {
517 run: argv => $.process.run(argv),
518 ledger: async () => { await loadLedger($); return read($, ledger) },
519 log: () => readLog($),
520 appendLog: event => appendLog($, event),
521 callerName: async id => id === undefined ? undefined : (await agentsOf($)).find(a => a.id === id)?.name,
522 liveNames: async () => (await agentsOf($)).filter(a => !ENDED.has(a.status) && a.name !== undefined).map(a => a.name!),
523 }
524}
525
526function migrationsIoOf($: EngineInterface): MigrationsIo {
527 return {
528 runCmd: argv => runCmd($, argv),
529 }
530}
531
532function statusIoOf($: EngineInterface, options: Record<string, unknown>, base: string): StatusIo {
533 return {
534 reconcile: () => reconcileStale(staleIoOf($, base)),
535 now: () => $.clock.now(),
536 handovers: () => read($, handovers),
537 readLog: () => readLog($),
538 prCache: () => read($, prCache),
539 fetchPrs: () => fetchPrs($),
540 refresh: () => refresh($),
541 activity: () => read($, activity),
542 unhanded: () => currentUnhanded($),
543 leftovers: () => read($, leftovers),
544 costLines: (prs, keep) => costLines($, prs, keep),
545 ledger: () => read($, ledger),
546 preflight: () => read($, preflight),
547 inbox: () => read($, inbox),
548 plans: () => read($, plan),
549 slots: () => read($, testSlots),
550 typecheckSlots: () => read($, typecheckSlots),
551 offerSeeds: () => offerSeedsOnce(standingIoOf($), options),
552 offerSuggestions: () => offerSuggestionsOnce(standingIoOf($), options),
553 pushState: () => read($, pushState),
554 breaker: () => read($, reviewerBreaker),
555 deploys: () => read($, deploys),
556 behind: () => read($, behind),
557 limitsLine: (rows, workers) => limitsLine(rows, workers),
558 stateDir: () => stateDir($),
559 }
560}
561
562function commandIoOf($: EngineInterface): CommandIo {
563 return {
564 now: () => $.clock.now(),
565 inbox: () => read($, inbox),
566 checks: () => read($, checks),
567 answerQuestion: (wanted, choice, by, options, user) => answerQuestion($, wanted, choice, by, options, user),
568 offerSuggestions: options => offerSuggestionsOnce(standingIoOf($), options),
569 withChecks: fn => withChecks($, fn),
570 costLines: prs => costLines($, prs),
571 handovers: () => read($, handovers),
572 preflight: () => read($, preflight),
573 roster: () => read($, roster),
574 endedManagers: (state, rows, hs) => doneManagers(state, rows, hs),
575 endedOwners: () => endedOwnersOf($),
576 panes: () => panesOf($),
577 close: () => $.ui.close({ id: PANE }),
578 home: () => paneHome($),
579 open: () => $.ui.open({ id: PANE, title: 'Flow', focus: true, closeOnEscape: true }),
580 gatherLeftovers: (base, resumed) => gatherLeftovers($, base, resumed),
581 pushState: () => read($, pushState),
582 after: (ms, fn) => { $.clock.after(ms, fn) },
583 submit: text => $.prompt.submit({ text }),
584 notesPath: owner => notesPath($, owner),
585 readNotes: owner => readNotes($, owner),
586 sweep: (base, apply, dryHint) => sweep($, base, apply, dryHint),
587 putHandover: async (pr, ho) => { await update($, handovers, hs => ({ ...hs, [pr]: ho })) },
588 best: (what, fn) => best($, what, fn),
589 saveHandover: ho => saveHandover($, ho),
590 appendLog: event => appendLog($, event),
591 toast: text => { $.ui.toast(text) },
592 ensureQueue: why => ensureQueue($, why),
593 releaseReviewerHalt: () => releaseHaltTo(breakerIoOf($), 'user'),
594 refresh: () => refresh($),
595 pushAct: (act, by) => pushAct($, act, by),
596 holdTarget: (name, until, by, reason) => holdTarget($, name, until, by, reason),
597 releaseTarget: name => releaseTarget($, name),
598 refreshBehind: () => refreshBehind($),
599 closeReturnedEnv: ho => closeReturnedEnv($, ho),
600 settleBatch: () => settleBatch($),
601 tellManager: (name, text) => tellManager($, name, text),
602 initDetect: options => initDetect(initIoOf($), options),
603 initMark: d => writeMarker(initIoOf($), d),
604 demoStart: () => demoStart(demoIoOf($)),
605 demoStop: () => demoStop(demoIoOf($)),
606 }
607}
608
609function limitsLine(rows: AgentRow[], workers: number): string {
610 return `Limits: managers ${liveManagers(rows).length}/${mirror.maxManagers}, workers per manager ${workers}`
611}
612
613// --- /flow init: the io detection works through, and the demo replay (demo-replay.ts) ---
614
615function initIoOf($: EngineInterface): InitIo {
616 return {
617 readFile: path => readText($, path),
618 exists: path => existsQuietly($, path),
619 writeFile: async (path, text) => {
620 try {
621 const tmp = `${path}.${Date.now()}.tmp`
622 await $.fs.write(tmp, text)
623 const r = await $.process.run(['mv', tmp, path])
624 return r.exitCode === 0
625 } catch {
626 return false
627 }
628 },
629 mkdirp: dir => $.process.run(['mkdir', '-p', dir]),
630 run: argv => runCmd($, argv, 15_000),
631 }
632}
633
634// The replay's state is this atom alone: no agent, handover or inbox row of the real flow is touched, and a
635// restart loses it. Each start gets a new generation, so a timer of an earlier run does nothing.
636const demo = atom({ plugin: 'flow', key: 'demo' } as const, null as DemoState | null)
637
638// The io the demo functions (demo-run.ts) work through; the entry points below stay `$`-taking wrappers.
639function demoIoOf($: EngineInterface): DemoIo {
640 return {
641 get: () => read($, demo),
642 set: async fn => { await update($, demo, fn) },
643 clearInbox: async () => {
644 await update($, inboxDraft, () => '')
645 await update($, inboxNote, () => '')
646 },
647 serial: paneSerial,
648 now: () => $.clock.now(),
649 toast: text => { $.ui.toast(text) },
650 after: (ms, fn) => { $.clock.after(ms, fn) },
651 openPane: () => $.ui.open({ id: PANE, title: 'Flow', focus: true, closeOnEscape: true }),
652 listAgents: () => $.agent.list(),
653 run: argv => runCmd($, argv),
654 }
655}
656
657// The view the pane was last drawn under: a focus event carries none, and a focus move is the
658// person acting in that view.
659let paneView: string | null = null
660
661// The pane's io sets paneView through this, not a closure assigning it (plain-names check 10).
662function setPaneView(v: string | null): void {
663 paneView = v
664}
665
666// Home: the tree with nothing selected and every card, view and demo closed. The followed transcript is
667// adopted as the ui.focus handler does, so the pane does not jump back to it. inboxDraft stays: an
668// unsent draft survives.
669async function paneHome($: EngineInterface): Promise<void> {
670 await update($, overrideView, () => paneView)
671 await update($, selected, () => null)
672 await update($, graphFocus, () => null)
673 await update($, viewMode, () => 'tree')
674 await update($, inboxNote, () => '')
675 await update($, inboxOpen, () => ({}))
676 await update($, batchPick, () => null)
677 await update($, prShown, () => null)
678 await update($, cardScroll, () => NO_SCROLL)
679 if (await read($, demo) !== null) await demoStop(demoIoOf($))
680}
681
682function rosterIoOf($: EngineInterface): RosterIo {
683 return {
684 list: () => $.agent.list(),
685 now: () => $.clock.now(),
686 plan: () => read($, plan),
687 updatePlan: async fn => { await update($, plan, fn) },
688 activity: () => read($, activity),
689 updateActivity: async fn => { await update($, activity, fn) },
690 handovers: () => read($, handovers),
691 seen: () => read($, seenAgents),
692 setSeen: async known => { await update($, seenAgents, () => known) },
693 log: () => readLog($),
694 inbox: () => read($, inbox),
695 roster: () => read($, roster),
696 setRoster: async rows => { await update($, roster, () => rows) },
697 setNow: async t => { await update($, now, () => t) },
698 sessions: () => read($, sessions),
699 testSlots: () => read($, testSlots),
700 typecheckSlots: () => read($, typecheckSlots),
701 toast: text => { $.ui.toast(text) },
702 status: line => $.ui.status(line),
703 wakeMain: text => { toMain($, text) },
704 autoSweep: () => autoSweep($),
705 occasionalSweep: () => { void occasionalSweep($) },
706 settleSlots: (rows, t) => settleSlots($, rows, t),
707 unhanded: async () => (await currentUnhanded($)).length,
708 preflightTick: rows => preflightTick($, rows),
709 deliver: (id, text, opts) => deliver($, id, text, opts),
710 tellMain: (name, text) => tellMain($, name, text),
711 markResumable: id => { resumable.add(id) },
712 decisionPhrases: () => mirror.decisionPhrases,
713 maxManagers: () => mirror.maxManagers,
714 slotLimit: () => mirror.slotLimit,
715 typecheckLimit: () => heldSettings?.typecheckSlots ?? 1,
716 }
717}
718
719// Settles every plan against the roster and handovers in one update, then tells each owner once (roster-run.ts).
720function syncPlans($: EngineInterface, rows: AgentRow[], edit?: (p: Plan) => Plan, quietOwner?: string): Promise<Plan> {
721 return syncPlansTo(rosterIoOf($), rows, edit, quietOwner)
722}
723
724// The roster as the board shows it: every agent of the session, with its role (roster-run.ts).
725function refresh($: EngineInterface): Promise<AgentRow[]> { return refreshTo(rosterIoOf($)) }
726
727async function openPane($: EngineInterface): Promise<void> {
728 const r = await $.ui.open({ id: PANE, title: 'Flow', closeOnEscape: true })
729 if (!r.isPlaced) $.ui.toast('flow is running agents: type /flow to watch them')
730}
731
732// flow's state on disk: <git-common-dir>/flow/. Shared by every worktree of the repo, never part
733// of a working tree. Every helper is best-effort: outside a repo, or when a write fails, it
734// does nothing (a failure goes to $.ui.log) and never throws, so a tool call or turn never fails
735// over state. `config.json` in this dir belongs to the settings package: never touched here.
736
737
738let cached: string | undefined
739
740// Forget the resolved dir; a new session resolves it again.
741function resetStateDir(): void {
742 cached = undefined
743}
744
745async function warn($: EngineInterface, what: string, err: unknown): Promise<void> {
746 try {
747 await $.ui.log(`flow state: ${what}: ${err instanceof Error ? err.message : String(err)}`)
748 } catch {
749 // No log to write to.
750 }
751}
752
753// The state dir, or undefined when this is not a repo (or the answer is no absolute path).
754async function stateDir($: EngineInterface): Promise<string | undefined> {
755 if (cached !== undefined) return cached
756 try {
757 const r = await $.process.run(['git', 'rev-parse', '--path-format=absolute', '--git-common-dir'])
758 const out = r.stdout.trim()
759 if (r.exitCode !== 0 || !out.startsWith('/') || out.includes('\n')) return undefined
760 cached = `${out.replace(/\/+$/, '')}/flow`
761 return cached
762 } catch {
763 return undefined
764 }
765}
766
767// Write a temp file next to the target, then rename it over: a reader sees the old file or the new one.
768async function writeJsonAtomic($: EngineInterface, path: string, obj: unknown): Promise<boolean> {
769 try {
770 const tmp = `${path}.${Date.now()}.tmp`
771 await $.fs.write(tmp, `${JSON.stringify(obj, null, 2)}\n`)
772 const r = await $.process.run(['mv', tmp, path])
773 if (r.exitCode !== 0) throw new Error(r.stderr.trim() || 'mv failed')
774 return true
775 } catch (err) {
776 await warn($, `writing ${path}`, err)
777 return false
778 }
779}
780
781// The parsed file, or undefined when it is missing, unreadable or not JSON.
782async function readJson($: EngineInterface, path: string): Promise<unknown> {
783 try {
784 const text = await $.fs.read(path)
785 return JSON.parse(text)
786 } catch {
787 return undefined
788 }
789}
790
791// --- Cost ledger ---
792function costIoOf($: EngineInterface): CostIo {
793 return {
794 stateDir: () => stateDir($),
795 readJson: path => readJson($, path),
796 writeJsonAtomic: (path, obj) => writeJsonAtomic($, path, obj),
797 mkdirp: async dir => { await $.process.run(['mkdir', '-p', dir]) },
798 now: () => $.clock.now(),
799 after: (ms, fn) => { $.clock.after(ms, fn) },
800 ledger: () => read($, ledger),
801 updateLedger: async fn => { await update($, ledger, fn) },
802 loaded: () => read($, ledgerLoaded),
803 markLoaded: async () => { await update($, ledgerLoaded, () => true) },
804 delta: () => read($, ledgerDelta),
805 updateDelta: async fn => { await update($, ledgerDelta, fn) },
806 epoch: () => read($, ledgerEpoch),
807 setEpoch: async e => { await update($, ledgerEpoch, () => e) },
808 startedAt: async () => {
809 const usage = await usageOf($)
810 if (usage === undefined) return undefined
811 return usage.startedAt
812 },
813 liveIds: async () => (await read($, roster)).map(a => a.id),
814 hasSessions: async () => Object.keys(await read($, sessions)).length > 0,
815 }
816}
817function loadLedger($: EngineInterface): Promise<void> { return loadLedgerTo(costIoOf($)) }
818function changeLedger($: EngineInterface, fn: (l: Ledger, now: number) => Ledger): Promise<void> { return changeLedgerTo(costIoOf($), fn) }
819function mainKey($: EngineInterface): Promise<string> { return mainKeyTo(costIoOf($)) }
820function costLines($: EngineInterface, prs: { pr: number; branch: string }[], keep?: (e: Ledger[string]) => boolean): Promise<string[]> {
821 return costLinesTo(costIoOf($), prs, keep)
822}
823
824// Inbox changes run one after another: two answers at once must not each start from the same file.
825let inboxChain: Promise<unknown> = Promise.resolve()
826
827// Read the inbox from disk, let fn change it, write it back and set the atom. fn returns the new inbox (the
828// same object when nothing changed) and whatever the caller wants back.
829function withInbox<T>($: EngineInterface, fn: (cur: Inbox) => { inbox: Inbox; out: T }): Promise<T> {
830 const run = async (): Promise<T> => {
831 const dir = await stateDir($)
832 const cur = dir === undefined ? await read($, inbox) : normalizeInbox(await readJson($, `${dir}/inbox.json`))
833 const { inbox: changed, out } = fn(cur)
834 if (changed !== cur) {
835 if (dir !== undefined) {
836 await $.process.run(['mkdir', '-p', dir])
837 await writeJsonAtomic($, `${dir}/inbox.json`, changed)
838 }
839 await update($, inbox, () => changed)
840 }
841 return out
842 }
843 const result = inboxChain.then(run, run)
844 inboxChain = result.catch(() => undefined)
845 return result
846}
847
848// Pre-flight changes run one after another, like the inbox's.
849let preflightChain: Promise<unknown> = Promise.resolve()
850
851function withPreflight<T>($: EngineInterface, fn: (cur: Preflight) => { state: Preflight; out: T }): Promise<T> {
852 const run = async (): Promise<T> => {
853 const dir = await stateDir($)
854 const cur = dir === undefined ? await read($, preflight) : normalizePreflight(await readJson($, `${dir}/preflight.json`))
855 const { state, out } = fn(cur)
856 if (state !== cur) {
857 if (dir !== undefined) {
858 await $.process.run(['mkdir', '-p', dir])
859 await writeJsonAtomic($, `${dir}/preflight.json`, state)
860 }
861 await update($, preflight, () => state)
862 }
863 return out
864 }
865 const result = preflightChain.then(run, run)
866 preflightChain = result.catch(() => undefined)
867 return result
868}
869
870// Check changes run one after another, like the inbox's.
871let checksChain: Promise<unknown> = Promise.resolve()
872
873function withChecks<T>($: EngineInterface, fn: (cur: Checks) => { checks: Checks; out: T }): Promise<T> {
874 const run = async (): Promise<T> => {
875 const dir = await stateDir($)
876 const cur = dir === undefined ? await read($, checks) : normalizeChecks(await readJson($, `${dir}/checks.json`))
877 const { checks: changed, out } = fn(cur)
878 if (changed !== cur) {
879 if (dir !== undefined) {
880 await $.process.run(['mkdir', '-p', dir])
881 await writeJsonAtomic($, `${dir}/checks.json`, changed)
882 }
883 await update($, checks, () => changed)
884 }
885 return out
886 }
887 const result = checksChain.then(run, run)
888 checksChain = result.catch(() => undefined)
889 return result
890}
891
892// The version the running plugin was installed as: its plugin.json next to the module. Undefined when unreadable.
893async function installedVersion($: EngineInterface): Promise<string | undefined> {
894 try {
895 const text = await $.fs.read(`${$.plugin.root}/.claude-plugin/plugin.json`)
896 const v = (JSON.parse(text) as { version?: unknown }).version
897 return typeof v === 'string' && /^\d+\.\d+\.\d+/.test(v) ? v : undefined
898 } catch {
899 return undefined
900 }
901}
902
903// The version a PR's merge needs installed: plugin.json at the merged sha, else one named in the steps.
904async function versionAt($: EngineInterface, sha: string | undefined, steps: string): Promise<string | undefined> {
905 if (sha) {
906 try {
907 const r = await $.process.run(['git', 'show', `${sha}:.claude-plugin/plugin.json`])
908 const v = r.exitCode === 0 ? (JSON.parse(r.stdout) as { version?: unknown }).version : undefined
909 if (typeof v === 'string' && v !== '') return v
910 } catch { /* not a plugin repo, or the sha is unknown */ }
911 }
912 return versionInSteps(steps)
913}
914
915// Adds a check for each needs-a-person line in a done PR's report (the same PR and steps never twice). Live: the
916// handover's verify_command rides along, unless verify_paths says no changed file warrants it. Returns the new ones.
917async function captureChecks($: EngineInterface, ho: Handover, verifyPaths: string[], live: boolean): Promise<Check[]> {
918 const needs = parseNeeds(ho.report)
919 if (needs.length === 0) return []
920 let command = live && ho.verifyCommand ? ho.verifyCommand : undefined
921 let note: string | undefined
922 if (command !== undefined && verifyPaths.length > 0) {
923 // gh failing runs the command anyway: fail toward verifying.
924 const r = await $.process.run(['gh', 'pr', 'view', String(ho.pr), '--json', 'files'])
925 let files: string[] | undefined
926 try { files = r.exitCode === 0 ? (JSON.parse(r.stdout) as { files: { path: string }[] }).files.map(f => f.path) : undefined } catch { files = undefined }
927 if (files !== undefined && !anyMatch(verifyPaths, files)) { command = undefined; note = SKIP_NOTE }
928 }
929 // Read unconditionally (a plain statement); only a live run stamps with it.
930 const clockT = await $.clock.now()
931 const t = live ? clockT : ho.at
932 const items = await Promise.all(needs.map(async n => ({
933 steps: n.steps, version: await versionAt($, ho.sha, n.steps),
934 ...(n.pr === ho.pr && command !== undefined ? { verifyCommand: command } : {}), ...(n.pr === ho.pr && note !== undefined ? { note } : {}),
935 })))
936 return withChecks($, cur => {
937 const r = addChecks(cur, ho.pr, ho.title, ho.sha, items, t)
938 return { checks: r.checks, out: r.added }
939 })
940}
941
942// Sends the round to main once it is due: everyone filed, skipped or done (preflight.ts doneManagers), or
943// the wait is over. The delivered flag is written inside the update, so two callers deliver it once; a
944// round telling main nothing new is closed unsent (deliverRound).
945async function preflightTick($: EngineInterface, rows: AgentRow[]): Promise<void> {
946 if (!(await read($, preflight)).rounds.some(r => !r.delivered)) return
947 const t = await $.clock.now()
948 const hs = await read($, handovers)
949 const items = await read($, inbox)
950 const due = await withPreflight($, cur => {
951 const done = doneManagers(cur, rows, Object.values(hs))
952 const d = deliverRound(cur, items, done, t, mirror.preflightWaitMs)
953 return { state: d.state, out: d.send === undefined ? undefined : { ...d.send, done } }
954 })
955 if (due === undefined) return
956 const text = renderRound(due.state, items, due.round, due.done, t, due.timedOut, mirror.askCards)
957 toMain($, text)
958}
959
960// Why this manager may not start workers yet, or undefined. Only a recorded manager is ever gated.
961async function preflightGate($: EngineInterface, agentId: string | undefined): Promise<string | undefined> {
962 if (!mirror.preflightOn || agentId === undefined) return undefined
963 const me = (await agentsOf($)).find(a => a.id === agentId)
964 if (me?.type !== MANAGER || me.name === undefined) return undefined
965 const g = gateOf(await read($, preflight), await read($, inbox), me.name)
966 return g === undefined ? undefined : denyText(g)
967}
968
969// Lite records change one after another, like pre-flight's. A lite manager must survive a plugin restart.
970let liteChain: Promise<unknown> = Promise.resolve()
971
972function withLite<T>($: EngineInterface, fn: (cur: LiteState) => { state: LiteState; out: T }): Promise<T> {
973 const run = async (): Promise<T> => {
974 const dir = await stateDir($)
975 const cur = dir === undefined ? await read($, lite) : normalizeLite(await readJson($, `${dir}/lite.json`))
976 const { state, out } = fn(cur)
977 if (state !== cur) {
978 if (dir !== undefined) {
979 await $.process.run(['mkdir', '-p', dir])
980 await writeJsonAtomic($, `${dir}/lite.json`, state)
981 }
982 await update($, lite, () => state)
983 }
984 return out
985 }
986 const result = liteChain.then(run, run)
987 liteChain = result.catch(() => undefined)
988 return result
989}
990
991// The lite manager an agent is (by its roster name), else undefined.
992async function liteManagerOf($: EngineInterface, agentId: string | undefined): Promise<string | undefined> {
993 if (agentId === undefined) return undefined
994 const me = (await agentsOf($)).find(a => a.id === agentId)
995 return me?.type === MANAGER && me.name !== undefined && isLiteName(await read($, lite), me.name) ? me.name : undefined
996}
997
998// Who is calling a reviewer-side tool: main, the reviewer, a lite manager or anyone else.
999async function toolCallerOf($: EngineInterface, agentId: string | undefined): Promise<ToolCaller> {
1000 if (agentId === undefined) return { kind: 'main' }
1001 const me = (await agentsOf($)).find(a => a.id === agentId)
1002 // A worker session is not on that roster; it is a worker, never the reviewer an unlisted id is taken for.
1003 if (me === undefined) {
1004 const named = await sessionOfId($, agentId)
1005 if (named !== undefined && named.role === undefined) return { kind: 'other' }
1006 }
1007 // Only a manager or a worker is refused. An id the roster no longer lists (the host drops agents) is a reviewer's, as before.
1008 if (me === undefined || isReviewer(me.type)) return { kind: 'reviewer' }
1009 const name = await liteManagerOf($, agentId)
1010 if (name !== undefined) return { kind: 'lite', name }
1011 return me.type === MANAGER || WORKERS.has(me.type) ? { kind: 'other' } : { kind: 'reviewer' }
1012}
1013
1014async function today($: EngineInterface) {
1015 const t = await $.clock.now()
1016 return new Date(t).toISOString().slice(0, 10)
1017}
1018
1019function messagingIoOf($: EngineInterface): MessagingIo {
1020 return {
1021 inbox: () => read($, inbox),
1022 withInbox: fn => withInbox($, fn),
1023 now: () => $.clock.now(),
1024 today: () => today($),
1025 agents: () => agentsOf($),
1026 seen: () => read($, seenAgents),
1027 deliver: (id, text, opts) => deliver($, id, text, opts),
1028 appendNote: (name, line) => appendNote($, name, line),
1029 best: (what, fn) => best($, what, fn),
1030 toMain: text => toMain($, text),
1031 markResumable: id => { resumable.add(id) },
1032 managerFinished: (ids, name, rows) => managerFinished($, ids, name, rows),
1033 addGuardTest: (options, glob, test) => addGuardTest(standingIoOf($), options, glob, test),
1034 onDeployAnswer: (q, answer) => onDeployAnswer($, q, answer),
1035 onEnvAnswer: (q, answer) => onEnvAnswer($, q, answer),
1036 envSettled: q => envSettled($, q),
1037 onPushAnswer: (q, answer, by) => onPushAnswer($, q, answer, by),
1038 onReviewerAnswer: (answer, by) => onReviewerAnswer($, answer, by),
1039 loadLedger: () => loadLedger($),
1040 ledger: () => read($, ledger),
1041 }
1042}
1043
1044// The one way a question gets answered (messaging-run.ts): marks it, tells the asker, notes the decision.
1045function answerQuestion($: EngineInterface, wanted: string, choice: string | null, by: string, options: Record<string, unknown>, user = false): Promise<string> {
1046 return answerQuestionTo(messagingIoOf($), wanted, choice, by, options, user)
1047}
1048async function paneInboxRows($: EngineInterface): Promise<{ rows: PaneRow[]; now: number }> { return paneInboxRowsTo(messagingIoOf($), await read($, inboxFolds)) }
1049async function endedOwnersOf($: EngineInterface): Promise<Set<string>> { return endedOwners(await read($, roster), await read($, seenAgents)) }
1050
1051// Pane presses run one after another, so a second press sees the first one's answer and highlight.
1052let paneChain: Promise<unknown> = Promise.resolve()
1053const paneSerial = <T,>(fn: () => Promise<T>): Promise<T> => {
1054 const run = paneChain.then(fn, fn)
1055 paneChain = run.catch(() => undefined)
1056 return run
1057}
1058
1059// ---- the deploy gate (deploy.ts, deploy-run.ts) ----
1060
1061function deployIoOf($: EngineInterface): DeployIo {
1062 return {
1063 stateDir: () => stateDir($),
1064 readJson: path => readJson($, path),
1065 writeJson: (path, obj) => writeJsonAtomic($, path, obj),
1066 mkdir: dir => $.process.run(['mkdir', '-p', dir]),
1067 deploys: () => read($, deploys),
1068 setDeploys: async changed => { await update($, deploys, () => changed) },
1069 behind: () => read($, behind),
1070 setBehind: async changed => { await update($, behind, () => changed) },
1071 infos: () => mirror.deployInfos,
1072 base: () => mirror.cleanupBase,
1073 exec: (argv, timeoutMs) => $.process.run(argv, { timeoutMs }),
1074 now: () => $.clock.now(),
1075 handovers: () => read($, handovers),
1076 updateHandovers: async fn => { await update($, handovers, fn) },
1077 saveHandover: ho => saveHandover($, ho),
1078 inbox: () => read($, inbox),
1079 withInbox: fn => withInbox($, fn),
1080 ensureQueue: why => ensureQueue($, why),
1081 loadRules: options => loadRules(standingIoOf($), options),
1082 appendNote: (name, line) => appendNote($, name, line),
1083 appendLog: event => appendLog($, event),
1084 today: () => today($),
1085 noteText,
1086 best: (what, fn) => best($, what, fn),
1087 toast: text => { $.ui.toast(text) },
1088 toMain: text => toMain($, text),
1089 paneOpen: () => flowPaneOpen($),
1090 }
1091}
1092
1093function refreshBehind($: EngineInterface): Promise<void> { return refreshBehindTo(deployIoOf($)) }
1094function onDeployAnswer($: EngineInterface, q: Question, answer: string): Promise<string> { return onDeployAnswerTo(deployIoOf($), q, answer) }
1095function onEnvAnswer($: EngineInterface, q: Question, answer: string): Promise<string> { return onEnvAnswerTo(deployIoOf($), q, answer) }
1096function envSettled($: EngineInterface, q: Question): Promise<string | undefined> { return envSettledTo(deployIoOf($), q) }
1097function holdTarget($: EngineInterface, name: string, until: Hold['until'], by: string, reason: string | undefined): Promise<string> {
1098 return holdTargetTo(deployIoOf($), name, until, by, reason)
1099}
1100function releaseTarget($: EngineInterface, name: string): Promise<string> { return releaseTargetTo(deployIoOf($), name) }
1101function deployTool($: EngineInterface, options: Record<string, unknown>, input: Record<string, unknown>, isMain: boolean, caller: string): Promise<string> {
1102 return deployToolTo(deployIoOf($), options, input, isMain, caller)
1103}
1104function openHandoverEnv(
1105 $: EngineInterface, options: Record<string, unknown>, ho: Handover, drafts: Draft[], prev: EnvChange[], at: number,
1106): Promise<string> { return openHandoverEnvTo(deployIoOf($), options, ho, drafts, prev, at) }
1107function closeReturnedEnv($: EngineInterface, ho: Handover): Promise<void> { return closeReturnedEnvTo(deployIoOf($), ho) }
1108
1109
1110// ---- the push gate (pushgate.ts) ----
1111
1112function tellManager($: EngineInterface, name: string, text: string): Promise<void> { return tellManagerTo(messagingIoOf($), name, text) }
1113function tellMain($: EngineInterface, name: string, text: string): Promise<void> { return tellMainTo(messagingIoOf($), name, text) }
1114function sizeBackNote($: EngineInterface, branch: string): Promise<string | undefined> { return sizeBackNoteTo(messagingIoOf($), branch) }
1115
1116function pushIoOf($: EngineInterface): PushIo {
1117 return {
1118 stateDir: () => stateDir($),
1119 readJson: path => readJson($, path),
1120 writeJson: (path, obj) => writeJsonAtomic($, path, obj),
1121 mkdir: dir => $.process.run(['mkdir', '-p', dir]),
1122 push: () => read($, pushState),
1123 setPush: async changed => { await update($, pushState, () => changed) },
1124 exec: (argv, timeoutMs) => $.process.run(argv, { timeoutMs }),
1125 now: () => $.clock.now(),
1126 handovers: () => read($, handovers),
1127 updateHandovers: async fn => { await update($, handovers, fn) },
1128 saveHandover: ho => saveHandover($, ho),
1129 appendLog: event => appendLog($, event),
1130 best: (what, fn) => best($, what, fn),
1131 withInbox: fn => withInbox($, fn),
1132 ensureQueue: () => ensureQueue($),
1133 closeReturnedEnv: ho => closeReturnedEnv($, ho),
1134 sizeBackNote: branch => sizeBackNote($, branch),
1135 tellManager: (name, text) => tellManager($, name, text),
1136 dropRelease: async key => {
1137 if (releaseMemo.last?.key === key) {
1138 releaseMemo.last = undefined
1139 const dir = await stateDir($)
1140 if (dir !== undefined) await writeJsonAtomic($, `${dir}/release.json`, {})
1141 }
1142 },
1143 toast: text => { $.ui.toast(text) },
1144 }
1145}
1146
1147function recordReady($: EngineInterface, settings: Settings, input: Record<string, unknown>): Promise<string> { return recordReadyTo(pushIoOf($), settings, input) }
1148function settleBatch($: EngineInterface): Promise<void> { return settleBatchTo(pushIoOf($)) }
1149function pushAct($: EngineInterface, act: PushAct, by: string): Promise<string> { return pushActTo(pushIoOf($), act, by) }
1150function onPushAnswer($: EngineInterface, q: Question, answer: string, by: string): Promise<string> { return onPushAnswerTo(pushIoOf($), q, answer, by) }
1151
1152// The io closures standing-run.ts works through: each one spells its `$.noun.event(...)` call.
1153function standingIoOf($: EngineInterface): StandingIo {
1154 return {
1155 locate: () => locate($),
1156 readFile: path => readQuietly($, path),
1157 mkdirp: dir => $.process.run(['mkdir', '-p', dir]),
1158 writeJson: (path, obj) => writeJsonAtomic($, path, obj),
1159 readJson: path => readJson($, path),
1160 stateDir: () => stateDir($),
1161 run: argv => $.process.run(argv),
1162 now: () => $.clock.now(),
1163 today: () => today($),
1164 inbox: () => read($, inbox),
1165 withInbox: fn => withInbox($, fn),
1166 appendNote: (name, line) => appendNote($, name, line),
1167 appendLog: event => appendLog($, event),
1168 best: (what, fn) => best($, what, fn),
1169 }
1170}
1171
1172
1173// One line appended to log.jsonl. A single short append does not interleave with another session's.
1174async function appendLog($: EngineInterface, event: Omit<LogEvent, 'ts'>, max = TEXT_MAX): Promise<void> {
1175 try {
1176 const dir = await stateDir($)
1177 if (dir === undefined) return
1178 const t = await $.clock.now()
1179 const ts = new Date(t).toISOString()
1180 const entry: LogEvent = { ts, ...event }
1181 if (entry.text !== undefined) entry.text = cap(entry.text.replaceAll('\n', ' '), max)
1182 await $.process.run(['mkdir', '-p', dir])
1183 const r = await $.process.run(['sh', '-c', 'printf "%s\\n" "$1" >> "$2"', 'sh', JSON.stringify(entry), `${dir}/log.jsonl`])
1184 if (r.exitCode !== 0) throw new Error(r.stderr.trim() || 'append failed')
1185 } catch (err) {
1186 await warn($, 'appending to log.jsonl', err)
1187 }
1188}
1189
1190// Every parsable line, oldest first; a corrupt line is skipped.
1191async function readLog($: EngineInterface): Promise<LogEvent[]> {
1192 const dir = await stateDir($)
1193 if (dir === undefined) return []
1194 const raw = await readQuietly($, `${dir}/log.jsonl`)
1195 if (raw === undefined) return []
1196 const events: LogEvent[] = []
1197 for (const line of raw.split('\n')) {
1198 try {
1199 const e = JSON.parse(line) as LogEvent
1200 if (typeof e === 'object' && e !== null && typeof e.event === 'string') events.push(e)hooks/startup-run.ts 378 lines1import type { EngineInterface } from 'claude-code'
2import type { Breaker, Handover } from '../types'
3import { MANAGER } from './core'
4import { ENDED } from './deliver'
5import { dueForPrompt, normalizeChecks } from './checks'
6import type { Checks } from './checks'
7import { normalizeDeploys } from './deploy'
8import type { Deploys } from './deploy'
9import { normalizeInbox } from './inbox'
10import type { Inbox } from './inbox'
11import { normalizeLite } from './lite'
12import type { LiteState } from './lite'
13import { normalizePreflight } from './preflight'
14import type { Preflight } from './preflight'
15import { deployModeWarnings, fill, MANAGER_PROMPT, NO_REVIEWER_RULE, REVIEWER_PROMPT, REVIEWER_RULE, WORKER_PROMPT } from './prompts'
16import { normalizePush } from './pushgate'
17import type { PushState } from './pushgate'
18import { normalizeBreaker } from './reviewer-breaker'
19import { mergeLayers, settingsOf } from './settings'
20
21// The body of the session.start hook and the settings loading it and its recheck timer use. The registration
22// and the state of register() stay in register.tsx; this takes closures over them (the engine refuses `$`
23// across an import).
24type Settings = ReturnType<typeof settingsOf>
25export type Merged = { settings: Settings; seen: string }
26type AgentSpec = Parameters<EngineInterface['agent']['register']>[0]
27type CommandSpec = Parameters<EngineInterface['command']['register']>[0]
28export type StartupRelay = { role: 'worker' | 'manager' | 'reviewer'; name: string; dir: string | undefined }
29
30export type StartupIo = {
31 options: Record<string, unknown>
32 pollMs: number
33 prPollMs: number
34 initHint: string
35 best: (what: string, fn: () => Promise<void>) => Promise<void>
36 run: (argv: string[], opts?: { timeoutMs?: number }) => Promise<{ exitCode: number; stdout: string }>
37 toast: (text: string) => void
38 every: (ms: number, fn: () => void) => void
39 after: (ms: number, fn: () => void) => void
40 now: () => Promise<number>
41 // What this process is, from FLOW_ROLE; setRelay keeps it for the other hooks.
42 relayMode: () => Promise<StartupRelay | undefined>
43 setRelay: (r: StartupRelay | undefined) => void
44 // The settings reload state and the one place that applies it.
45 settings: () => Settings
46 applySettings: (s: Settings) => void
47 paths: () => string[]
48 setPaths: (p: string[]) => void
49 detected: () => string
50 setDetected: (base: string) => void
51 seen: () => string
52 setSeen: (s: string) => void
53 checking: () => boolean
54 setChecking: (on: boolean) => void
55 locate: () => Promise<string[]>
56 readText: (path: string) => Promise<string | undefined>
57 mtime: (path: string) => Promise<number>
58 registerAgent: (spec: AgentSpec) => Promise<unknown>
59 registerCommand: (spec: CommandSpec) => Promise<unknown>
60 registerTools: () => Promise<void>
61 // A claude worker's copy: the worker's tools only.
62 registerWorkerTools: () => Promise<void>
63 // The state loaders.
64 resetDelivery: () => void
65 resetStateDir: () => void
66 readState: (file: string) => Promise<{ disk: unknown } | undefined>
67 loadHandovers: () => Promise<Record<string, Handover>>
68 mergeHandovers: (disk: Record<string, Handover>) => Promise<void>
69 autoSweep: () => void
70 setInbox: (disk: Inbox) => Promise<void>
71 setBreaker: (disk: Breaker) => Promise<void>
72 releaseHalt: () => Promise<void>
73 installedVersion: () => Promise<string | undefined>
74 installed: () => string | undefined
75 setInstalled: (v: string | undefined) => void
76 handovers: () => Promise<Record<string, Handover>>
77 checks: () => Promise<Checks>
78 setChecks: (disk: Checks) => Promise<void>
79 captureChecks: (ho: Handover, verifyPaths: string[]) => Promise<unknown>
80 markPrompted: (version: string | undefined) => Promise<void>
81 setDeploys: (disk: Deploys) => Promise<void>
82 deployKnown: (name: string) => boolean
83 refreshBehind: () => void
84 setPush: (disk: PushState) => Promise<void>
85 setLite: (disk: LiteState) => Promise<void>
86 mergeSessions: (raw: unknown) => Promise<void>
87 snapshotSessions: () => Promise<void>
88 adoptSessions: () => Promise<void>
89 setPreflight: (disk: Preflight) => Promise<void>
90 agents: () => Promise<{ type: string; status: string; name?: string }[]>
91 closePreflight: (live: string[], t: number) => Promise<void>
92 setSlotDir: (dir: string | undefined) => void
93 sh: (script: string, arg: string) => Promise<unknown>
94 // The timers and what they call.
95 relaySessionCount: () => Promise<number>
96 pump: () => void
97 refresh: () => void
98 watchSessions: () => void
99 fetchPrs: () => void
100 refreshLeftovers: () => void
101 tickNow: () => Promise<void>
102 startReviewer: () => Promise<void>
103 clearDemo: () => Promise<void>
104 firstRun: () => Promise<boolean>
105}
106
107// Cheap change check for the roster poll: both files' mtimes, "-" for a missing one.
108async function signature(io: StartupIo, paths: string[]): Promise<string> {
109 const parts = await Promise.all(paths.map(async p => {
110 try {
111 if (p === '') return '-'
112 return String(await io.mtime(p))
113 } catch {
114 return '-'
115 }
116 }))
117 return parts.join('|')
118}
119
120// Layer /config under the settings files. The caller assigns the result (register's `apply`).
121async function loadSettings(io: StartupIo, paths: string[], base: string): Promise<Merged> {
122 const seen = await signature(io, paths)
123 const layers = await Promise.all(paths.map(async path => ({ path, text: await io.readText(path) })))
124 const loaded = mergeLayers(io.options, layers)
125 const warnings = [...loaded.warnings, ...deployModeWarnings(loaded.raw.deploy_targets)]
126 if (warnings.length > 0) io.toast(`flow settings:\n${warnings.join('\n')}`)
127 return { settings: settingsOf(loaded.raw, base), seen }
128}
129
130// The agent definitions carry the settings' prompts and models; a re-registered name is
131// replaced from the next turn, so agents already running keep what they started with.
132async function registerAgents(io: StartupIo, settings: Settings) {
133 await io.registerAgent({
134 name: 'manager',
135 description: 'A flow manager: owns one task, writes briefs, starts flow:worker agents, reviews their PRs and hands them to the reviewer. ' +
136 'Pass the task in the user\'s words as the prompt and a short task slug as the name; run it in the background.',
137 prompt: fill(MANAGER_PROMPT.replace('{{REVIEWER_RULE}}', settings.useReviewer ? REVIEWER_RULE : NO_REVIEWER_RULE), settings),
138 model: settings.managerModel,
139 background: true,
140 })
141 await io.registerAgent({
142 name: 'worker',
143 description: 'A flow worker: implements one brief in a git worktree of its own and opens a PR. ' +
144 'Pass the whole brief as the prompt, its first line "Your name: <slug>", and the slug as the name.',
145 prompt: fill(WORKER_PROMPT, settings),
146 model: settings.workerModel,
147 isolation: 'worktree',
148 background: true,
149 })
150 await io.registerAgent({
151 name: 'continue',
152 description: 'A flow worker that continues a handed-off branch in the same worktree. The plugin picks it when a flow:worker spawn says "Continue on branch:"; never start it yourself.',
153 prompt: fill(WORKER_PROMPT, settings),
154 model: settings.workerModel,
155 background: true,
156 })
157 await io.registerAgent({
158 name: 'reviewer',
159 description: 'The flow reviewer. Started by the plugin when a PR is handed over; never start it yourself.',
160 prompt: fill(REVIEWER_PROMPT, settings),
161 model: settings.reviewerModel,
162 isolation: 'worktree',
163 background: true,
164 })
165 // The old agent type name, kept so a spawn or a resume under flow:queue still works.
166 await io.registerAgent({
167 name: 'queue',
168 description: 'The old name of flow:reviewer. Never start it; the plugin starts flow:reviewer.',
169 prompt: fill(REVIEWER_PROMPT, settings),
170 model: settings.reviewerModel,
171 isolation: 'worktree',
172 background: true,
173 })
174}
175
176// Re-read the settings when a file's mtime changed (the roster poll calls this): undefined when
177// nothing changed or the reload failed, which never stops the roster refresh.
178async function recheck(io: StartupIo): Promise<Merged | undefined> {
179 try {
180 if ((await signature(io, io.paths())) === io.seen()) return undefined
181 const merged = await loadSettings(io, io.paths(), io.detected())
182 await registerAgents(io, merged.settings)
183 return merged
184 } catch {
185 return undefined
186 }
187}
188
189// One state file: the loader runs only when there is a state dir; a failure is a warning, never a throw.
190// The blocks differ too much in what they do with the file to be one table, so each keeps its own body.
191async function loadState(io: StartupIo, what: string, file: string, apply: (disk: unknown) => Promise<void>): Promise<void> {
192 await io.best(what, async () => {
193 const got = await io.readState(file)
194 if (got === undefined) return
195 await apply(got.disk)
196 })
197}
198
199// The body of the session.start hook, up to the `next(e)` that stays in register.tsx.
200export async function startSession(io: StartupIo): Promise<void> {
201 // First of all, what this process is: a terminal-started worker without a relay dir (started before workers
202 // had one) is passive (no tools, no state, no timers: its copy must not wipe main's test-slot grants); a
203 // manager, the reviewer or a worker with one relays to main.
204 const relay = await io.relayMode()
205 io.setRelay(relay)
206 if (relay?.role === 'worker' && relay.dir === undefined) return
207 if (relay !== undefined) {
208 // A terminal claude's own copy: it holds no state and runs no timers. It reads the settings for its
209 // local guards, shows the tools (a worker only its own) and the /flow stub, and forwards every flow tool
210 // call to main (tool.call).
211 try {
212 const local = await io.run(['git', 'symbolic-ref', '--short', 'refs/remotes/origin/HEAD'])
213 if (local.exitCode === 0 && local.stdout.trim() !== '') io.setDetected(local.stdout.trim().replace(/^origin\//, ''))
214 } catch {
215 // Not a git repo, or no remote: keep "main".
216 }
217 io.setPaths(await io.locate())
218 try {
219 io.applySettings((await loadSettings(io, io.paths(), io.detected())).settings)
220 } catch {
221 // Keep the settings from /config alone.
222 }
223 await io.registerCommand({
224 name: 'flow',
225 description: 'The flow pane and commands live in the main Claude Code session: run /flow there. This session\'s mcp__flow__* tools are forwarded to it.',
226 })
227 await io.registerCommand({
228 name: 'flow-tasks',
229 description: 'Runs in the main Claude Code session: run /flow-tasks there.',
230 })
231 await (relay.role === 'worker' ? io.registerWorkerTools() : io.registerTools())
232 return
233 }
234 io.resetDelivery()
235 // Handovers a restart would lose: merge what is on disk under this session's own records.
236 let queueDue = false
237 await io.best('loading handovers', async () => {
238 io.resetStateDir()
239 const disk = await io.loadHandovers()
240 if (Object.keys(disk).length === 0) return
241 await io.mergeHandovers(disk)
242 queueDue = Object.values(disk).some(ho => ho.status === 'pending')
243 })
244 await loadState(io, 'loading the inbox', 'inbox.json', raw => io.setInbox(normalizeInbox(raw)))
245 // A fresh session is a fresh attempt: the halt and the wait end, the failure history stays.
246 await loadState(io, 'loading the reviewer breaker', 'reviewer-breaker.json', async raw => {
247 await io.setBreaker(normalizeBreaker(raw))
248 await io.releaseHalt()
249 })
250 await io.best('loading checks', async () => {
251 io.setInstalled(await io.installedVersion())
252 const got = await io.readState('checks.json')
253 if (got === undefined) return
254 await io.setChecks(normalizeChecks(got.disk))
255 // Done handovers from before checks existed (or a session that died first) get theirs once.
256 for (const ho of Object.values(await io.handovers())) {
257 // A PR that already has a check (any state) runs no git calls on a normal restart.
258 if (ho.status === 'done' && !(await io.checks()).items.some(c => c.pr === ho.pr)) await io.captureChecks(ho, io.settings().verifyPaths)
259 }
260 // Once per installed version: a toast names the checks it now covers. Not a prompt: an update
261 // must not start a turn in main; the checks stay in /flow checks, the inbox and the pane.
262 const installed = io.installed()
263 const due = dueForPrompt(await io.checks(), installed)
264 if (due.length === 0) return
265 await io.markPrompted(installed)
266 io.toast(`flow ${installed}: ${due.length} after-deploy check${due.length === 1 ? '' : 's'} can be done now. /flow checks lists them.`)
267 })
268 await loadState(io, 'loading deploy gates', 'deploys.json', async raw => {
269 const disk = normalizeDeploys(raw)
270 await io.setDeploys(disk)
271 queueDue = queueDue || Object.entries(disk.targets).some(([name, t]) => t.due === true && io.deployKnown(name))
272 io.refreshBehind()
273 })
274 await loadState(io, 'loading the push gate', 'push.json', async raw => {
275 const disk = normalizePush(raw)
276 await io.setPush(disk)
277 // A released or rebuilding batch left by a session that ended gets its reviewer.
278 queueDue = queueDue || (disk.batch !== undefined && disk.batch.state !== 'ready')
279 })
280 await loadState(io, 'loading lite managers', 'lite.json', raw => io.setLite(normalizeLite(raw)))
281 // Terminal sessions from before a restart: their relay directories are pumped again.
282 await loadState(io, 'loading sessions', 'sessions.json', async raw => {
283 await io.mergeSessions(raw)
284 await io.snapshotSessions()
285 await io.adoptSessions()
286 })
287 await loadState(io, 'loading pre-flight', 'preflight.json', async raw => {
288 await io.setPreflight(normalizePreflight(raw))
289 // A round left undelivered by a session that ended is not sent now.
290 const live = (await io.agents()).filter(a => a.type === MANAGER && !(ENDED as Set<string>).has(a.status) && a.name !== undefined).map(a => a.name!)
291 await io.closePreflight(live, await io.now())
292 })
293 // The base branch: the option, else the remote's default branch, else main.
294 // A fresh clone may have no origin/HEAD, so ask the remote when the local ref is missing.
295 try {
296 const local = await io.run(['git', 'symbolic-ref', '--short', 'refs/remotes/origin/HEAD'])
297 let base = local.exitCode === 0 ? local.stdout.trim().replace(/^origin\//, '') : ''
298 if (base === '') {
299 const remote = await io.run(['git', 'ls-remote', '--symref', 'origin', 'HEAD'], { timeoutMs: 10_000 })
300 base = /ref: refs\/heads\/(\S+)\s+HEAD/.exec(remote.stdout)?.[1] ?? ''
301 }
302 if (base !== '') io.setDetected(base)
303 } catch {
304 // Not a git repo, or no remote: keep "main".
305 }
306 io.setPaths(await io.locate())
307 try {
308 const merged = await loadSettings(io, io.paths(), io.detected())
309 io.setSeen(merged.seen)
310 io.applySettings(merged.settings)
311 } catch {
312 // Keep the settings from /config alone.
313 }
314 // Reviewer worktrees left over from before a restart or reload. Only now: the sessions loaded and
315 // adopted above are what keeps a terminal reviewer's or worker's worktree from the sweep (swept
316 // before, a resumed reviewer found its worktree gone, #222), and the settings say whether to sweep.
317 io.autoSweep()
318
319 // Grant files of a previous session would read as grants; start from an empty directory.
320 try {
321 const r = await io.run(['git', 'rev-parse', '--path-format=absolute', '--git-common-dir'])
322 if (r.exitCode === 0 && r.stdout.trim() !== '') {
323 const slotDir = `${r.stdout.trim()}/flow/test-slots`
324 io.setSlotDir(slotDir)
325 await io.sh('rm -rf "$1" && mkdir -p "$1"', slotDir)
326 }
327 } catch {
328 io.setSlotDir(undefined)
329 }
330
331 await io.registerCommand({
332 name: 'flow',
333 description: 'Show the flow in a pane: managers, their workers, the reviewer and handed-over PRs. /flow inbox lists the open questions and the decisions agents made (/flow inbox decisions lists them all, /flow inbox <id> shows one in full), /flow ok keeps every open decision (/flow ok <id|owner|topic> takes those, or the default of a question), /flow no <id> [what instead] undoes a decision, /flow answer <id> <choice> answers any question addressed to main, /flow status shows what the agents cost (estimates at API list prices), /flow checks lists the after-deploy checks that need a person (pass or fail them), /flow preflight shows the current pre-flight round, /flow close closes it, /flow lite <task> runs one task as just a manager and its workers (no pre-flight, no reviewer agent) to save tokens, /flow resume picks up unfinished flow work, /flow approve <pr> lets the reviewer merge a PR that awaits your approval, /flow reject <pr> [reason] (alias /flow drop) turns down a handover that awaits approval or is pending, /flow push starts the push of the batch the reviewer checked and saved (push_mode confirm; /flow push back <pr> sends one PR back, /flow push drop returns them all), /flow hold <target> [batch|released] keeps a deploy target from deploying and /flow release <target> lets it, /flow clean lists leftover worktrees and branches (--yes removes them)',
334 argumentHint: '[inbox [all|archive [all]|<id>]|ok [<id|owner|topic>...]|no <id> [what instead]|answer <id> <choice>|checks|status|preflight|close|lite <task>|resume|approve <pr>|reject <pr> [reason]|push [back <pr>|drop]|clean]',
335 })
336 await io.registerCommand({
337 name: 'flow-tasks',
338 description: 'Pick tasks from a task source (.claude/flow/sources/<name>.md) and start a manager for each',
339 argumentHint: '[source] [ids or filter]',
340 })
341 await registerAgents(io, io.settings())
342
343 await io.registerTools()
344
345 // Calls the terminal managers, the reviewer and claude workers left in their relay directories (see pumpOnce).
346 // The fast timer exists only while such a session does: armed here for sessions a restart brought back, and by the
347 // roster poll below for ones started since. It never goes away; pumpOnce does nothing without a live one.
348 let pumpArmed = false
349 const armPump = async () => {
350 if (pumpArmed || (await io.relaySessionCount()) === 0) return
351 pumpArmed = true
352 io.every(500, () => io.pump())
353 }
354 await armPump()
355 io.every(io.pollMs, () => {
356 void io.adoptSessions().then(armPump).catch(() => undefined)
357 io.refresh()
358 io.watchSessions()
359 if (io.checking()) return
360 io.setChecking(true)
361 void recheck(io).then(m => {
362 if (m !== undefined) { io.setSeen(m.seen); io.applySettings(m.settings) }
363 }).finally(() => { io.setChecking(false) })
364 })
365 // gh is not free: a slow timer, one look shortly after the start, and status when the list is stale.
366 io.every(io.prPollMs, () => { io.fetchPrs(); io.refreshBehind(); io.refreshLeftovers() })
367 io.fetchPrs()
368 io.refreshLeftovers()
369 // One shared tick for every running time on the pane: the render reads `now`, no card has a timer.
370 io.every(1000, () => void io.tickNow().catch(() => undefined))
371 // The reviewer agent type exists only now, and a spawn needs the session bound: start it after the hook.
372 if (queueDue) io.after(0, () => void io.best('starting the reviewer', io.startReviewer))
373 // A replay left over from before a reload is gone with the atom's memory; this clears it explicitly.
374 await io.clearDemo()
375 // A new repo: one line pointing at /flow init, after the session has drawn.
376 io.after(3000, () => void io.best('first-run hint', async () => { if (await io.firstRun()) io.toast(io.initHint) }))
377}
378hooks/mergemode.ts 35 lines1// Merge mode: whether the reviewer merges an approved PR directly (auto) or waits for the user's
2// /flow approve (confirm). Pure rules, so the handover and reviewer handlers stay thin.
3
4export type MergeMode = 'auto' | 'confirm'
5
6export const CONFIRM_LABEL = 'flow:confirm'
7export const AUTO_LABEL = 'flow:auto'
8
9// Unknown values fall back to auto, the behaviour before the setting existed.
10export const parseMode = (v: unknown): MergeMode => v === 'confirm' ? 'confirm' : 'auto'
11
12// The PR's own label wins; both labels means the safer one.
13export function labelMode(labels: string[]): MergeMode | undefined {
14 if (labels.includes(CONFIRM_LABEL)) return 'confirm'
15 if (labels.includes(AUTO_LABEL)) return 'auto'
16 return undefined
17}
18
19// Label > the mode stored on the handover > the setting.
20export const effectiveMode = (labels: string[], stored: MergeMode | undefined, setting: MergeMode): MergeMode =>
21 labelMode(labels) ?? stored ?? setting
22
23// A manager may only make a PR safer; lowering a confirm setting is the user's call.
24export const autoRefused = (requested: MergeMode | undefined, setting: MergeMode): boolean =>
25 requested === 'auto' && setting === 'confirm'
26
27// What `take` does: hold a confirm PR until the user approved exactly this head.
28export const takeDecision = (a: { labels: string[]; stored?: MergeMode; setting: MergeMode; head: string; approvedHead?: string }): 'take' | 'hold' =>
29 effectiveMode(a.labels, a.stored, a.setting) === 'confirm' && a.approvedHead !== a.head ? 'hold' : 'take'
30
31export const labelSpec = (mode: MergeMode): { name: string; color: string; description: string } =>
32 mode === 'confirm'
33 ? { name: CONFIRM_LABEL, color: 'D93F0B', description: 'flow: the reviewer waits for the user to approve this PR (/flow approve)' }
34 : { name: AUTO_LABEL, color: '0E8A16', description: 'flow: the reviewer may merge this PR without asking' }
35hooks/slots.ts 74 lines1import type { AgentRow, SlotEntry, TestSlots } from '../types'
2import { ENDED } from './deliver'
3
4// A hook has a 10 s budget, a $.clock wait included, so acquire blocks only briefly. A free slot
5// is granted to the head waiter at once (claimed: false); it has CLAIM_MS to confirm with acquire,
6// else the grant passes on. The grant is signalled by a file and a message, so waiting costs no turns.
7export const LEASE_MS = 45 * 60_000
8export const CLAIM_MS = 2 * 60_000
9export const WAIT_MAX_S = 8
10export const WAIT_DEFAULT_S = 2
11
12// The grant file of a waiter, under the slot directory `dir`; undefined when there is none.
13export const grantFile = (dir: string | undefined, key: string): string | undefined => dir && `${dir}/${key.replace(/[^\w.-]/g, '_')}.granted`
14
15export const span = (ms: number): string => {
16 const m = Math.floor(ms / 60_000)
17 return m < 1 ? `${Math.max(0, Math.round(ms / 1000))}s` : `${m}m`
18}
19export const heldBy = (h: SlotEntry, t: number): string => `${h.name} (${h.label}, ${span(t - h.since)})`
20
21// Drops holders and waiters whose agent ended or is gone and holders past the lease. The main session (key "main") never ends. Returns the new state and what was dropped.
22export function reapSlots(state: TestSlots, rows: AgentRow[], t: number): { state: TestSlots; notes: string[] } {
23 const status = new Map(rows.map(a => [a.id, a.status]))
24 const gone = (key: string) => key !== 'main' && (status.get(key) === undefined || ENDED.has(status.get(key)!))
25 const notes: string[] = []
26 const holders = state.holders.filter(h => {
27 if (gone(h.key)) return false
28 if (t - h.since >= LEASE_MS) {
29 notes.push(`test slot of ${h.name} (${h.label}) released after ${span(LEASE_MS)}: its lease ran out`)
30 return false
31 }
32 return true
33 })
34 const waiters = state.waiters.filter(w => !gone(w.key))
35 const changed = holders.length !== state.holders.length || waiters.length !== state.waiters.length
36 return { state: changed ? { holders, waiters } : state, notes }
37}
38
39// Adds a waiter to the line. A priority waiter (the reviewer: merging is the shared bottleneck) goes
40// ahead of every non-priority waiter and behind earlier priority ones; it never touches holders, so a
41// running holder or an offered grant stays. Others join at the end. A key already waiting keeps its place.
42export function enqueueWaiter(waiters: SlotEntry[], w: SlotEntry): SlotEntry[] {
43 if (waiters.some(x => x.key === w.key)) return waiters
44 if (w.priority !== true) return [...waiters, w]
45 const at = waiters.findIndex(x => x.priority !== true)
46 return at < 0 ? [...waiters, w] : [...waiters.slice(0, at), w, ...waiters.slice(at)]
47}
48
49// Gives free slots to the head waiters, after dropping grants nobody confirmed within CLAIM_MS.
50// Pure: the caller does the signalling for `granted`.
51export function grantSlots(state: TestSlots, limit: number, t: number): { state: TestSlots; granted: SlotEntry[]; notes: string[] } {
52 const notes: string[] = []
53 const holders = state.holders.filter(h => {
54 if (h.claimed !== false || t - h.since < CLAIM_MS) return true
55 notes.push(`test slot offered to ${h.name} (${h.label}) passed on: not confirmed within ${span(CLAIM_MS)}`)
56 return false
57 })
58 const waiters = [...state.waiters]
59 const granted: SlotEntry[] = []
60 while (holders.length < limit && waiters.length > 0) {
61 const w = { ...waiters.shift()!, since: t, claimed: false }
62 holders.push(w)
63 granted.push(w)
64 }
65 const changed = holders.length !== state.holders.length || granted.length > 0
66 return { state: changed ? { holders, waiters } : state, granted, notes }
67}
68
69export function slotLine(state: TestSlots, limit: number, t: number): string {
70 if (state.holders.length === 0 && state.waiters.length === 0) return ''
71 const held = state.holders.length ? `held by ${state.holders.map(h => heldBy(h, t)).join(', ')}` : 'free'
72 return `Test slots: ${state.holders.length}/${limit} ${held}${state.waiters.length ? ` · ${state.waiters.length} waiting` : ''}`
73}
74hooks/typecheck-slots.ts 100 lines1import type { AgentRow, SlotEntry, TestSlots } from '../types'
2import { ENDED } from './deliver'
3import { grantSlots, grantFile, heldBy, span, CLAIM_MS, WAIT_DEFAULT_S, WAIT_MAX_S } from './slots'
4import type { SlotsIo } from './slots-run'
5import type { Settings } from './prompts'
6
7// The typecheck pool: the same shape and rules as the test slots, but its own holders, a short
8// lease (a typecheck takes a minute, not a suite's 45), and a lighter limit, so a typecheck never
9// queues behind a suite.
10export const TYPECHECK_LEASE_MS = 10 * 60_000
11
12// Like reapSlots, with the short lease.
13export function reapTypecheck(state: TestSlots, rows: AgentRow[], t: number): { state: TestSlots; notes: string[] } {
14 const status = new Map(rows.map(a => [a.id, a.status]))
15 const gone = (key: string) => key !== 'main' && (status.get(key) === undefined || ENDED.has(status.get(key)!))
16 const notes: string[] = []
17 const holders = state.holders.filter(h => {
18 if (gone(h.key)) return false
19 if (t - h.since >= TYPECHECK_LEASE_MS) {
20 notes.push(`typecheck slot of ${h.name} (${h.label}) released after ${span(TYPECHECK_LEASE_MS)}: its lease ran out`)
21 return false
22 }
23 return true
24 })
25 const waiters = state.waiters.filter(w => !gone(w.key))
26 const changed = holders.length !== state.holders.length || waiters.length !== state.waiters.length
27 return { state: changed ? { holders, waiters } : state, notes }
28}
29
30// grantSlots, with its notes worded for this pool.
31export function grantTypecheck(state: TestSlots, limit: number, t: number): { state: TestSlots; granted: SlotEntry[]; notes: string[] } {
32 const g = grantSlots(state, limit, t)
33 return { ...g, notes: g.notes.map(n => n.replace('test slot', 'typecheck slot')) }
34}
35
36// Grant files of the typecheck pool live beside the test pool's, in a subdirectory.
37export const typecheckDir = (dir: string | undefined): string | undefined => dir && `${dir}/typecheck`
38
39export function typecheckLine(state: TestSlots, limit: number, t: number): string {
40 if (state.holders.length === 0 && state.waiters.length === 0) return ''
41 const held = state.holders.length ? `held by ${state.holders.map(h => heldBy(h, t)).join(', ')}` : 'free'
42 return `Typecheck slots: ${state.holders.length}/${limit} ${held}${state.waiters.length ? ` · ${state.waiters.length} waiting` : ''}`
43}
44
45// test_slot with kind "typecheck": acquire, release, status on the typecheck pool.
46export async function typecheckSlotTool(io: SlotsIo, settings: Settings, input: Record<string, unknown>, rows: AgentRow[], key: string, name: string): Promise<{ result: string }> {
47 const action = String(input.action)
48 const label = typeof input.label === 'string' && input.label.trim() !== '' ? input.label.trim().slice(0, 60) : 'typecheck'
49 const limit = settings.typecheckSlots ?? 1
50 const t = await io.now()
51 const slots = io.typecheckSlots!
52 const settle = io.settleTypecheck!
53
54 if (action === 'status') {
55 return { result: typecheckLine(await slots(), limit, t) || `Typecheck slots: 0/${limit} held, nobody waiting.` }
56 }
57 if (action === 'release') {
58 let freed = false
59 await settle(rows, t, st => {
60 freed = st.holders.some(h => h.key === key)
61 return freed ? { ...st, holders: st.holders.filter(h => h.key !== key) } : st
62 })
63 return { result: freed ? 'Released your typecheck slot.' : 'You held no typecheck slot; nothing to release.' }
64 }
65 if (action !== 'acquire') return { result: `Unknown action "${action}".` }
66
67 // Check and take inside one update(), so two callers never both get the last slot.
68 const attempt = async (): Promise<string | undefined> => {
69 let already: SlotEntry | undefined
70 const at = await io.now()
71 await settle(rows, at, st => {
72 already = st.holders.find(h => h.key === key)
73 if (already || st.waiters.some(w => w.key === key)) return st
74 return { ...st, waiters: [...st.waiters, { key, name, label, since: at }] }
75 }, key)
76 if (already?.claimed === true) {
77 return `You already hold a typecheck slot (${already.label}, ${span(at - already.since)}). Release it when the typecheck is over.`
78 }
79 const st = await slots()
80 if (!st.holders.some(h => h.key === key)) return undefined
81 return `Typecheck slot granted (${st.holders.length}/${limit}). Run it, then release the slot, also if it fails. It frees by itself after ${span(TYPECHECK_LEASE_MS)}.`
82 }
83
84 const wait = Math.min(WAIT_MAX_S, Math.max(0, Number.isFinite(Number(input.wait_s)) ? Number(input.wait_s) : WAIT_DEFAULT_S))
85 const first = await attempt()
86 if (first !== undefined) return { result: first }
87 for (let waited = 0; waited < wait; waited++) {
88 await io.sleep(1000)
89 await io.refresh()
90 const got = await attempt()
91 if (got !== undefined) return { result: got }
92 }
93 const st = await slots()
94 const pos = st.waiters.findIndex(w => w.key === key) + 1
95 const f = grantFile(typecheckDir(io.slotDir()), key)
96 return {
97 result: `No typecheck slot after ${wait} s; queued, position ${pos}. Held by ${st.holders.map(h => heldBy(h, t)).join(', ') || 'nobody'}. You keep your place and are granted the slot when it is your turn (it is offered for ${span(CLAIM_MS)}). Don't poll acquire. ${f ? `Wait with Bash: until [ -e '${f}' ]; do sleep 3; done . Or do other work; a "your typecheck slot is granted" message arrives.` : 'Do other work; a "your typecheck slot is granted" message arrives.'} Then call acquire (kind "typecheck") once to confirm, run, and release.`,
98 }
99}
100hooks/evidence.ts 118 lines1// The `## Verification` section of a PR description: what the worker ran, how the change was exercised for
2// real, and what was not verified. `handover` refuses a PR without it; the parsed record travels with the
3// handover into the reviewer report and the status file. Pure, so it is tested without the plugin runtime.
4
5import type { GuardHit } from './guardtests'
6
7export type Evidence = { ran: string[]; exercised: string; notVerified: string[] }
8
9export const EVIDENCE_FORMAT = [
10 '## Verification',
11 'Ran:',
12 '- `<command>`: pass (<short result, e.g. 42 tests>)',
13 'Exercised: <how the change was run for real: app launched and what was seen, screenshot path, curl output, or "n/a: <reason>" for docs/prompt-only changes>',
14 'Not verified:',
15 '- <what you did not check> (or one line "Not verified: none, because <reason>")',
16].join('\n')
17
18const LABELS = { ran: /^ran$/i, exercised: /^exercised$/i, notVerified: /^not verified$/i }
19type Key = keyof typeof LABELS
20
21const bullet = /^\s*[-*]\s+/
22const label = /^\s*(ran|exercised|not verified)\s*:\s*(.*)$/i
23
24// The text of the section, or undefined when the body has none. Case-insensitive heading, ends at the next `## `.
25export function verificationSection(body: string): string | undefined {
26 const lines = body.replace(/\r\n?/g, '\n').split('\n')
27 const start = lines.findIndex(l => /^##\s+verification\s*$/i.test(l.trim()))
28 if (start < 0) return undefined
29 const rest = lines.slice(start + 1)
30 const end = rest.findIndex(l => /^##\s/.test(l))
31 return (end < 0 ? rest : rest.slice(0, end)).join('\n')
32}
33
34// Labels may stand alone with bullets below, or carry text after the colon. Bullets are entries; any other
35// text under Ran or Not verified is one entry per line; Exercised joins its lines.
36export function parseVerification(section: string): Partial<Evidence> {
37 const out: Evidence = { ran: [], exercised: '', notVerified: [] }
38 const seen = new Set<Key>()
39 let cur: Key | undefined
40 const add = (key: Key, text: string) => {
41 const t = text.trim()
42 if (!t) return
43 if (key === 'exercised') out.exercised = out.exercised ? `${out.exercised} ${t}` : t
44 else out[key].push(t)
45 }
46 for (const raw of section.split('\n')) {
47 const m = label.exec(raw)
48 if (m && !bullet.test(raw)) {
49 cur = (Object.keys(LABELS) as Key[]).find(k => LABELS[k].test(m[1]!.trim()))!
50 seen.add(cur)
51 add(cur, m[2]!)
52 } else if (cur) {
53 add(cur, raw.replace(bullet, ''))
54 }
55 }
56 return {
57 ...(seen.has('ran') ? { ran: out.ran } : {}),
58 ...(seen.has('exercised') ? { exercised: out.exercised } : {}),
59 ...(seen.has('notVerified') ? { notVerified: out.notVerified } : {}),
60 }
61}
62
63const unticked = (s: string) => s.replace(/`/g, '')
64
65// Evidence when the body qualifies, else every reason it does not. `required` are the settings' workerChecks
66// and alwaysTests: each must appear (backticks optional) in some Ran entry. `guard` are the guard tests the PR's
67// changed files require (guardtests.ts): same matching, and the refusal names the globs that triggered them.
68export function checkEvidence(body: string, required: string[], guard: GuardHit[] = []): { evidence: Evidence } | { problems: string[] } {
69 const section = verificationSection(body)
70 if (section === undefined) return { problems: ['the PR description has no `## Verification` section'] }
71 if (!section.trim()) return { problems: ['the `## Verification` section is empty'] }
72 const p = parseVerification(section)
73 const problems: string[] = []
74 if (!p.ran?.length) problems.push('`Ran:` has no entries')
75 if (!p.exercised) problems.push('`Exercised:` is missing or empty')
76 else if (/^n\/a:?$/i.test(p.exercised.trim())) problems.push('`Exercised: n/a` needs a reason ("n/a: <reason>")')
77 if (!p.notVerified?.length) problems.push('`Not verified:` is missing or empty')
78 else if (p.notVerified.length === 1 && /^(nothing|none|n\/a|-)\.?$/i.test(unticked(p.notVerified[0]!).trim())) {
79 problems.push('`Not verified:` must name at least one honest item, or say "none, because <reason>"')
80 }
81 if (p.ran?.length) {
82 const ran = p.ran.map(unticked)
83 for (const cmd of required) {
84 if (!ran.some(r => r.includes(unticked(cmd)))) problems.push(`required command \`${cmd}\` does not appear under \`Ran:\``)
85 }
86 for (const g of guard) {
87 if (required.includes(g.test) || ran.some(r => r.includes(unticked(g.test)))) continue
88 problems.push(`guard test \`${g.test}\` (for ${g.globs.map(x => `\`${x}\``).join(', ')}) does not appear under \`Ran:\``)
89 }
90 }
91 if (problems.length) return { problems }
92 return { evidence: { ran: p.ran!, exercised: p.exercised!, notVerified: p.notVerified! } }
93}
94
95export function evidenceRefusal(pr: number, problems: string[]): string {
96 return [
97 `Refused: PR #${pr} does not carry the proof handover requires:`,
98 ...problems.map(p => `- ${p}`),
99 'The PR description must contain this section:',
100 EVIDENCE_FORMAT,
101 `Have the worker fix the PR description (gh pr edit ${pr} --body-file <file>), then call handover again.`,
102 ].join('\n')
103}
104
105const clip = (s: string, n: number) => (s.length > n ? `${s.slice(0, n - 1)}…` : s)
106
107// Full text, for the reviewer's list.
108export function evidenceText(e: Evidence | undefined): string {
109 if (!e) return 'no evidence recorded'
110 return `ran: ${e.ran.join('; ')} | exercised: ${e.exercised} | not verified: ${e.notVerified.join('; ')}`
111}
112
113// Short, for the status line.
114export function evidenceSummary(e: Evidence | undefined): string {
115 if (!e) return 'no evidence recorded'
116 return `${e.ran.length} ran, exercised: ${clip(e.exercised, 60)}, ${e.notVerified.length} not verified`
117}
118hooks/mainff.ts 82 lines1// Fast-forward of the repo's main checkout after a reviewer batch. The reviewer runs worktree-isolated
2// and the host refuses its git calls on the main checkout, so the plugin (not subject to that
3// isolation) does it when the reviewer reports "done". Never stash, reset, checkout, clean or force.
4import { parsePorcelain } from './clean'
5
6export type Run = { exitCode: number; stdout: string; stderr: string }
7// Runs one argv, git first.
8export type GitRunner = (argv: string[]) => Promise<Run>
9
10// The line that says what went wrong: git's last error:/fatal: line, else the first line. A fetch's first
11// stderr line is "From <url>" chatter, which used to hide the real error.
12const reason = (r: Run): string => {
13 const lines = (r.stderr.trim() || r.stdout.trim()).split('\n').map(l => l.trim()).filter(l => l !== '')
14 const meaningful = lines.filter(l => /^(error|fatal):/.test(l)).pop() ?? lines[0]
15 return meaningful?.slice(0, 160) || `exit ${r.exitCode}`
16}
17// Another git process in the shared .git holds or just moved a ref: the auto cleanup sweep runs
18// `git fetch origin --prune` right as the reviewer reports "done", and both update origin/<base>.
19const LOCKED = /cannot lock ref|unable to update local ref|\.lock'?: File exists|Unable to create '.*\.lock'/i
20// Fetch attempts in all. Each retry is one more fetch, by which time the other fetch has finished.
21const FETCH_TRIES = 3
22const notUpdated = (why: string): string => `main checkout not updated: ${why}`
23
24// One line: "main checkout fast-forwarded to <sha>" or "main checkout not updated: <reason>".
25export async function fastForwardMain(git: GitRunner, base: string): Promise<string> {
26 try {
27 const wl = await git(['git', 'worktree', 'list', '--porcelain'])
28 if (wl.exitCode !== 0) return notUpdated(`worktree list failed: ${reason(wl)}`)
29 const main = parsePorcelain(wl.stdout)[0]?.path
30 if (main === undefined) return notUpdated('no main checkout found')
31 // Untracked files do not count as dirty; an incoming file that would overwrite one fails the merge.
32 const st = await git(['git', '-C', main, 'status', '--porcelain', '--untracked-files=no'])
33 if (st.exitCode !== 0) return notUpdated(`status failed: ${reason(st)}`)
34 if (st.stdout.trim() !== '') return notUpdated('dirty')
35 const br = await git(['git', '-C', main, 'branch', '--show-current'])
36 if (br.exitCode !== 0) return notUpdated(`branch check failed: ${reason(br)}`)
37 const on = br.stdout.trim()
38 if (on === '') return notUpdated('on a detached HEAD')
39 if (on !== base) return notUpdated(`on branch ${on}`)
40 // Fetch and merge apart, not `git pull`: a fetch that lost the ref race to a concurrent fetch is
41 // retried; the merge then reads the remote-tracking ref, which is current either way.
42 let fetched = await git(['git', '-C', main, 'fetch', 'origin', `+refs/heads/${base}:refs/remotes/origin/${base}`])
43 for (let i = 1; i < FETCH_TRIES && fetched.exitCode !== 0 && LOCKED.test(fetched.stderr); i++) {
44 fetched = await git(['git', '-C', main, 'fetch', 'origin', `+refs/heads/${base}:refs/remotes/origin/${base}`])
45 }
46 if (fetched.exitCode !== 0) return notUpdated(`ff failed: ${reason(fetched)}`)
47 const merged = await git(['git', '-C', main, 'merge', '--ff-only', `refs/remotes/origin/${base}`])
48 if (merged.exitCode !== 0) return notUpdated(`ff failed: ${reason(merged)}`)
49 const sha = await git(['git', '-C', main, 'rev-parse', '--short', 'HEAD'])
50 return `main checkout fast-forwarded to ${sha.exitCode === 0 ? sha.stdout.trim() : 'origin/' + base}`
51 } catch (err) {
52 return notUpdated(`ff failed: ${(err instanceof Error ? err.message : String(err)).split('\n')[0]?.slice(0, 160) ?? ''}`)
53 }
54}
55
56// One fast-forward at a time; several "done" calls in a batch queue behind each other. A repeat is
57// harmless: the second fetch and merge find nothing to do and answers fast-forwarded to the same sha.
58let chain: Promise<unknown> = Promise.resolve()
59export function serialFastForward(git: GitRunner, base: string): Promise<string> {
60 const next = chain.then(() => fastForwardMain(git, base), () => fastForwardMain(git, base))
61 chain = next
62 return next
63}
64
65// What a reviewer run did with the queue, for the line of a run that never reached "done".
66export type RunWork = { touched: boolean; ready: boolean; line?: string }
67
68export const noteWork = (w: RunWork | undefined, action: string): RunWork => {
69 const cur = w ?? { touched: false, ready: false }
70 if (action === 'ready') return { ...cur, touched: true, ready: true }
71 if (action === 'take' || action === 'back') return { ...cur, touched: true }
72 return cur
73}
74
75// The main-checkout line for the final report of a run: the one "done" produced, else why none ran.
76// undefined for a run that did no batch work.
77export function runLine(w: RunWork | undefined): string | undefined {
78 if (w === undefined || (!w.touched && w.line === undefined)) return undefined
79 if (w.line !== undefined) return w.line
80 return notUpdated(w.ready ? 'batch awaits /flow push' : 'nothing pushed')
81}
82hooks/testfail.ts 150 lines1// Failing tests under test_slot: which tests failed, and which passed on a rerun of the same tree (flaky). Pure
2// helpers; the plugin keeps the state in an atom and logs the events.
3import type { AgentInfo } from 'claude-code'
4import type { Session } from '../types'
5import { findWorktree } from './state'
6
7// A failed run: its test names ([] when it gave none) and the tree it ran on (undefined when unknown).
8export type FailedRun = { names: string[]; tree?: string }
9export type TestFails = {
10 // agent key + label -> its last failed run; a string[] is state from before trees were kept (unknown tree)
11 last: Record<string, FailedRun | string[]>
12 // agent key -> flaky test names seen during its run
13 flaky: Record<string, string[]>
14}
15export const NO_FAILS: TestFails = { last: {}, flaky: {} }
16
17const MAX_KEPT = 50
18const cleanNames = (names: unknown): string[] =>
19 Array.isArray(names) ? [...new Set(names.filter((n): n is string => typeof n === 'string').map(n => n.trim()).filter(Boolean))] : []
20const slotKey = (agent: string, label: string): string => `${agent}\u0000${label}`
21const cleanTree = (tree: unknown): string | undefined => typeof tree === 'string' && tree.trim() !== '' ? tree.trim() : undefined
22
23// Persisted runs come in two shapes; trust neither blindly.
24function failedRun(v: unknown): FailedRun {
25 if (Array.isArray(v)) return { names: cleanNames(v) }
26 const o = v !== null && typeof v === 'object' ? v as Record<string, unknown> : {}
27 const tree = cleanTree(o.tree)
28 return { names: cleanNames(o.names), ...(tree !== undefined && { tree }) }
29}
30
31// Two tree ids name the same tree: equal, or a short and a full sha of the same commit.
32function sameTree(a: string, b: string): boolean {
33 if (a === b) return true
34 const sha = /^[0-9a-f]{7,40}$/i
35 return sha.test(a) && sha.test(b) && (a.toLowerCase().startsWith(b.toLowerCase()) || b.toLowerCase().startsWith(a.toLowerCase()))
36}
37const short = (tree: string | undefined): string => tree === undefined ? 'unknown' : tree.replace(/^([0-9a-f]{7})[0-9a-f]*/i, '$1')
38
39// Whether a release needs the run's tree: a fail, or a pass with a fail on record to compare against.
40export function needsTree(state: TestFails, agent: string, label: string, result: unknown): boolean {
41 return result === 'fail' || (result === 'pass' && slotKey(agent, label) in state.last)
42}
43
44export type ReleaseNote = { state: TestFails; answer: string; event?: { kind: 'tests-failed' | 'flaky'; text: string } }
45
46// What a test_slot "release" with a result means: the answer for the agent, the log event, the new state. A pass
47// after a fail is flaky only when both runs were on the same known tree; a pass on another tree is a fix.
48export function noteRelease(state: TestFails, agent: string, label: string, result: unknown, failed: unknown, tree?: string): ReleaseNote {
49 const k = slotKey(agent, label)
50 const names = cleanNames(failed)
51 const now = cleanTree(tree)
52 if (result === 'fail') {
53 const run: FailedRun = { names, ...(now !== undefined && { tree: now }) }
54 const last = { ...Object.fromEntries(Object.entries(state.last).slice(-MAX_KEPT)), [k]: run }
55 const text = names.length ? `${label}: failed: ${names.join(', ')}` : `${label}: fail (names not given)`
56 const answer = names.length
57 ? `Failing tests recorded: ${names.join(', ')}.`
58 : 'No failing test names given: put the exact names of the failing tests (from the output) in your report.'
59 return { state: { ...state, last }, answer, event: { kind: 'tests-failed', text } }
60 }
61 if (result === 'pass' && k in state.last) {
62 const was = failedRun(state.last[k])
63 const { [k]: _gone, ...rest } = state.last
64 if (was.tree === undefined || now === undefined || !sameTree(was.tree, now)) {
65 const answer = was.tree === undefined || now === undefined
66 ? 'Passed after a fail, but the tree of a run is unknown: not counted as flaky.'
67 : `Passed on a different tree than the failure (${short(was.tree)} → ${short(now)}): a fix, not flaky.`
68 return { state: { ...state, last: rest }, answer }
69 }
70 const flaky = { ...state.flaky, [agent]: [...new Set([...(state.flaky[agent] ?? []), ...was.names])] }
71 const list = was.names.length ? was.names.join(', ') : 'an unnamed test'
72 return {
73 state: { last: rest, flaky },
74 answer: `flaky: ${list} (failed, passed on rerun): name it in your report as flaky: <test>.`,
75 event: { kind: 'flaky', text: `${label}: flaky: ${list}` },
76 }
77 }
78 return { state, answer: '' }
79}
80
81export type CallerDirIo = {
82 // The terminal sessions on record, by name.
83 sessions: () => Promise<Record<string, Session>>
84 agents: () => Promise<AgentInfo[]>
85 exec: (argv: string[]) => Promise<{ exitCode: number; stdout: string; stderr: string }>
86 cwd: () => Promise<string | undefined>
87}
88
89// The caller's own worktree, else the session's directory. A relayed call (`session:<name>`) uses that session's
90// recorded worktree; the lookup is here, not in register.tsx, because the plugin directory flagged a `$` helper
91// returning `s?.worktree` (MOD_CAPABILITY_USE_NOT_PLAIN).
92export async function callerDir(io: CallerDirIo, agentId: string | undefined): Promise<string | undefined> {
93 let dir: string | undefined
94 let mine: string | undefined
95 if (agentId !== undefined && agentId.startsWith('session:')) {
96 const all = await io.sessions()
97 const named = all[agentId.slice('session:'.length)]
98 if (named !== undefined) mine = named.worktree
99 }
100 if (mine !== undefined) dir = mine
101 else if (agentId !== undefined) {
102 const me = (await io.agents()).find(a => a.id === agentId)
103 const wt = await io.exec(['git', 'worktree', 'list', '--porcelain']).catch(() => undefined)
104 if (me !== undefined && wt?.exitCode === 0) dir = findWorktree(wt.stdout, me.id, `flow/${me.name ?? me.id}`)?.path
105 }
106 dir ??= await io.cwd().catch(() => undefined)
107 return dir
108}
109
110// FNV-1a: cheap, and enough to tell two uncommitted diffs apart.
111function hash(text: string): string {
112 let h = 0x811c9dc5
113 for (let i = 0; i < text.length; i++) h = Math.imul(h ^ text.charCodeAt(i), 0x01000193)
114 return (h >>> 0).toString(16).padStart(8, '0')
115}
116
117// The tree a run was on: the given sha, else the caller's HEAD, plus a hash of the uncommitted diff when the
118// worktree is dirty (an uncommitted fix is another tree). undefined when it cannot be worked out.
119export async function runTree(io: Partial<CallerDirIo>, agentId: string | undefined, sha: unknown): Promise<string | undefined> {
120 const given = cleanTree(sha)
121 if (given !== undefined) return given
122 const { sessions, agents, exec, cwd } = io
123 if (sessions === undefined || agents === undefined || exec === undefined || cwd === undefined) return undefined
124 try {
125 const dir = await callerDir({ sessions, agents, exec, cwd }, agentId)
126 const git = (...args: string[]) => exec(['git', ...(dir === undefined ? [] : ['-C', dir]), ...args])
127 const head = await git('rev-parse', 'HEAD')
128 if (head.exitCode !== 0 || head.stdout.trim() === '') return undefined
129 const status = await git('status', '--porcelain', '--untracked-files=no')
130 if (status.exitCode !== 0) return undefined
131 if (status.stdout.trim() === '') return head.stdout.trim()
132 const diff = await git('diff', 'HEAD')
133 return diff.exitCode === 0 ? `${head.stdout.trim()}+${hash(diff.stdout)}` : undefined
134 } catch {
135 return undefined
136 }
137}
138
139// The reviewer's report with "| flaky: a, b" appended for the names it does not mention yet.
140export function withFlaky(report: string, flaky: string[] | undefined): string {
141 const names = (flaky ?? []).filter(n => !report.includes(n))
142 return names.length === 0 ? report : `${report} | flaky: ${names.join(', ')}`
143}
144
145// The reason of a "back" with the failing tests named.
146export function withFailed(reason: string, failed: unknown): string {
147 const names = cleanNames(failed)
148 return names.length === 0 ? reason : `${reason} | failed: ${names.join(', ')}`
149}
150hooks/clean.ts 689 lines1import type { HandoffRecord, Leftovers, LogEvent, Session } from '../types'
2import { sessionKey, sessionLive } from './sessions'
3
4// Which leftover worktrees and local branches of finished agents can go. Pure: register.tsx runs
5// git and gh, hands the parsed answers here, and removes what comes back in `remove`.
6// Only clean work that is on the base, in a merged PR, or pushed with its PR closed is removed;
7// uncommitted, unpushed, locked and live work is listed for a person, never touched.
8
9export type Worktree = {
10 path: string
11 head?: string
12 // Short name, without refs/heads/; absent on a detached HEAD.
13 branch?: string
14 // The lock reason ('' when locked without one); absent when not locked.
15 locked?: string
16 // The directory is gone; `git worktree prune` drops the entry.
17 prunable: boolean
18}
19
20// `git worktree list --porcelain`, the main checkout first; bare entries are skipped.
21export function parsePorcelain(text: string): Worktree[] {
22 const out: Worktree[] = []
23 for (const block of text.split(/\n\n+/)) {
24 const lines = block.split('\n')
25 if (lines.includes('bare')) continue
26 const get = (k: string) => {
27 const l = lines.find(x => x === k || x.startsWith(`${k} `))
28 return l === undefined ? undefined : l.slice(k.length + 1)
29 }
30 const path = get('worktree')
31 if (path === undefined || path === '') continue
32 const branch = get('branch')?.replace(/^refs\/heads\//, '')
33 const locked = get('locked')
34 out.push({
35 path,
36 ...(get('HEAD') && { head: get('HEAD') }),
37 ...(branch && { branch }),
38 ...(locked !== undefined && { locked }),
39 prunable: get('prunable') !== undefined,
40 })
41 }
42 return out
43}
44
45// Untracked links to the plugin type definitions a worker makes for tsc; never work.
46const TYPE_LINKS = new Set(['types', 'types/', '.claude-plugin/types', '.claude-plugin/types/'])
47
48// The files `git status --porcelain` names, minus the type-definition links.
49export function dirtyFiles(status: string): string[] {
50 return status.split('\n').filter(l => l.trim() !== '')
51 .filter(l => !(l.startsWith('?? ') && TYPE_LINKS.has(l.slice(3).trim())))
52 .map(l => l.slice(3).trim())
53}
54
55// An agent that may still use its worktree: running, waiting, or idle between turns.
56export const isLive = (status: string): boolean => ['pending', 'running', 'waiting', 'idle'].includes(status)
57
58// The type-link paths `git status` lists as untracked: the only files apply deletes itself so a
59// plain `git worktree remove` goes through. Exactly the ignored ones, nothing else.
60export function typeLinks(status: string): string[] {
61 return status.split('\n').filter(l => l.startsWith('?? ') && TYPE_LINKS.has(l.slice(3).trim()))
62 .map(l => l.slice(3).trim().replace(/\/$/, ''))
63}
64
65export type PrRow = { number: number; headRefName: string; headRefOid: string; state: string }
66export type RosterEntry = { id: string; name?: string; live: boolean; cwd?: string }
67
68export type CleanInputs = {
69 main: string
70 base: string
71 worktrees: Worktree[]
72 // `git status --porcelain` per worktree path; absent when it could not be read.
73 status: Record<string, string>
74 // Local branches and their tips.
75 branches: Record<string, string>
76 // Shas known to be ancestors of origin/<base>.
77 onBase: Set<string>
78 // origin/<branch> tips.
79 remote: Record<string, string>
80 // undefined: gh failed, ancestry only.
81 prs?: PrRow[]
82 // "a b": a is an ancestor of b (b a sha or origin/<branch>), as asked by ancestryQueries.
83 ancestry: Set<string>
84 roster: RosterEntry[]
85 // Pids from lock reasons that no longer run.
86 deadPids?: Set<number>
87 // Worktree paths a handoff record keeps for a successor not spawned yet.
88 waiting?: Set<string>
89 // sha -> the commits (short sha + subject, origin/<base>..sha) whose whole change from the merge
90 // base is already on origin/<base>, file for file; see containedCandidates.
91 contained?: Record<string, string[]>
92 // The pid of the Claude process running this plugin; absent when it could not be told. A lock
93 // that names it was made in this session, so $.agent.list() knows its agent.
94 ownPid?: number
95 // The pid of the plugin's process and its ancestors, up to the Claude process: the plugin's
96 // process runner need not be a direct child of Claude, so a lock may name any of them.
97 ownPids?: Set<number>
98 // Worktrees whose lock file is older than 10 minutes; a younger or unaged lock may belong to an
99 // agent that is still starting and not yet in the roster.
100 oldLocks?: Set<string>
101 // Branches of best-of-N arms that lost (an `arm-lost` event, hooks/bestof.ts): with a closed PR and pushed they are safe like a merged one.
102 lost?: Set<string>
103 // Worktrees restoreWorktree made again in the last RESTORED_MS: their owner is on its way back to them.
104 restored?: Set<string>
105 // What flow knows it made outside .claude/worktrees/ (a terminal host's workspace dir): every session's
106 // worktree and hostWorktree, and the names of its sessions and spawned agents (for mgr-<name> and reviewer-<n>).
107 known?: { paths: Set<string>; names: Set<string> }
108}
109
110export type Kept = { kind: 'worktree' | 'branch'; name: string; reason: string; needsLook: boolean }
111export type Sweep = {
112 remove: { worktrees: string[]; branches: string[] }
113 // Locked worktrees whose lock belongs to an agent that ended: unlocked before removal.
114 unlock: string[]
115 keep: Kept[]
116 // Type links to delete before the plain remove, per worktree path that is in remove.
117 links: Record<string, string[]>
118 // Unpushed commits dropped because a merged PR of the branch family already holds their content.
119 dropped: { kind: 'worktree' | 'branch'; name: string; commits: string[] }[]
120}
121
122// A linked worktree flow made, wherever it lives: under .claude/worktrees/, on a flow/ branch, a session's
123// recorded worktree or host worktree, or a detached mgr-<name> / reviewer-<n> whose name flow knows. Anything
124// else is the person's own and is never listed or touched.
125export function linked(i: Pick<CleanInputs, 'main' | 'known'>, w: Worktree): boolean {
126 if (w.path === i.main) return false
127 if (w.path.startsWith(`${i.main.replace(/\/+$/, '')}/.claude/worktrees/`)) return true
128 if (w.branch?.startsWith('flow/') === true) return true
129 if (i.known?.paths.has(w.path) === true) return true
130 if (w.branch !== undefined) return false
131 const leaf = w.path.replace(/\/+$/, '').split('/').pop() ?? ''
132 const mgr = /^mgr-(.+)$/.exec(leaf)?.[1]
133 if (mgr !== undefined) return i.known?.names.has(mgr) === true
134 return /^reviewer-\d+$/.test(leaf) && i.known?.names.has(leaf) === true
135}
136
137// flow/x and flow/x-2 are one line of work: a continuation or rebase reuses the name with a suffix.
138const family = (b: string) => b.replace(/-\d+$/, '')
139
140const mergedFamily = (i: Pick<CleanInputs, 'prs'>, branch: string) =>
141 (i.prs ?? []).filter(p => p.state === 'MERGED' && family(p.headRefName) === family(branch))
142
143// Worktrees whose handoff record keeps them for a successor: not taken, not continued, and the
144// branch has no merged PR (the work was complete after all, so nobody will come).
145export function waitingPaths(
146 hs: { branch: string; worktree?: string; takenBy?: string; at: number }[],
147 continued: { branch?: string; ts: string }[],
148 prs: PrRow[] | undefined,
149): Set<string> {
150 return new Set(hs.filter(h => h.worktree !== undefined && h.takenBy === undefined
151 && !continued.some(l => l.branch === h.branch && Date.parse(l.ts) >= h.at)
152 && !(prs ?? []).some(p => p.state === 'MERGED' && p.headRefName === h.branch)).map(h => h.worktree!))
153}
154
155// The shas register.tsx checks for content equivalence: tips not on the base whose branch family
156// has a merged PR. It answers with `contained` (every file the commits changed since the merge
157// base has the same tree entry on origin/<base>, so nothing is lost), which landed() trusts.
158export function containedCandidates(i: Omit<CleanInputs, 'ancestry'>): string[] {
159 const out = new Set<string>()
160 const ask = (sha: string | undefined, branch: string | undefined) => {
161 if (sha === undefined || branch === undefined || i.onBase.has(sha)) return
162 if (mergedFamily(i, branch).length > 0) out.add(sha)
163 }
164 for (const w of i.worktrees) if (linked(i, w) && !w.prunable) ask(w.head, w.branch)
165 for (const [b, sha] of Object.entries(i.branches)) ask(sha, b)
166 return [...out]
167}
168
169const merged = (i: Pick<CleanInputs, 'prs'>, branch?: string) =>
170 (i.prs ?? []).filter(p => p.state === 'MERGED' && (branch === undefined || p.headRefName === branch))
171
172// The pairs ancestry needs beyond onBase, as "a b": a sha against a merged PR head of its branch,
173// and against origin/<branch>. register.tsx answers each with `git merge-base --is-ancestor`.
174export function ancestryQueries(i: Omit<CleanInputs, 'ancestry'>): string[] {
175 const out = new Set<string>()
176 const ask = (sha: string | undefined, branch: string | undefined) => {
177 if (sha === undefined || i.onBase.has(sha)) return
178 if (branch === undefined) return
179 for (const p of merged(i, branch)) if (p.headRefOid && p.headRefOid !== sha) out.add(`${sha} ${p.headRefOid}`)
180 if (i.remote[branch] !== undefined && i.remote[branch] !== sha) out.add(`${sha} origin/${branch}`)
181 }
182 for (const w of i.worktrees) if (linked(i, w) && !w.prunable) ask(w.head, w.branch)
183 for (const [b, sha] of Object.entries(i.branches)) ask(sha, b)
184 return [...out]
185}
186
187type Verdict = { ok: true; dropped?: string[] } | { ok: false; reason: string; needsLook: boolean }
188
189// Whether a commit's work is safe to drop: on the base, in a merged PR, or (worktrees only)
190// pushed with a closed PR.
191function landed(i: CleanInputs, sha: string, branch: string | undefined, closedOk: boolean): Verdict {
192 if (i.onBase.has(sha)) return { ok: true }
193 if (merged(i).some(p => p.headRefOid === sha)) return { ok: true }
194 if (branch !== undefined && merged(i, branch).some(p => i.ancestry.has(`${sha} ${p.headRefOid}`))) return { ok: true }
195 const same = i.contained?.[sha]
196 if (branch !== undefined && same !== undefined && mergedFamily(i, branch).length > 0) {
197 return same.length > 0 ? { ok: true, dropped: same } : { ok: true }
198 }
199 const pushed = branch !== undefined && (i.remote[branch] === sha || i.ancestry.has(`${sha} origin/${branch}`))
200 const prs = branch === undefined ? [] : (i.prs ?? []).filter(p => p.headRefName === branch)
201 const closed = prs.find(p => p.state === 'CLOSED')
202 if (closedOk && pushed && closed !== undefined) return { ok: true }
203 if (closed !== undefined) return { ok: false, reason: `PR #${closed.number} closed without merging${pushed ? ', pushed' : ''}`, needsLook: true }
204 if (branch === undefined) return { ok: false, reason: 'detached HEAD with commits not on the base', needsLook: true }
205 if (merged(i, branch).length > 0) return { ok: false, reason: 'unpushed commits after its PR was merged', needsLook: true }
206 if (pushed) return { ok: false, reason: 'pushed, not merged, no PR', needsLook: true }
207 return { ok: false, reason: 'unpushed commits', needsLook: true }
208}
209
210// The live agents' claim on a worktree: its path ends in agent-<id>, it is their cwd, or it is
211// on their branch flow/<name>.
212function liveOwner(i: CleanInputs, path: string | undefined, branch: string | undefined): RosterEntry | undefined {
213 return i.roster.find(a => a.live && (
214 (path !== undefined && (path.endsWith(`/agent-${a.id}`) || a.cwd === path || a.cwd?.startsWith(`${path}/`) === true)) ||
215 (branch !== undefined && a.name !== undefined && branch === `flow/${a.name}`)))
216}
217
218const LOCK_AGENT = /\bagent-([0-9a-zA-Z]+)\b/
219const LOCK_PID = /\bpid (\d+)\b/
220
221// A lock is stale when the agent it names ended in this session's roster, is unknown to it while
222// the lock is this session's own, or its process is gone.
223function staleLock(i: CleanInputs, reason: string, path: string): boolean {
224 const id = LOCK_AGENT.exec(reason)?.[1]
225 const pid = Number(LOCK_PID.exec(reason)?.[1] ?? NaN)
226 const agent = id === undefined ? undefined : i.roster.find(a => a.id === id || a.id === `agent-${id}`)
227 if (agent !== undefined) return !agent.live
228 // Same process, same session: the roster lists every agent it started, nested ones included
229 // (AgentInfo.parentId), so an agent missing from it is gone. Another pid proves nothing.
230 if (id !== undefined && Number.isInteger(pid) && (pid === i.ownPid || i.ownPids?.has(pid) === true)) return i.oldLocks?.has(path) === true
231 return id !== undefined && Number.isInteger(pid) && i.deadPids?.has(pid) === true
232}
233
234export function selectCleanup(i: CleanInputs): Sweep {
235 const sweep: Sweep = { remove: { worktrees: [], branches: [] }, unlock: [], keep: [], links: {}, dropped: [] }
236 const keep = (kind: Kept['kind'], name: string, reason: string, needsLook: boolean) =>
237 sweep.keep.push({ kind, name, reason, needsLook })
238 // Branches checked out in a worktree that stays (the main checkout included).
239 const held = new Map<string, string>()
240 for (const w of i.worktrees) {
241 if (!linked(i, w)) {
242 if (w.branch !== undefined) held.set(w.branch, w.path)
243 continue
244 }
245 const hold = () => { if (w.branch !== undefined) held.set(w.branch, w.path) }
246 if (w.prunable) {
247 sweep.remove.worktrees.push(w.path)
248 continue
249 }
250 const live = liveOwner(i, w.path, w.branch)
251 if (live !== undefined) {
252 keep('worktree', w.path, `in use by ${live.name ?? live.id}`, false)
253 hold()
254 continue
255 }
256 if (i.waiting?.has(w.path)) {
257 keep('worktree', w.path, 'waiting for its successor', false)
258 hold()
259 continue
260 }
261 if (i.restored?.has(w.path)) {
262 keep('worktree', w.path, 'made again for its owner', false)
263 hold()
264 continue
265 }
266 const open = w.branch === undefined ? undefined : (i.prs ?? []).find(p => p.state === 'OPEN' && p.headRefName === w.branch)
267 if (open !== undefined) {
268 keep('worktree', w.path, `PR #${open.number} is open`, false)
269 hold()
270 continue
271 }
272 const status = i.status[w.path]
273 if (status === undefined || w.head === undefined) {
274 keep('worktree', w.path, 'git status failed', true)
275 hold()
276 continue
277 }
278 const dirty = dirtyFiles(status)
279 if (dirty.length > 0) {
280 const named = dirty.slice(0, 3).join(', ') + (dirty.length > 3 ? ` and ${dirty.length - 3} more` : '')
281 keep('worktree', w.path, `uncommitted changes: ${named}`, true)
282 hold()
283 continue
284 }
285 const v = landed(i, w.head, w.branch, true)
286 if (!v.ok) {
287 keep('worktree', w.path, v.reason, v.needsLook)
288 hold()
289 continue
290 }
291 if (w.locked !== undefined) {
292 if (!staleLock(i, w.locked, w.path)) {
293 keep('worktree', w.path, 'locked', true)
294 hold()
295 continue
296 }
297 sweep.unlock.push(w.path)
298 }
299 if (v.dropped) sweep.dropped.push({ kind: 'worktree', name: w.path, commits: v.dropped })
300 const links = typeLinks(status)
301 if (links.length > 0) sweep.links[w.path] = links
302 sweep.remove.worktrees.push(w.path)
303 }
304
305 for (const [b, tip] of Object.entries(i.branches)) {
306 if (b === i.base) continue
307 const at = held.get(b)
308 if (at !== undefined) {
309 // The main checkout's branch is the person's own business.
310 if (at !== i.main) keep('branch', b, `checked out in ${at}`, false)
311 continue
312 }
313 const open = (i.prs ?? []).find(p => p.state === 'OPEN' && p.headRefName === b)
314 if (open !== undefined) {
315 keep('branch', b, `PR #${open.number} is open`, false)
316 continue
317 }
318 const live = liveOwner(i, undefined, b)
319 if (live !== undefined) {
320 keep('branch', b, `in use by ${live.name ?? live.id}`, false)
321 continue
322 }
323 const v = landed(i, tip, b, i.lost?.has(b) === true)
324 if (v.ok) {
325 sweep.remove.branches.push(b)
326 if (v.dropped) sweep.dropped.push({ kind: 'branch', name: b, commits: v.dropped })
327 }
328 else keep('branch', b, v.reason, v.needsLook)
329 }
330 return sweep
331}
332
333// The listing /flow clean and mcp__flow__clean answer with.
334export function sweepText(s: Sweep, opts: { applied: boolean; removed?: Sweep['remove']; failed?: Kept[]; note?: string; dryHint?: string }): string {
335 const lines: string[] = []
336 if (opts.note) lines.push(opts.note)
337 const gone = opts.applied ? opts.removed ?? s.remove : s.remove
338 const verb = opts.applied ? 'Removed' : 'Would remove'
339 if (gone.worktrees.length) lines.push(`${verb} ${gone.worktrees.length} worktree${gone.worktrees.length > 1 ? 's' : ''}:`, ...gone.worktrees.map(p => ` ${p}`))
340 if (gone.branches.length) lines.push(`${verb} ${gone.branches.length} branch${gone.branches.length > 1 ? 'es' : ''}:`, ...gone.branches.map(b => ` ${b}`))
341 if (!gone.worktrees.length && !gone.branches.length) lines.push(opts.applied ? 'Removed nothing.' : 'Nothing to remove.')
342 const lost = s.dropped.filter(d => gone[d.kind === 'worktree' ? 'worktrees' : 'branches'].includes(d.name))
343 if (lost.length) {
344 lines.push('Dropping unpushed commits whose content a merged PR already holds:')
345 for (const d of lost) lines.push(` ${d.kind} ${d.name}:`, ...d.commits.map(c => ` ${c}`))
346 }
347 const kept = [...(opts.failed ?? []), ...s.keep]
348 const look = kept.filter(k => k.needsLook)
349 const busy = kept.filter(k => !k.needsLook)
350 if (look.length) lines.push('Kept for a person to decide:', ...look.map(k => ` ${k.kind} ${k.name}: ${k.reason}`))
351 if (busy.length) lines.push('Kept, in use:', ...busy.map(k => ` ${k.kind} ${k.name}: ${k.reason}`))
352 if (!opts.applied && opts.dryHint && (s.remove.worktrees.length || s.remove.branches.length)) lines.push(opts.dryHint)
353 return lines.join('\n')
354}
355
356// The pane's and status's one line; undefined when there is nothing to say.
357export function leftoverLine(c: { worktrees: number; branches: number; needsLook: number }): string | undefined {
358 if (c.worktrees === 0 && c.branches === 0 && c.needsLook === 0) return undefined
359 // worktrees and branches are what a sweep would remove; needsLook is what it keeps for a person to decide.
360 const gone = [
361 ...(c.worktrees ? [`${c.worktrees} worktree${c.worktrees === 1 ? '' : 's'}`] : []),
362 ...(c.branches ? [`${c.branches} branch${c.branches === 1 ? '' : 'es'}`] : []),
363 ]
364 const parts = [
365 ...(gone.length ? [`${gone.join(' and ')} can be removed`] : []),
366 ...(c.needsLook ? [`${c.needsLook} hold${c.needsLook === 1 ? 's' : ''} work that isn't merged`] : []),
367 ]
368 return `Cleanup: ${parts.join(', ')}. /flow clean lists them`
369}
370
371// This session's pids: `start` and its ancestors up to and including the nearest `claude` process,
372// walked with `step` (undefined when ps fails). A chain that meets no claude within `max` steps,
373// pid 1 or a repeat is not trusted: empty. Stopping at the nearest one keeps a nested claude from
374// claiming the locks of the session whose shell it runs in.
375export async function ancestorPids(start: number, step: (pid: number) => Promise<{ ppid: number; comm: string } | undefined>, max = 12): Promise<Set<number>> {
376 const out = new Set<number>()
377 let pid: number | undefined = start
378 for (let n = 0; n < max && pid !== undefined && Number.isInteger(pid) && pid > 1 && !out.has(pid); n++) {
379 out.add(pid)
380 const r = await step(pid)
381 if (r === undefined) break
382 if (r.comm.trim().split('/').pop() === 'claude') return out
383 pid = r.ppid
384 }
385 return new Set()
386}
387
388// --- Sweep: reading git and gh, and removing what is safe ----------------------------------------
389// The engine handle `$` is never passed across an import, so the caller hands in these calls.
390
391export type CleanIo = {
392 // A process run; a failure to start throws.
393 exec: (argv: string[], timeoutMs: number) => Promise<{ exitCode: number; stdout: string; stderr: string }>
394 agents: () => Promise<{ id: string; status: string; name?: string }[]>
395 cwd: () => Promise<string | undefined>
396 handoffs: () => Promise<HandoffRecord[]>
397 sessions: () => Promise<Session[]>
398 log: () => Promise<LogEvent[]>
399 append: (event: Omit<LogEvent, 'ts'>) => Promise<void>
400 setLeftovers: (counts: Leftovers) => Promise<void>
401}
402
403export type CleanGathered = { inputs?: CleanInputs; notes: string[]; error?: string }
404
405// Everything selectCleanup needs, read once: one fetch, one gh call, then local git.
406async function gatherClean(io: CleanIo, base: string): Promise<CleanGathered> {
407 const run = async (argv: string[]) => {
408 try {
409 return await io.exec(argv, 60_000)
410 } catch (err) {
411 return { exitCode: 1, stdout: '', stderr: err instanceof Error ? err.message : String(err) }
412 }
413 }
414 const first = (r: { stderr: string }) => r.stderr.trim().split('\n')[0]?.slice(0, 200) || 'no output'
415 const notes: string[] = []
416 const fetched = await run(['git', 'fetch', 'origin', '--prune'])
417 if (fetched.exitCode !== 0) notes.push(`git fetch origin failed (${first(fetched)}): judged against the refs as they were.`)
418 const wl = await run(['git', 'worktree', 'list', '--porcelain'])
419 if (wl.exitCode !== 0) return { notes, error: `git worktree list failed: ${first(wl)}` }
420 const worktrees = parsePorcelain(wl.stdout)
421 const main = worktrees[0]?.path
422 if (main === undefined) return { notes, error: 'git worktree list gave no checkout.' }
423 const refs = async (prefix: string) => {
424 const r = await run(['git', 'for-each-ref', '--format=%(refname:short) %(objectname)', prefix])
425 const out: Record<string, string> = {}
426 for (const l of r.stdout.split('\n')) {
427 const [name, sha] = l.trim().split(' ')
428 if (name && sha) out[name] = sha
429 }
430 return out
431 }
432 const branches = await refs('refs/heads')
433 const remote: Record<string, string> = {}
434 for (const [name, sha] of Object.entries(await refs('refs/remotes/origin'))) {
435 if (name.startsWith('origin/') && name !== 'origin/HEAD') remote[name.slice('origin/'.length)] = sha
436 }
437 if (remote[base] === undefined) return { notes, error: `origin/${base} not found: nothing is judged without the base.` }
438 const onBase = new Set((await run(['git', 'for-each-ref', '--merged', `origin/${base}`, '--format=%(objectname)', 'refs/heads'])).stdout
439 .split('\n').map(l => l.trim()).filter(Boolean))
440 // Ended sessions' worktrees are flow's too, wherever the terminal host put them; a record written before
441 // hostWorktree existed names only its worktree. Names from the log reach worktrees whose record is gone.
442 const sessions = await io.sessions()
443 const known = { paths: new Set<string>(), names: new Set<string>() }
444 for (const s of sessions) {
445 known.names.add(s.name)
446 if (s.worktree !== main) known.paths.add(s.worktree)
447 if (s.hostWorktree !== undefined) known.paths.add(s.hostWorktree)
448 }
449 for (const l of await io.log()) if (l.event === 'spawn' && l.agent !== undefined) known.names.add(l.agent)
450 // Only flow's worktrees are read: the person's own are none of the sweep's business.
451 const ours = worktrees.filter(w => linked({ main, known }, w))
452 const status: Record<string, string> = {}
453 const deadPids = new Set<number>()
454 for (const w of ours) {
455 if (w.prunable) continue
456 const st = await run(['git', '-C', w.path, 'status', '--porcelain'])
457 if (st.exitCode === 0) status[w.path] = st.stdout
458 if (w.head !== undefined && !onBase.has(w.head)
459 && (await run(['git', 'merge-base', '--is-ancestor', w.head, `origin/${base}`])).exitCode === 0) onBase.add(w.head)
460 const pid = /\bpid (\d+)\b/.exec(w.locked ?? '')?.[1]
461 if (pid !== undefined && (await run(['ps', '-p', pid])).exitCode !== 0) deadPids.add(Number(pid))
462 }
463 let prs: PrRow[] | undefined
464 const gh = await run(['gh', 'pr', 'list', '--state', 'all', '--limit', '300', '--json', 'number,headRefName,headRefOid,state'])
465 try {
466 if (gh.exitCode !== 0) throw new Error(first(gh))
467 const parsed = JSON.parse(gh.stdout || '[]') as unknown
468 if (!Array.isArray(parsed)) throw new Error('unexpected gh output')
469 prs = parsed as PrRow[]
470 } catch (err) {
471 notes.push(`gh pr list failed (${err instanceof Error ? err.message : String(err)}): squash-merged work is not recognised, only what is on origin/${base}.`)
472 }
473 // A successor continuing in a handed-off worktree runs there; one not spawned yet may still claim it.
474 const hs = await io.handoffs()
475 const continued = (await io.log()).filter(l => l.event === 'continue')
476 const cwdOf = new Map(hs.filter(h => h.takenBy !== undefined && h.worktree !== undefined).map(h => [h.takenBy!, h.worktree!]))
477 const waiting = waitingPaths(hs, continued, prs)
478 const lost = new Set((await io.log()).filter(l => l.event === 'arm-lost' && l.branch !== undefined).map(l => l.branch!))
479 const roster = (await io.agents()).map(a => ({
480 id: a.id, live: isLive(a.status), ...(a.name !== undefined && { name: a.name }),
481 ...(a.name !== undefined && cwdOf.has(a.name) && { cwd: cwdOf.get(a.name) }),
482 }))
483 // The main session may itself run in a linked worktree: never pull the floor from under it.
484 const here = await io.cwd().catch(() => undefined)
485 if (here) roster.push({ id: 'main', live: true, name: 'the main session', cwd: here })
486 // A worker in another harness lives in its worktree until it is stopped or its terminal is gone. A
487 // session waiting for its next message (idle: a worker that went quiet, or the reviewer between
488 // batches) still holds it.
489 for (const s of sessions) {
490 const live = sessionLive(s)
491 roster.push({ id: sessionKey(s.name), live, name: s.name, cwd: s.worktree })
492 if (s.hostWorktree !== undefined) roster.push({ id: sessionKey(s.name), live, name: s.name, cwd: s.hostWorktree })
493 }
494 const partial: Omit<CleanInputs, 'ancestry'> = { main, base, worktrees, status, branches, onBase, remote, prs, roster, deadPids, waiting, lost, restored: restoredPaths(), known }
495 // Content equivalence for tips a merged PR of the branch family may have replaced (a rebase
496 // leaves the old commits behind): contained when every file they changed since the merge base
497 // has the very same tree entry on origin/<base>. Anything odd (quoted names, many files) is not.
498 const contained: Record<string, string[]> = {}
499 for (const sha of containedCandidates(partial)) {
500 const mb = (await run(['git', 'merge-base', sha, `origin/${base}`])).stdout.trim()
501 const diff = await run(['git', 'diff', '--name-only', '--no-renames', mb, sha])
502 const files = diff.stdout.split('\n').filter(Boolean)
503 if (!mb || diff.exitCode !== 0 || files.length > 200 || files.some(f => f.startsWith('"'))) continue
504 let same = true
505 for (const f of files) {
506 const [a, b] = await Promise.all([sha, `origin/${base}`].map(r => run(['git', 'ls-tree', r, '--', f])))
507 if (a!.exitCode !== 0 || b!.exitCode !== 0 || a!.stdout.trim() !== b!.stdout.trim()) { same = false; break }
508 }
509 if (!same) continue
510 const log = await run(['git', 'log', '--format=%h %s', `origin/${base}..${sha}`])
511 if (log.exitCode === 0) contained[sha] = log.stdout.split('\n').filter(Boolean)
512 }
513 partial.contained = contained
514 // The lock names the Claude process; the plugin's runner may sit below it, so the chain up to the
515 // nearest claude process counts as this session. Works with an empty roster (after a reload): an agent absent
516 // from it is judged by its lock's age. An unreadable chain means no lock is broken.
517 const own = await ancestorPids(Number((await run(['sh', '-c', 'echo $PPID'])).stdout.trim()), async pid => {
518 const r = await run(['ps', '-o', 'ppid=,comm=', '-p', String(pid)])
519 const m = /^\s*(\d+)\s+(.*)$/.exec(r.stdout.trim())
520 return r.exitCode === 0 && m ? { ppid: Number(m[1]), comm: m[2]! } : undefined
521 })
522 if (own.size > 0) {
523 partial.ownPids = own
524 // A fresh agent's worktree is locked before the roster lists it; only an old lock is judged.
525 // Unknown age (no admin dir, no lock file) counts as young.
526 const oldLocks = new Set<string>()
527 for (const w of ours) {
528 const lp = Number(/\bpid (\d+)\b/.exec(w.locked ?? '')?.[1] ?? NaN)
529 if (!own.has(lp)) continue
530 const dir = await run(['git', '-C', w.path, 'rev-parse', '--absolute-git-dir'])
531 if (dir.exitCode !== 0) continue
532 const old = await run(['find', `${dir.stdout.trim()}/locked`, '-mmin', '+10'])
533 if (old.exitCode === 0 && old.stdout.trim() !== '') oldLocks.add(w.path)
534 }
535 partial.oldLocks = oldLocks
536 }
537 const ancestry = new Set<string>()
538 for (const q of ancestryQueries(partial)) {
539 const [a, b] = q.split(' ')
540 if ((await run(['git', 'merge-base', '--is-ancestor', a!, b!])).exitCode === 0) ancestry.add(q)
541 }
542 return { inputs: { ...partial, ancestry }, notes }
543}
544
545// The occasional sweep's rate limit: due once OCCASIONAL_MS passed since the last one. Never due before a
546// first one was clocked (`last` undefined): the caller starts the clock then, as startup has just swept.
547export const OCCASIONAL_MS = 10 * 60_000
548export const occasionalDue = (last: number | undefined, now: number): boolean => last !== undefined && now - last >= OCCASIONAL_MS
549
550// One sweep at a time: the reviewer's `done`, a reviewer ending and /flow clean may meet.
551let sweepChain: Promise<unknown> = Promise.resolve()
552function exclusive<T>(fn: () => Promise<T>): Promise<T> {
553 const run = sweepChain.then(fn, fn)
554 sweepChain = run.catch(() => undefined)
555 return run
556}
557
558// A worktree made again stays out of the sweeps this long: the reviewer it was made for may still be
559// resuming (not live on the roster yet), and a fresh detached checkout of the base reads as safe to remove.
560const RESTORED_MS = 10 * 60_000
561const restoredAt = new Map<string, number>()
562function restoredPaths(now = Date.now()): Set<string> {
563 for (const [p, t] of restoredAt) if (now - t >= RESTORED_MS) restoredAt.delete(p)
564 return new Set(restoredAt.keys())
565}
566
567type Exec = (argv: string[], timeoutMs: number) => Promise<{ exitCode: number; stdout: string; stderr?: string }>
568
569// A reviewer's worktree that is gone from disk (a sweep or a person removed it), made again at the same
570// path the way launch makes one: detached at origin/<base>. The reviewer that runs or resumes there gets
571// its directory back instead of failing every command (#222). Under the sweep lock, so a sweep never sees
572// it half made and two callers never both add it; the second finds it there. A missing directory still
573// registered (locked by its agent, or not pruned yet) is unlocked and pruned first, else the add refuses.
574export async function restoreWorktree(exec: Exec, path: string, base: string): Promise<{ restored: boolean } | { error: string }> {
575 return exclusive(async () => {
576 const run = (argv: string[], ms = 60_000) => exec(argv, ms).catch((err: unknown) => ({ exitCode: 1, stdout: '', stderr: err instanceof Error ? err.message : String(err) }))
577 if ((await run(['test', '-d', path], 10_000)).exitCode === 0) return { restored: false }
578 await run(['git', 'worktree', 'unlock', path])
579 await run(['git', 'worktree', 'prune'])
580 // A failed fetch leaves origin/<base> as it was, which still makes a usable checkout.
581 await run(['git', 'fetch', 'origin', base], 120_000)
582 const r = await run(['git', 'worktree', 'add', '--detach', path, `origin/${base}`], 120_000)
583 if (r.exitCode !== 0) return { error: (r.stderr ?? '').trim().split('\n')[0]?.slice(0, 200) || r.stdout.trim().split('\n')[0]?.slice(0, 200) || 'git worktree add failed' }
584 restoredAt.set(path, Date.now())
585 return { restored: true }
586 })
587}
588
589// The worktree paths the terminal host manages for this repo; empty when it is not installed or not up.
590async function hostWorktrees(io: CleanIo, main: string): Promise<Set<string>> {
591 try {
592 const r = await io.exec(['orca', 'worktree', 'list', '--repo', `path:${main}`, '--json', '--limit', '1000'], 30_000)
593 if (r.exitCode !== 0) return new Set()
594 const rows = (JSON.parse(r.stdout) as { result?: { worktrees?: { path?: unknown }[] } }).result?.worktrees ?? []
595 return new Set(rows.map(w => w.path).filter((p): p is string => typeof p === 'string' && p !== main))
596 } catch {
597 return new Set()
598 }
599}
600
601const leftoverCounts = (s: Sweep, failed: Kept[] = [], applied = false): Leftovers => ({
602 worktrees: applied ? 0 : s.remove.worktrees.length,
603 branches: applied ? 0 : s.remove.branches.length,
604 needsLook: s.keep.filter(k => k.needsLook).length + failed.length,
605})
606
607// A sweep: the listing, and with apply the removal of what selectCleanup marked safe. A removal
608// that fails is kept with git's message; nothing is forced. `started` runs once it holds the lock.
609export async function sweep(io: CleanIo, base: string, apply: boolean, dryHint?: string, started?: () => void): Promise<string> {
610 return exclusive(async () => {
611 started?.()
612 const g = await gatherClean(io, base)
613 if (g.inputs === undefined) return [...g.notes, g.error ?? 'Cleanup failed.'].join('\n')
614 const s = selectCleanup(g.inputs)
615 const note = g.notes.join('\n') || undefined
616 if (!apply) {
617 await io.setLeftovers(leftoverCounts(s))
618 return sweepText(s, { applied: false, ...(note && { note }), ...(dryHint && { dryHint }) })
619 }
620 const git = async (argv: string[]) => {
621 try {
622 return await io.exec(['git', ...argv], 60_000)
623 } catch (err) {
624 return { exitCode: 1, stdout: '', stderr: err instanceof Error ? err.message : String(err) }
625 }
626 }
627 const failed: Kept[] = []
628 const removed: Sweep['remove'] = { worktrees: [], branches: [] }
629 const stuck = new Set<string>()
630 const byPath = new Map(g.inputs.worktrees.map(w => [w.path, w]))
631 const hosted = s.remove.worktrees.some(p => byPath.get(p)?.prunable === false) ? await hostWorktrees(io, g.inputs.main) : new Set<string>()
632 // Branches the terminal host's remove may have deleted along with their worktree.
633 const hostRemoved = new Set<string>()
634 for (const path of s.remove.worktrees) {
635 const w = byPath.get(path)
636 // A missing directory: prune drops the entry.
637 if (w?.prunable) { removed.worktrees.push(path); continue }
638 if (s.unlock.includes(path)) await git(['worktree', 'unlock', path])
639 // Untracked type links block a plain remove: unlink the links themselves (never followed). A real directory under that name is somebody's files: left for git to refuse.
640 for (const l of s.links[path] ?? []) {
641 const at = `${path}/${l}`
642 // `test -L` then `rm` (no trailing slash, no -r): removes the link, never its target.
643 const isLink = await io.exec(['test', '-L', at], 10_000).then(r => r.exitCode === 0, () => false)
644 if (isLink) await io.exec(['rm', '-f', '--', at], 10_000).catch(() => undefined)
645 }
646 // The terminal host keeps its own list beside git's: its remove drops both. It also deletes the checked-out
647 // branch, so it is used only when the sweep removes that branch too (it passed the same landed checks)
648 // or the worktree is detached; never --force. When it fails (the host is down), git removes it as before.
649 const branchGoes = w?.branch === undefined || s.remove.branches.includes(w.branch)
650 if (hosted.has(path) && branchGoes) {
651 const h = await io.exec(['orca', 'worktree', 'rm', '--worktree', `path:${path}`, '--json'], 120_000)
652 .catch(() => ({ exitCode: 1, stdout: '', stderr: '' }))
653 if (h.exitCode === 0 && !/"ok"\s*:\s*false/.test(h.stdout)) {
654 removed.worktrees.push(path)
655 if (w?.branch !== undefined) hostRemoved.add(w.branch)
656 continue
657 }
658 }
659 const r = await git(['worktree', 'remove', path])
660 if (r.exitCode === 0) removed.worktrees.push(path)
661 else {
662 failed.push({ kind: 'worktree', name: path, reason: `kept: ${r.stderr.trim().split('\n')[0] || 'git worktree remove failed'}`, needsLook: true })
663 if (w?.branch !== undefined) stuck.add(w.branch)
664 }
665 }
666 await git(['worktree', 'prune'])
667 for (const b of s.remove.branches) {
668 if (stuck.has(b)) {
669 failed.push({ kind: 'branch', name: b, reason: 'its worktree could not be removed', needsLook: true })
670 continue
671 }
672 const r = await git(['branch', '-D', b])
673 if (r.exitCode === 0) removed.branches.push(b)
674 else if (hostRemoved.has(b) && (await git(['show-ref', '--verify', '--quiet', `refs/heads/${b}`])).exitCode !== 0) removed.branches.push(b)
675 else failed.push({ kind: 'branch', name: b, reason: `kept: ${r.stderr.trim().split('\n')[0] || 'git branch -D failed'}`, needsLook: true })
676 }
677 await io.setLeftovers(leftoverCounts(s, failed, true))
678 if (removed.worktrees.length || removed.branches.length) {
679 await io.append({
680 event: 'clean', owner: 'main',
681 text: `removed ${[...removed.worktrees.map(p => `worktree ${p.split('/').pop()}`), ...removed.branches.map(b => `branch ${b}`)].join(', ')}`
682 + s.dropped.filter(d => (d.kind === 'worktree' ? removed.worktrees : removed.branches).includes(d.name))
683 .map(d => `; dropped unpushed in ${d.kind} ${d.name.split('/').pop()}: ${d.commits.join(' | ')}`).join(''),
684 })
685 }
686 return sweepText(s, { applied: true, removed, failed, ...(note && { note }) })
687 })
688}
689hooks/resume.ts 204 lines1// The /flow resume leftovers: unfinished flow work an earlier session left behind, and the
2// instructions that restart it. The engine handle `$` is never passed across an import, so the
3// caller hands in these calls.
4
5import type { Handover, LogEvent, Session } from '../types'
6import { LIVE } from './deliver'
7import { parsePorcelain } from './clean'
8import { ownerFor } from './state'
9
10export type ResumeIo = {
11 // A process run; a failure to start throws.
12 exec: (argv: string[], timeoutMs: number) => Promise<{ exitCode: number; stdout: string; stderr: string }>
13 agents: () => Promise<{ id: string; status: string; name?: string }[]>
14 sessions: () => Promise<Session[]>
15 log: () => Promise<LogEvent[]>
16 loadHandovers: () => Promise<Record<string, Handover>>
17 saveHandover: (h: Handover) => Promise<void>
18 // State on disk is best-effort: a failure goes to the UI log.
19 best: (what: string, fn: () => Promise<void>) => Promise<void>
20 // Adds the handovers read from disk to the atom; what the atom already holds wins.
21 mergeHandovers: (all: Record<string, Handover>) => Promise<void>
22}
23
24const OWNED = new Set([...LIVE, 'idle'])
25
26const resumeHead = (limit: number): string => [
27 'The user ran /flow resume. Unfinished flow work was found (below). Start flow managers for it with the Agent tool, without asking:',
28 '- One flow:manager per task, named resume-<slug>, run_in_background true, at most ' + limit + ' at a time; start the rest as each finishes. Items whose branch names share a manager prefix (flow/csv-export-endpoint and flow/csv-export-button) are one task.',
29 '- Each manager\'s prompt carries, for every item of its task: the branch, the PR number and URL, the PR description (including any ## Handoff section), and for a worktree its path. It carries the work on from there and must not redo work already merged into the base branch.',
30].join('\n')
31
32// Unfinished flow work left behind by an earlier session, as `/flow resume` lists it.
33export type Leftover = { key: string; branch?: string; kind: 'pr' | 'branch' | 'worktree'; line: string; detail: string; owner?: string }
34
35// `error` with items means GitHub was unavailable and the items come from the state dir alone.
36export type Gathered = { items: Leftover[]; skipped: Leftover[]; error?: string }
37
38// Handovers on disk that are not finished, as resume items. A handover whose PR GitHub shows as
39// merged counts as done: it is marked so in the atom and not restarted.
40export async function diskItems(io: ResumeIo, items: Leftover[], merged: { prs: Set<number>; branches: Set<string> } | undefined): Promise<void> {
41 const all = await io.loadHandovers()
42 const events = await io.log()
43 const hs = Object.values(all)
44 if (hs.length === 0) return
45 const finished = (h: Handover) => h.status === 'done' || (merged !== undefined && (merged.prs.has(h.pr) || merged.branches.has(h.branch)))
46 await io.best('restoring handovers', async () => {
47 for (const h of hs) {
48 if (h.status !== 'done' && finished(h)) {
49 all[String(h.pr)] = { ...h, status: 'done' }
50 await io.saveHandover(all[String(h.pr)] as Handover)
51 }
52 }
53 await io.mergeHandovers(all)
54 })
55 for (const h of hs) {
56 if (finished(h)) continue
57 const note = `Handover #${h.pr} is ${h.status}${h.status === 'returned' ? ` (${h.reason ?? 'no reason'})` : ''}, reported to ${h.reportTo}. Verified: ${h.verified} Pending: ${h.pending}` +
58 (h.status === 'awaiting' ? ` It awaits the user's /flow approve ${h.pr}; do not restart work on it.` : '') +
59 (h.status === 'ready' ? ' It is in a batch the reviewer built and checked, which awaits the user\'s /flow push; do not restart work on it.' : '')
60 const mate = items.find(i => i.key === h.branch)
61 if (mate !== undefined) {
62 mate.line += ` | handover ${h.status}`
63 mate.detail += `\n${note}`
64 } else {
65 items.push({ key: h.branch, branch: h.branch, kind: 'pr', line: `#${h.pr} ${h.branch}: handover ${h.status} — ${h.title}`, detail: `Branch ${h.branch}, PR #${h.pr}, title "${h.title}".\n${note}` })
66 }
67 const at = items.find(i => i.key === h.branch)
68 if (at !== undefined) at.owner = ownerFor(events, { pr: h.pr, branch: h.branch }) ?? h.reportTo
69 }
70 for (const i of items) {
71 if (i.owner === undefined && i.branch !== undefined) i.owner = ownerFor(events, { branch: i.branch })
72 }
73}
74
75// Finds what a restart leaves behind: flow/* PRs and pushed branches, and worktrees with
76// uncommitted or unpushed work. Any git or gh failure becomes one line, never a throw.
77export async function gatherLeftovers(io: ResumeIo, base: string, resumed: Set<string>): Promise<Gathered> {
78 const run = async (argv: string[]) => {
79 try {
80 return await io.exec(argv, 60_000)
81 } catch (err) {
82 return { exitCode: 1, stdout: '', stderr: err instanceof Error ? err.message : String(err) }
83 }
84 }
85 const fail = async (what: string, r: { stderr: string }): Promise<Gathered> => {
86 const items: Leftover[] = []
87 await diskItems(io, items, undefined)
88 return {
89 items: items.filter(i => !resumed.has(i.key)), skipped: items.filter(i => resumed.has(i.key)),
90 error: `Cannot look for unfinished work: ${what} failed: ${r.stderr.trim().split('\n')[0]?.slice(0, 200) || 'no output'}${items.length ? '. GitHub was unavailable: these come from the state dir only.' : ''}`,
91 }
92 }
93
94 const fetched = await run(['git', 'fetch', 'origin', '--prune'])
95 if (fetched.exitCode !== 0) return await fail('git fetch origin', fetched)
96 const open = await run(['gh', 'pr', 'list', '--state', 'open', '--json', 'number,title,headRefName,isDraft,url,body', '--limit', '100'])
97 if (open.exitCode !== 0) return await fail('gh pr list', open)
98 const all = await run(['gh', 'pr', 'list', '--state', 'all', '--json', 'number,headRefName,headRefOid,state', '--limit', '200'])
99 if (all.exitCode !== 0) return await fail('gh pr list', all)
100 const refs = await run(['git', 'for-each-ref', '--format=%(refname:short)', 'refs/remotes/origin/flow/'])
101 if (refs.exitCode !== 0) return await fail('git for-each-ref', refs)
102
103 type Pr = { number: number; title: string; headRefName: string; isDraft: boolean; url: string; body: string }
104 const prs = (JSON.parse(open.stdout || '[]') as Pr[]).filter(p => p.headRefName.startsWith('flow/'))
105 const ended = (JSON.parse(all.stdout || '[]') as { number?: number; headRefName: string; headRefOid?: string; state: string }[])
106 .filter(p => p.state !== 'OPEN')
107 const closed = new Set(ended.map(p => p.headRefName))
108 // A squash-merged branch is deleted on the remote, so its worktree looks unpushed: match by head too.
109 const endedHeads = new Set(ended.map(p => p.headRefOid).filter(Boolean))
110 const withPr = new Set(prs.map(p => p.headRefName))
111 const branches = refs.stdout.split('\n').map(l => l.trim().replace(/^origin\//, ''))
112 .filter(b => b.startsWith('flow/') && !withPr.has(b) && !closed.has(b))
113
114 // A live agent named like the branch owns it.
115 const liveAgents = (await io.agents()).filter(a => OWNED.has(a.status))
116 const owners = new Set(liveAgents.filter(a => a.name !== undefined).map(a => `flow/${a.name}`))
117 for (const s of await io.sessions()) if (s.status === 'running' || s.status === 'reported') owners.add(s.branch)
118 // A worktree path ends in agent-<agentId>: that covers a worker that has not renamed its branch, and the reviewer.
119 const liveIds = new Set(liveAgents.map(a => `agent-${a.id}`))
120
121 const items: Leftover[] = []
122 for (const p of prs) {
123 items.push({
124 key: p.headRefName, kind: 'pr',
125 line: `#${p.number} ${p.headRefName}${p.isDraft ? ' (draft)' : ''}: ${p.title} ${p.url}`,
126 detail: `Branch ${p.headRefName}, PR #${p.number} ${p.url}${p.isDraft ? ' (draft)' : ''}, title "${p.title}".\nPR description:\n${p.body.trim() || '(empty)'}`,
127 })
128 }
129 for (const b of branches) {
130 items.push({ key: b, kind: 'branch', line: `${b} (pushed, no PR)`, detail: `Branch ${b}, pushed, no PR yet.` })
131 }
132
133 const wt = await run(['git', 'worktree', 'list', '--porcelain'])
134 if (wt.exitCode === 0) {
135 for (const { path, branch } of parsePorcelain(wt.stdout)) {
136 if (!path.includes('/.claude/worktrees/')) continue
137 if (liveIds.has(path.split('/').pop() ?? '') || (branch !== undefined && closed.has(branch))) continue
138 const dirty = (await run(['git', '-C', path, 'status', '--porcelain'])).stdout.trim() !== ''
139 if (branch === undefined && !dirty) continue
140 let unpushed = ''
141 if (!dirty) {
142 const up = await run(['git', '-C', path, 'rev-parse', '--abbrev-ref', '@{u}'])
143 unpushed = (await run(up.exitCode === 0
144 ? ['git', '-C', path, 'log', '--oneline', '@{u}..']
145 : ['git', '-C', path, 'log', '--oneline', `origin/${base}..HEAD`])).stdout.trim()
146 }
147 if (!dirty && unpushed === '') continue
148 const head = (await run(['git', '-C', path, 'rev-parse', 'HEAD'])).stdout.trim()
149 if (endedHeads.has(head)) continue
150 if (!dirty && (await run(['git', '-C', path, 'branch', '-r', '--contains', 'HEAD'])).stdout.trim() !== '') continue
151 const what = dirty ? 'uncommitted changes' : `${unpushed.split('\n').length} unpushed commit(s)`
152 const mate = branch === undefined ? undefined : items.find(i => i.key === branch)
153 if (mate !== undefined) {
154 mate.line += ` | worktree ${path} (${what})`
155 mate.detail += `\nIts worktree: ${path} (${what}).`
156 continue
157 }
158 items.push({
159 key: path, branch, kind: 'worktree', line: `${path} on ${branch ?? 'detached HEAD'}: ${what}`,
160 detail: `Worktree ${path}, branch ${branch ?? 'detached HEAD'}: ${what}.`,
161 })
162 }
163 }
164
165 await diskItems(io, items, {
166 prs: new Set(ended.filter(p => p.state === 'MERGED' && p.number !== undefined).map(p => p.number as number)),
167 branches: new Set(ended.filter(p => p.state === 'MERGED').map(p => p.headRefName)),
168 })
169
170 const live = (i: Leftover) => owners.has(i.branch ?? i.key)
171 return {
172 items: items.filter(i => !live(i) && !resumed.has(i.key)),
173 skipped: items.filter(i => !live(i) && resumed.has(i.key)),
174 }
175}
176
177export type OwnerNotes = { path: string; text: string }
178
179export function resumeInstructions(items: Leftover[], limit: number, notes: Map<string, OwnerNotes> = new Map()): string {
180 const owners = [...new Set(items.map(i => i.owner).filter((o): o is string => o !== undefined))]
181 // Recorded owners: the state on disk says who ran each item and what the user told them.
182 const grouped = owners.length === 0 ? [] : [
183 '',
184 'Flow state on disk names the manager that owned each item. Items of one owner go to ONE manager. Its prompt tells it to read its notes first (mcp__flow__note with manager = the owner name below and no text), and carries the notes quoted here. A manager with notes but no item below is not restarted.',
185 ...owners.flatMap(o => {
186 const n = notes.get(o)
187 return [
188 '',
189 `Owner ${o}:`,
190 ...items.filter(i => i.owner === o).map(i => `- ${i.detail.replaceAll('\n', '\n ')}`),
191 n?.text ? `Notes (${n.path}):\n${n.text}` : 'Notes: none.',
192 ]
193 }),
194 ...(items.some(i => i.owner === undefined) ? ['', 'No recorded owner:', ...items.filter(i => i.owner === undefined).map(i => `- ${i.detail.replaceAll('\n', '\n ')}`)] : []),
195 ]
196 if (grouped.length) return [resumeHead(limit), ...grouped].join('\n')
197 return [
198 resumeHead(limit),
199 '',
200 'Found:',
201 ...items.map(i => `- ${i.detail.replaceAll('\n', '\n ')}`),
202 ].join('\n')
203}
204hooks/deliver.ts 153 lines1// Message delivery to agents. A message to an idle agent starts a new turn, and when the prompt
2// cache (5 minutes) has expired that turn re-writes the whole context at full price. So a running
3// agent gets a message at once, an idle one gets messages that arrive close together as ONE wake-up,
4// and a message that needs no action yet (a non-blocking ask) waits for the agent's next turn.
5// The queue is in memory: a plugin reload loses it.
6
7// The engine handle `$` is never passed across an import, so the caller hands in these calls.
8export type DeliverIo = {
9 // The agent's status; undefined when it is not on the roster; throws when the roster cannot be read.
10 status: (id: string) => Promise<string | undefined>
11 // Throws when the agent is gone or the session refuses the message.
12 send: (id: string, text: string) => Promise<void>
13 after: (ms: number, fn: () => void) => void
14 // The name to show in a fallback text; the id is used when absent.
15 name?: (id: string) => Promise<string | undefined>
16}
17
18export const ENDED = new Set(['completed', 'failed', 'killed'])
19export const LIVE = new Set(['pending', 'running', 'waiting'])
20
21// How long an idle agent's first queued message waits for company.
22export const WINDOW_MS = 8_000
23// The longest a held message waits when nothing else wakes the agent.
24export const HOLD_CAP_MS = 600_000
25// How long a queue held for a reviewer's message waits if that message never lands.
26export const REVIEWER_HOLD_MS = 60_000
27
28export type DeliverOptions = {
29 // Flush the queue with this text at once, even if the agent is idle.
30 urgent?: boolean
31 // Do not wake an idle agent for this text: wait for the next delivery, its next turn or the cap.
32 held?: boolean
33 // Where the text goes when the agent has ended by the time it is flushed (default: main).
34 onGone?: (text: string) => void | Promise<void>
35}
36
37type Item = { text: string; held: boolean; onGone?: DeliverOptions['onGone'] }
38// refused: a send of this queue was refused while the agent was not ended; the next cap flush is final.
39type Queue = { items: Item[]; windowMs: number; generation: number; refused?: boolean }
40
41const queues = new Map<string, Queue>()
42let generation = 0
43let toMain: (text: string) => void = () => undefined
44
45export const resetDelivery = (main: (text: string) => void): void => {
46 queues.clear()
47 toMain = main
48}
49
50// The joined text of the queue: arrival order, identical texts once, a blank line between.
51const joined = (items: Item[]): string => [...new Set(items.map(i => i.text))].join('\n\n')
52
53// An unreadable roster is not an ended agent: 'unknown' is sent to now, and the send says if it is gone.
54const statusOf = (io: DeliverIo, id: string): Promise<string | undefined> => io.status(id).catch(() => 'unknown')
55
56// Send a text now; false when the agent is gone or the send fails.
57const sendNow = (io: DeliverIo, id: string, text: string): Promise<boolean> =>
58 io.send(id, text).then(() => true, () => false)
59
60// The agent is gone, or kept refusing: each item goes to its own fallback, else to main with the target named.
61async function gone(io: DeliverIo, id: string, items: Item[], why: 'ended' | 'refused' = 'ended'): Promise<void> {
62 const name = (await io.name?.(id).catch(() => undefined)) ?? id
63 for (const i of items) {
64 if (i.onGone !== undefined) await i.onGone(i.text)
65 else toMain(why === 'ended' ? `${i.text} (${name} ended before this was delivered.)` : `${i.text} (This could not be delivered to ${name}: it kept refusing the message.)`)
66 }
67}
68
69// Put refused items back, ahead of anything queued since, as held: they go out on the agent's next
70// turn or delivery, and at the cap timer at the latest.
71function requeue(io: DeliverIo, id: string, items: Item[]): void {
72 const q = queues.get(id) ?? { items: [], windowMs: 0, generation: 0 }
73 queues.set(id, q)
74 const seen = new Set<string>()
75 q.items = [...items, ...q.items].filter(i => !seen.has(i.text) && seen.add(i.text))
76 for (const i of q.items) i.held = true
77 q.refused = true
78 arm(io, id, q, HOLD_CAP_MS)
79}
80
81// Send items as one message. A refusal by an agent that has not ended is not a gone agent (the host
82// refuses one waiting between turns): the items are re-queued, or fall back when this was the final
83// try. True when sent or re-queued; false when the items went to their fallbacks.
84async function sendItems(io: DeliverIo, id: string, items: Item[], final = false): Promise<boolean> {
85 if (await sendNow(io, id, joined(items))) return true
86 const status = await statusOf(io, id)
87 if (status === undefined || ENDED.has(status)) await gone(io, id, items)
88 else if (final) await gone(io, id, items, 'refused')
89 else {
90 requeue(io, id, items)
91 return true
92 }
93 return false
94}
95
96// Send everything queued for an agent as one message. A no-op when nothing is queued.
97// The cap timer passes capTimer: a queue that was refused before and is refused again falls back.
98export async function flushAgent(io: DeliverIo, id: string, capTimer = false): Promise<void> {
99 const q = queues.get(id)
100 if (q === undefined || q.items.length === 0) return
101 queues.delete(id)
102 const status = await statusOf(io, id)
103 if (status === undefined || ENDED.has(status)) await gone(io, id, q.items)
104 else await sendItems(io, id, q.items, capTimer && q.refused === true)
105}
106
107// Arm the flush timer: the window when something is not held, else the cap. A shorter deadline
108// replaces a longer one; the stale timer sees its generation changed and does nothing.
109function arm(io: DeliverIo, id: string, q: Queue, ms: number): void {
110 const g = ++generation
111 q.generation = g
112 q.windowMs = ms
113 io.after(ms, () => {
114 if (queues.get(id)?.generation === g) void flushAgent(io, id, true)
115 })
116}
117
118// True when the text was sent or is queued, also re-queued after a refusal (it goes out later); false when the
119// agent is gone. A caller that must know about a refusal reads it from its io (see sendWrapUp).
120export async function deliver(io: DeliverIo, id: string, text: string, opts: DeliverOptions = {}): Promise<boolean> {
121 const status = await statusOf(io, id)
122 if (status === undefined || ENDED.has(status)) {
123 // Not a live target: whatever was queued for it and this text fall back together.
124 const q = queues.get(id)
125 queues.delete(id)
126 await gone(io, id, [...(q?.items ?? []), { text, held: false, onGone: opts.onGone }])
127 return false
128 }
129 const q = queues.get(id)
130 const item: Item = { text, held: opts.held === true, onGone: opts.onGone }
131 if (status !== 'idle' || opts.urgent === true) {
132 // Running (or urgent): the agent takes everything queued for it now, with this text last.
133 queues.delete(id)
134 return sendItems(io, id, [...(q?.items ?? []), item])
135 }
136 const queue: Queue = q ?? { items: [], windowMs: 0, generation: 0 }
137 queues.set(id, queue)
138 if (!queue.items.some(i => i.text === text)) queue.items.push(item)
139 // A held text must not shorten the wait of a queue that already has a window running.
140 if (queue.generation === 0 || (!item.held && queue.windowMs > WINDOW_MS)) arm(io, id, queue, item.held ? HOLD_CAP_MS : WINDOW_MS)
141 return true
142}
143
144// A reviewer's message to this agent is about to land and will start its turn: what is queued waits
145// for that turn (flushAgent on its first step) instead of waking the agent a second time. The short
146// timer sends it anyway if the message never lands.
147export function holdForReviewer(io: DeliverIo, id: string): void {
148 const q = queues.get(id)
149 if (q === undefined || q.items.length === 0) return
150 for (const i of q.items) i.held = true
151 arm(io, id, q, REVIEWER_HOLD_MS)
152}
153hooks/cost.ts 309 lines1// The cost meter's pure part: one price table, the ledger arithmetic and the text of the report.
2//
3// Prices are ESTIMATES at Anthropic first-party API list prices, taken 2026-10-10. Subscription
4// plans are billed differently, so read the dollars as "what this would cost at list price".
5// To update: edit PRICES below (USD per million tokens) and nothing else; the ledger keeps tokens,
6// not dollars, so a changed table reprices history.
7
8import { localDate } from './release'
9import type { Bucket, Ledger, LedgerEntry, Role, Tokens } from '../types'
10
11export type Rates = { input: number; write5m: number; write1h: number; read: number; output: number }
12
13// Cache write 5m = 1.25x input, 1h = 2x input, cache read = 0.1x input, unless a model lists its own read price.
14function rates(input: number, output: number, read = input * 0.1): Rates {
15 return { input, write5m: input * 1.25, write1h: input * 2, read, output }
16}
17
18type Price = { rates: Rates; long?: { over: number; rates: Rates } }
19
20const PRICES: Record<string, Price> = {
21 'claude-opus-5-5': { rates: rates(4, 20, 0.2) },
22 'claude-opus-5': { rates: rates(5, 25) },
23 'claude-opus-4-8': { rates: rates(5, 25) },
24 'claude-opus-4-7': { rates: rates(5, 25) },
25 'claude-opus-4-6': { rates: rates(5, 25) },
26 'claude-sonnet-5-5': { rates: rates(2, 10, 0.2) },
27 'claude-sonnet-5': { rates: rates(2, 10, 0.2) },
28 'claude-sonnet-4-6': { rates: rates(3, 15) },
29 // Prompts over 100K tokens (input + cache write + cache read of one step) cost more.
30 'claude-haiku-5-5': { rates: rates(0.1, 0.5), long: { over: 100_000, rates: rates(0.5, 2.5) } },
31 'claude-haiku-4-5': { rates: rates(1, 5) },
32 'claude-fable-5-1': { rates: rates(10, 50, 0.25) },
33 'claude-fable-5': { rates: rates(10, 50) },
34}
35
36// An alias, or a version not in the table, is priced as the newest of its family.
37const FAMILIES: Record<string, string> = {
38 opus: 'claude-opus-5-5',
39 sonnet: 'claude-sonnet-5-5',
40 haiku: 'claude-haiku-5-5',
41 fable: 'claude-fable-5-1',
42}
43
44// The same normalisation as modelKey in register.tsx: `[1m]`, a date suffix and `-latest` do not change the price.
45export function normalizeModel(model: string): string {
46 return model.toLowerCase().replace(/\[1m\]/g, '').replace(/-latest$/, '').replace(/-\d{8}$/, '')
47}
48
49// The price of a model id: the exact id, else the longest known id it extends, else its family, else undefined.
50export function priceOf(model: string): Price | undefined {
51 const key = normalizeModel(model)
52 const exact = PRICES[key]
53 if (exact) return exact
54 const known = Object.keys(PRICES).filter(k => key.startsWith(`${k}-`)).sort((a, b) => b.length - a.length)[0]
55 if (known) return PRICES[known]
56 const family = Object.keys(FAMILIES).find(f => key.includes(f))
57 return family === undefined ? undefined : PRICES[FAMILIES[family]!]
58}
59
60export const ZERO: Tokens = { input: 0, write5m: 0, write1h: 0, read: 0, output: 0 }
61
62const add = (a: Tokens, b: Tokens): Tokens => ({
63 input: a.input + b.input, write5m: a.write5m + b.write5m, write1h: a.write1h + b.write1h, read: a.read + b.read, output: a.output + b.output,
64})
65const sum = (list: Tokens[]): Tokens => list.reduce(add, ZERO)
66const all = (t: Tokens): number => t.input + t.write5m + t.write1h + t.read + t.output
67const prompt = (t: Tokens): number => t.input + t.write5m + t.write1h + t.read
68
69const dollars = (t: Tokens, r: Rates): number =>
70 (t.input * r.input + t.write5m * r.write5m + t.write1h * r.write1h + t.read * r.read + t.output * r.output) / 1_000_000
71
72// The USD estimate of a bucket, or undefined when the model has no price (shown as "?", never as 0).
73export function costOf(model: string, b: Bucket): number | undefined {
74 const p = priceOf(model)
75 if (p === undefined) return undefined
76 if (p.long === undefined || b.long === undefined) return dollars(b, p.rates)
77 const base: Tokens = {
78 input: b.input - b.long.input, write5m: b.write5m - b.long.write5m, write1h: b.write1h - b.long.write1h,
79 read: b.read - b.long.read, output: b.output - b.long.output,
80 }
81 return dollars(base, p.rates) + dollars(b.long, p.long.rates)
82}
83
84// cache read / everything the prompts carried; undefined before any prompt.
85export function hitRate(t: Tokens): number | undefined {
86 return prompt(t) === 0 ? undefined : t.read / prompt(t)
87}
88
89const num = (v: unknown): number => (typeof v === 'number' && Number.isFinite(v) && v > 0 ? v : 0)
90
91// One step's usage as tokens; the cache write splits 5m/1h when the usage carries the breakdown, else all is 5m.
92export function stepTokens(usage: unknown): Tokens | undefined {
93 if (typeof usage !== 'object' || usage === null) return undefined
94 const u = usage as Record<string, unknown>
95 const bd = typeof u.cache_creation === 'object' && u.cache_creation !== null ? u.cache_creation as Record<string, unknown> : undefined
96 const total = num(u.cache_creation_input_tokens)
97 const write1h = bd === undefined ? 0 : num(bd.ephemeral_1h_input_tokens)
98 const write5m = bd !== undefined && bd.ephemeral_5m_input_tokens !== undefined ? num(bd.ephemeral_5m_input_tokens) : Math.max(0, total - write1h)
99 return { input: num(u.input_tokens), write5m, write1h, read: num(u.cache_read_input_tokens), output: num(u.output_tokens) }
100}
101
102export type Identity = Partial<Omit<LedgerEntry, 'models' | 'firstAt' | 'lastAt' | 'turns'>>
103
104const definedOnly = <T extends object>(o: T): Partial<T> => Object.fromEntries(Object.entries(o).filter(([, v]) => v !== undefined)) as Partial<T>
105
106// The ledger with one step added (a new object; the old one is untouched). A step with no tokens at all is skipped.
107export function addStep(ledger: Ledger, key: string, model: string, usage: unknown, who: Identity | undefined, now: number): Ledger {
108 const t = stepTokens(usage)
109 if (t === undefined || all(t) === 0) return ledger
110 const isMain = key.startsWith('main@')
111 const cur: LedgerEntry = ledger[key] ?? { role: isMain ? 'main' : 'other', name: isMain ? 'main' : key, models: {} }
112 const entry: LedgerEntry = { ...cur, ...(who ? definedOnly(who) : {}), firstAt: cur.firstAt ?? now, lastAt: now }
113 const b: Bucket = entry.models[model] ?? { ...ZERO }
114 const over = priceOf(model)?.long?.over
115 const long = over !== undefined && prompt(t) > over
116 const next: Bucket = { ...add(b, t), ...(long || b.long ? { long: add(b.long ?? ZERO, long ? t : ZERO) } : {}) }
117 return { ...ledger, [key]: { ...entry, models: { ...entry.models, [model]: next } } }
118}
119
120// The ledger with one completed turn counted. An agent with no row yet gets an empty one (no models,
121// so the cost block hides it until a step arrives and its tokens are counted).
122export function addTurn(ledger: Ledger, key: string, now: number): Ledger {
123 const isMain = key.startsWith('main@')
124 const cur: LedgerEntry = ledger[key] ?? { role: isMain ? 'main' : 'other', name: isMain ? 'main' : key, models: {} }
125 return { ...ledger, [key]: { ...cur, turns: (cur.turns ?? 0) + 1, firstAt: cur.firstAt ?? now, lastAt: now } }
126}
127
128// Identity recorded at spawn (or filled from the roster): sets the fields, keeps the tokens.
129export function setIdentity(ledger: Ledger, key: string, who: Identity & { role: Role; name: string }, now: number): Ledger {
130 const cur = ledger[key]
131 return { ...ledger, [key]: { models: {}, ...cur, ...definedOnly(who), firstAt: cur?.firstAt ?? now, lastAt: now } as LedgerEntry }
132}
133
134// The file's generation stamp lives under this top-level key. It is a string, so normalizeLedger (and an
135// older plugin's) drops it as a non-entry. A rebuild or the first save of a legacy file sets a new one.
136export const EPOCH_KEY = '__epoch'
137export function epochOf(raw: unknown): string {
138 const e = typeof raw === 'object' && raw !== null && !Array.isArray(raw) ? (raw as Record<string, unknown>)[EPOCH_KEY] : undefined
139 return typeof e === 'string' ? e : ''
140}
141
142// What came off disk: anything that is not a ledger entry is dropped.
143export function normalizeLedger(raw: unknown): Ledger {
144 if (typeof raw !== 'object' || raw === null || Array.isArray(raw)) return {}
145 const out: Ledger = {}
146 for (const [k, v] of Object.entries(raw)) {
147 if (typeof v !== 'object' || v === null) continue
148 const e = v as Record<string, unknown>
149 if (typeof e.name !== 'string' || typeof e.models !== 'object' || e.models === null) continue
150 out[k] = { ...(e as unknown as LedgerEntry), role: (['manager', 'worker', 'reviewer', 'main'] as const).find(r => r === e.role) ?? 'other' }
151 }
152 return out
153}
154
155// What changed between two views of the ledger, as a ledger: each changed entry keeps `after`'s identity and
156// times but carries only the added tokens and turns, so merging it onto the disk adds counts and never
157// replaces a real identity with a default.
158export function diffLedger(before: Ledger, after: Ledger): Ledger {
159 const out: Ledger = {}
160 const sub = (a: Tokens, b: Tokens | undefined): Tokens => ({
161 input: a.input - (b?.input ?? 0), write5m: a.write5m - (b?.write5m ?? 0), write1h: a.write1h - (b?.write1h ?? 0),
162 read: a.read - (b?.read ?? 0), output: a.output - (b?.output ?? 0),
163 })
164 const any = (t: Tokens): boolean => t.input !== 0 || t.write5m !== 0 || t.write1h !== 0 || t.read !== 0 || t.output !== 0
165 for (const [k, e] of Object.entries(after)) {
166 const o = before[k]
167 if (o === e) continue
168 const models: Record<string, Bucket> = {}
169 for (const [m, b] of Object.entries(e.models)) {
170 const d = sub(b, o?.models[m])
171 const long = b.long === undefined ? undefined : sub(b.long, o?.models[m]?.long)
172 if (any(d) || (long !== undefined && any(long))) models[m] = { ...d, ...(long !== undefined && any(long) ? { long } : {}) }
173 }
174 const { turns: _turns, ...rest } = e
175 const turns = (e.turns ?? 0) - (o?.turns ?? 0)
176 out[k] = { ...rest, models, ...(turns > 0 ? { turns } : {}) }
177 }
178 return out
179}
180
181// Both ledgers' tokens added (the file's history plus what this run counted before it was loaded).
182export function mergeLedgers(a: Ledger, b: Ledger): Ledger {
183 const out: Ledger = { ...a }
184 for (const [k, e] of Object.entries(b)) {
185 const o = out[k]
186 if (o === undefined) { out[k] = e; continue }
187 const models = { ...o.models }
188 for (const [m, bk] of Object.entries(e.models)) {
189 const x = models[m]
190 models[m] = x === undefined ? bk : { ...add(x, bk), ...(x.long || bk.long ? { long: add(x.long ?? ZERO, bk.long ?? ZERO) } : {}) }
191 }
192 out[k] = {
193 ...e, ...o, models,
194 ...((o.turns ?? 0) + (e.turns ?? 0) > 0 ? { turns: (o.turns ?? 0) + (e.turns ?? 0) } : {}),
195 ...(o.firstAt !== undefined || e.firstAt !== undefined ? { firstAt: Math.min(o.firstAt ?? Infinity, e.firstAt ?? Infinity) } : {}),
196 ...(o.lastAt !== undefined || e.lastAt !== undefined ? { lastAt: Math.max(o.lastAt ?? 0, e.lastAt ?? 0) } : {}),
197 }
198 }
199 return out
200}
201
202// The ledger file stays bounded: an entry not counted for 90 days goes, and so does one with no `lastAt`.
203export const KEEP_MS = 90 * 24 * 3600 * 1000
204export function pruneLedger(ledger: Ledger, now: number): Ledger {
205 const kept = Object.entries(ledger).filter(([, e]) => e.lastAt !== undefined && e.lastAt >= now - KEEP_MS)
206 return kept.length === Object.keys(ledger).length ? ledger : Object.fromEntries(kept)
207}
208
209// --- Totals ---
210
211export type Total = { tokens: Tokens; usd: number; unknown: boolean; turns: number }
212
213export function totalOf(entries: LedgerEntry[]): Total {
214 let usd = 0
215 let unknown = false
216 let turns = 0
217 const parts: Tokens[] = []
218 for (const e of entries) {
219 turns += e.turns ?? 0
220 for (const [m, b] of Object.entries(e.models)) {
221 parts.push(b)
222 const c = costOf(m, b)
223 if (c === undefined) unknown = true
224 else usd += c
225 }
226 }
227 return { tokens: sum(parts), usd, unknown, turns }
228}
229
230// A name without its successor suffix: `csv-export-2` is a successor of `csv-export`.
231export const baseName = (name: string): string => name.replace(/-\d+$/, '')
232
233// --- Text ---
234
235export function humanTokens(n: number): string {
236 if (n < 1000) return String(Math.round(n))
237 if (n < 1_000_000) return `${(n / 1000).toFixed(n < 100_000 ? 1 : 0).replace(/\.0$/, '')}k`
238 return `${(n / 1_000_000).toFixed(n < 100_000_000 ? 1 : 0).replace(/\.0$/, '')}M`
239}
240
241export function money(usd: number, unknown = false): string {
242 const s = usd < 0.1 && usd > 0 ? usd.toFixed(3) : usd.toFixed(2)
243 return unknown ? (usd > 0 ? `~$${s}+?` : '~$?') : `~$${s}`
244}
245
246const percent = (t: Tokens): string => {
247 const h = hitRate(t)
248 return h === undefined ? '-' : `${Math.round(h * 100)}%`
249}
250
251const tokenText = (t: Tokens): string =>
252 `${humanTokens(t.input)} in / ${humanTokens(t.write5m + t.write1h)} cache write / ${humanTokens(t.read)} cache read / ${humanTokens(t.output)} out, hit ${percent(t)}`
253
254// Turns and cache write per turn (the cost of each wake-up) show only once a turn was counted.
255const turnText = (t: Total): string =>
256 t.turns > 0 ? `, ${t.turns} turns, ~${humanTokens((t.tokens.write5m + t.tokens.write1h) / t.turns)} cache write/turn` : ''
257
258export const totalText = (t: Total): string => `${money(t.usd, t.unknown)} (tokens ${tokenText(t.tokens)}${turnText(t)})`
259
260// Appended to a reviewer's done report: the PR's workers' cost. Empty when they spent nothing.
261export function reportSuffix(t: Total): string {
262 if (all(t.tokens) === 0) return ''
263 return ` | cost: ${money(t.usd, t.unknown)} (tokens ${humanTokens(prompt(t.tokens))} in, ${humanTokens(t.tokens.output)} out, hit ${percent(t.tokens)})`
264}
265
266// The workers of a PR: those on its branch (a `-2` successor continues on the same branch).
267export const entriesOfBranch = (ledger: Ledger, branch: string): LedgerEntry[] =>
268 Object.values(ledger).filter(e => e.role === 'worker' && e.branch === branch)
269
270export const prCost = (ledger: Ledger, branch: string): Total => totalOf(entriesOfBranch(ledger, branch))
271
272// The block of `status`: one line per agent that took steps, then manager, PR, reviewer, main and session totals.
273// `scope`: this session started at `start` and has `live` agent ids in its roster. An entry is this
274// session's when its agent is live or was counted since the start; the older ones only reach the all-time line.
275export function costBlock(ledger: Ledger, prs: { pr: number; branch: string }[], otherSessions: boolean, scope: { start: number; live: Set<string> }): string[] {
276 const counted = Object.entries(ledger).filter(([, e]) => Object.keys(e.models).length > 0)
277 if (counted.length === 0) return []
278 const here = counted.filter(([k, e]) => scope.live.has(k) || (e.lastAt ?? 0) >= scope.start)
279 const entries = here.map(([, e]) => e)
280 const lines = ['Cost (estimates at API list prices):']
281 const order: Record<Role, number> = { main: 0, manager: 1, worker: 2, reviewer: 3, other: 4 }
282 for (const e of [...entries].sort((a, b) => order[a.role] - order[b.role] || a.name.localeCompare(b.name))) {
283 lines.push(` ${e.role} ${e.name} [${Object.keys(e.models).join(', ')}]: ${totalText(totalOf([e]))}`)
284 }
285 const ownerOf = (e: LedgerEntry): string | undefined => e.role === 'manager' ? baseName(e.name) : e.role === 'worker' && e.manager !== undefined ? baseName(e.manager) : undefined
286 for (const m of [...new Set(entries.map(ownerOf).filter((x): x is string => x !== undefined))].sort()) {
287 lines.push(` manager ${m} total (with its workers): ${totalText(totalOf(entries.filter(e => ownerOf(e) === m)))}`)
288 }
289 for (const p of [...prs].sort((a, b) => a.pr - b.pr)) {
290 const mine = entriesOfBranch(ledger, p.branch).filter(e => entries.includes(e) && Object.keys(e.models).length > 0)
291 if (mine.length > 0) lines.push(` PR #${p.pr} (${p.branch}) workers: ${totalText(totalOf(mine))}`)
292 }
293 const rev = entries.filter(e => e.role === 'reviewer')
294 if (rev.length > 0) lines.push(` reviewer total: ${totalText(totalOf(rev))}`)
295 const main = entries.filter(e => e.role === 'main')
296 if (main.length > 0) lines.push(` main total: ${totalText(totalOf(main))}`)
297 // Only once model routing has put a size on some entry; the rest is "unsized" (main, the reviewer, older entries; managers count under their size once main states one).
298 if (entries.some(e => e.size !== undefined)) {
299 const part = (label: string, of: LedgerEntry[]) => of.length === 0 ? [] : [`${label} ${money(totalOf(of).usd, totalOf(of).unknown)}`]
300 const by = [...['small', 'normal', 'large'].flatMap(s => part(s, entries.filter(e => e.size === s))), ...part('unsized', entries.filter(e => e.size === undefined))]
301 lines.push(` by size: ${by.join(', ')}`)
302 }
303 lines.push(` session total: ${totalText(totalOf(entries))}`)
304 const first = Math.min(...counted.map(([, e]) => e.firstAt ?? Infinity))
305 lines.push(` All time${Number.isFinite(first) ? ` (since ${localDate(first)})` : ''}: ${totalText(totalOf(counted.map(([, e]) => e)))}`)
306 if (otherSessions) lines.push(' Workers run in other harness sessions are not counted.')
307 return lines
308}
309