Context, rate-limit and git band above the prompt, plus the 70% context guard

Personal dotfiles managed with GNU Stow. Ansible handles provisioning on new machines.
Theme: Catppuccin Macchiato throughout.
Provisioning uses three mechanisms — know which applies before editing a package: stow (symlink, edits round-trip to git), materialized (copied once from a template by bootstrap-dirs.sh, then drifts silently — edit the template, not the live file), and sync-pushed (one-way push by sync-agent-rules.sh, live edits are invisible to git).
| Package | Stow target | Provisioning |
|---|---|---|
zsh/ | ~/.zshrc, ~/.zprofile, ~/.zsh/ | stow (autosuggestions via deja from Brewfile, replacing zsh-autosuggestions) |
starship/ | ~/.config/starship.toml | stow |
mise/ | ~/.config/mise/config.toml | stow — dev CLI + runtime pins; run mise install after restow |
nvim/ | ~/.config/nvim/ | stow |
tmux/ | ~/.tmux.conf, ~/.local/bin/tmux-cht | stow |
tmuxinator/ | ~/.config/tmuxinator/dotfiles.yml | stow |
kitty/ | ~/.config/kitty/ | stow |
git/ | ~/.gitconfig | stow |
jj/ | ~/.config/jj/config.toml | stow |
aerospace/ | ~/.aerospace.toml | stow (macOS tiling WM) — not in the stow line above; add when used |
mouseless/ | ~/Library/Application Support/Mouseless/configs/config.yaml | stow (macOS Mouseless app) — not in the stow line above; back up the live file before first stow mouseless, restart the app after |
sketchybar/ | ~/.config/sketchybar/ | stow (macOS status bar) — not in the stow line above; add when used; sketchybar --reload after edits |
i3/ | ~/.config/i3/config | Linux-only, applied via Ansible (not macOS stow) |
claude/ | ~/.claude/ | stow (partial) — including settings.json; skills/+agents/ mix dotfiles and llm-wiki sources |
opencode/ | ~/.config/opencode/ | partial — plugins/ stow; opencode.json materialized; agents//skills/ unmanaged |
codex/ | ~/.codex/ | no-op stub today — Codex is sync-pushed via sync-agent-rules.sh, not stowed |
pi/ | ~/.pi/ | stow (extensions only); ~/.pi/agent/ runtime state is unmanaged, except portable MCP entries sync-pushed to mcp.json |
herdr/ | ~/.config/herdr/config.toml | stow — not in the stow line above; back up the live file before first stow herdr; ~/.config/herdr/ logs/sockets/session-history are unmanaged runtime state; herdr server reload-config after edits |
launchd/ | ~/Library/LaunchAgents/ | stow — user LaunchAgents such as the Herdr→Sketchybar bridge |
# 1. Clone (submodules required — llm-wiki is bundled as a submodule)
git clone --recurse-submodules git@github.com:vietbui99/dotfiles.git ~/dotfiles
# 2. Install Homebrew
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
# 3. Install packages
cd ~/dotfiles && brew bundle
# 4. Create expected directories (uses a standalone ~/repos/llm-wiki clone if present)
./scripts/bootstrap-dirs.sh
# 5. Symlink configs
./scripts/restow.sh
# 6. Install dev CLIs + runtimes (go, node, neovim, ripgrep, jq, ...) from mise.
# The list lives in mise/.config/mise/config.toml, stowed in step 5.
# Upgrade them with `mise up` — not `brew upgrade`.
mise install
# 7. Sync AI tool rules (AGENTS.md + MCP servers)
./scripts/sync-agent-rules.sh
Covers: base packages, Rust toolchain, modern CLI tools, zsh, starship, tmux, neovim. Kitty only on macOS/desktop.
# Local machine
ansible-playbook ansible/site.yml --limit localhost
# Remote Debian dev server
ansible-playbook ansible/site.yml --limit dev_debian -i ansible/inventory/hosts.yml
# Remote RedHat admin server
ansible-playbook ansible/site.yml --limit admin_redhat -i ansible/inventory/hosts.yml
Two routes, both running the ubuntu_desktop play.
On the box itself — one script, no GitHub SSH key:
curl -fsSL https://raw.githubusercontent.com/vietbui1999ru/dotfiles/main/scripts/bootstrap-ubuntu.sh | bash
# or, once the repo is cloned:
scripts/bootstrap-ubuntu.sh
The script requires Ubuntu (/etc/os-release), warns if the version is not 26.04, installs git ansible python3-apt, clones ~/dotfiles over HTTPS when it is missing, then runs the play locally with -e dotfiles_git_transport=https. Extra arguments pass through (--check, --tags dotfiles). It is safe to rerun: an existing ~/dotfiles is left alone, not pulled.
This route clones over HTTPS, so origin in ~/dotfiles stays HTTPS. Once the box has an SSH key, switch it:
git -C ~/dotfiles remote set-url origin git@github.com:vietbui1999ru/dotfiles.git
From the Mac, over SSH (unchanged):
ansible-playbook ansible/site.yml --limit ubuntu_desktop -i ansible/inventory/hosts.yml -K
| Script | Purpose |
|---|---|
scripts/bootstrap-dirs.sh | Create directories, sync shared skills, and materialize default configs |
scripts/restow.sh | Restow all managed packages — single source of truth for the package list |
scripts/sync-agent-rules.sh | Sync shared/AGENTS.md and MCP servers to Claude Code, Codex, OpenCode |
scripts/agent-workflow | Attach/detach/status/doctor for per-repo Commandr/Pi/Neovim workflow |
scripts/agent-session | Legacy per-repo session inbox kept for migration compatibility |
repos/llm-wiki is a git submodule — the shared upstream for Claude Code agents, skills, and rules.
# Update llm-wiki pin to latest upstream commit
git submodule update --remote repos/llm-wiki
git add repos/llm-wiki && git commit -m "chore(submodule): bump llm-wiki"
# After pulling a commit that moves the pin, check out the pinned commit
git submodule update --init repos/llm-wiki
~/repos/llm-wiki and ~/dotfiles/repos/llm-wiki are independent clones on this machine. bootstrap-dirs.sh creates a redirect to the submodule only when no standalone clone exists; it never replaces an existing clone. Many Claude rules and skills are symlinks into the standalone clone (check with readlink); the spec-loop rules and skills, and the rules model-routing, plan-handoff, skill-invocation and startup, live in this repo. Commit and push wiki changes from the standalone clone first, then bump the pin here so the submodule matches its main.
| Tool | Install | |
|---|---|---|
pi (pi-coding-agent) | bun add -g @earendil-works/pi-coding-agent | |
| GitHub stacked PRs | gh extension install github/gh-stack (skill synced by bootstrap-dirs.sh) | |
omp (oh-my-pi) | `curl -fsSL https://omp.sh/install \ | sh` |
rtk (Rust Token Killer) | mise install (pinned in mise/.config/mise/config.toml) |
omp binaries land in ~/.bun/bin/ — already on PATH via .zprofile.
Pi runs headless only: dispatched through pueue with pi -p, and watched in the session-band pane or a herdr viewer pane (scripts/pi-view). Extensions that only act in Pi's interactive TUI are not kept. The pi/ stow package includes these Pi extensions:
~/repos/DiffViewer/pi-extension — Pi package for the measured review gate: persistent .pi/diff-review/ drafts and submitted decisionspost-run-verifier.ts — owns completed-run verification (format → lint → typecheck → focused tests), inferred per-project config persisted under ~/.pi/agent/verification/projects/, max 3 automatic repair cycles; /verify, /verify-final, /verify-status, /verify-config, /verify-init.rtk.ts — transparently rewrites supported Bash commands through RTK to reduce tool-output tokens; set RTK_DISABLED=1 for passthroughpi/.pi-lens/config.json is the stow-provisioned global pi-lens config: pi-lens owns non-mutating turn-end static safety/context signals; its LSP, test, format, and autofix runners are disabled. post-run-verifier.ts alone owns format, lint, typecheck, and focused behavioral tests.
Pi uses its built-in MCP client. scripts/sync-agent-rules.sh syncs the portable servers in shared/mcp-servers.json into ~/.pi/agent/mcp.json, preserving machine-specific entries. Do not install pi-mcp-adapter.
shared/AGENTS.md is one-way sync-pushed to OpenCode and Codex by scripts/sync-agent-rules.sh; edit the shared source, never the generated targets.~/.claude/plugins/known_marketplaces.json is materialized once from the llm-wiki template, then Claude Code manages it. Treat it as a deliberate local fork.~/.config/agent-workflow/config.json is materialized once from shared/agent-workflow.default.json. Treat it as a deliberate local fork; change the template for new machines and the local file for this machine.Claude Code uses the equivalent rtk hook claude PreToolUse hook from claude/.claude/settings.json, with usage instructions in ~/.claude/RTK.md.
Research tools have exclusive primary scopes:
ketch code onlyFallback is allowed only when the primary tool lacks coverage. Canonical policy lives in shared/research-tool-routing.md.
Firecrawl is CLI first, for every harness. bootstrap-dirs.sh calls scripts/firecrawl-setup.sh, which links two shims into ~/.local/bin (firecrawl and firecrawl-mcp, both read FIRECRAWL_API_KEY from ~/secrets/.env so a stale inherited key cannot win), installs the CLI with bun if it is missing, runs firecrawl init for the CLI's own skills, and keeps only the ones listed in shared/firecrawl-skills.txt. The rest are moved to ~/.agents/skills-disabled/, not deleted. Add a name to that file and re-run bootstrap to bring one back; scripts/firecrawl-setup.sh --refresh re-installs. The same bootstrap links the shared personal skills (gh-stack, grill-me, verify-spec and others) into ~/.agents/skills for Pi and other compatible harnesses. Codex needs a permission profile before its sandbox lets the Firecrawl CLI reach the network: see docs/codex-permissions.md.
Herdr owns the live pi, claude, and codex integration files; do not stow them. scripts/bootstrap-dirs.sh runs herdr integration install for all three. The persistent Herdr workspaces are plan (Claude) and build (Pi). com.vietbui.herdr-sketchybar-bridge subscribes to Herdr agent-state events and drives Sketchybar's agents pill; clicking it focuses Pi and opens AeroSpace workspace T.
Global defaults live in shared/agent-workflow.default.json and are copied to ~/.config/agent-workflow/config.json by scripts/bootstrap-dirs.sh. Override per repo with .agent-workflow.json or machine-locally with ignored .agent-workflow.local.json.
# Check global install state (including RTK binary + Pi extension)
scripts/agent-workflow doctor
# Attach a repo to the Commandr bus + DiffViewer sidecars + approval gate
scripts/agent-workflow attach ~/repos/example
# Inspect current bus/board state
scripts/agent-workflow status ~/repos/example
# Remove only the managed hook; keep task history by default
scripts/agent-workflow detach ~/repos/example
The spec loop is the seven numbered rules between the <!-- spec-loop:start --> and <!-- spec-loop:end --> markers in shared/AGENTS.md. The same block is mirrored in shared/research-tool-routing.md; the two copies must stay identical. The rules themselves are canonical in that block; this section describes the workflow they govern.
Prerequisites: python3 and git; approval also needs a macOS GUI session. The scripts are not on PATH, so call them as ~/dotfiles/scripts/ac-run and ~/dotfiles/scripts/floor-guard. Those paths point at the primary checkout, which may be on another branch; when developing the scripts in a feature worktree, call that worktree's scripts/ copy instead. The session-band /gates pane always uses the canonical ~/dotfiles/scripts/ copies.
grill-me skill interviews you and writes SPEC.md at the repo root. shared/templates/spec.md is the starting template: copy it to the repo root as SPEC.md and set branch: to the current branch. Lint must pass: the sections Objective, Acceptance Criteria, Boundaries (Always / Ask first / Never) and Open Questions are required. The draft is committed on its feature branch only; rule 3 forbids merging a spec-only PR into main, because a root SPEC.md merged that way is never removed by the rule 7 archive./gates pane to find matching specs (SPEC.md and specs/*.md) and pending Pi reviews across the current repo's worktrees. Select a spec to read every AC and its full verify command, then press Approve. Alternatively, run ~/dotfiles/scripts/ac-run approve SPEC.md yourself in its worktree. Both paths require a person to click Approve in a macOS dialog; Cancel is the default, and timeout or dialog failure refuses approval. There is no stdin or terminal fallback: piping y cannot approve. To read the same complete summary without running commands or changing anything, use ac-run show SPEC.md. Approval runs the non-manual commands once for a baseline only when three things hold: a merge-base against origin/HEAD, main or master exists, no non-spec changes have been committed since that merge-base, and the working tree is clean apart from SPEC.md. Otherwise the baseline is recorded as unknown, and check later reports a passing command as PASS (no baseline). It stores a record under ~/.local/state/ac-run/, named by a hash of normalized values: the spec path relative to the repo, the branch, the AC ids, and each AC's verify: and baseline: values with leading and trailing whitespace stripped. Changing one of those values voids the approval (check exits 3), but these are limits of the record: leading or trailing whitespace changes keep it, edits to the Objective, Boundaries or AC prose do not void it, and an identical relative spec on the same branch in another repo on the same machine can reuse it. It then writes status: approved into SPEC.md, but check never reads the status line, so the record alone authorizes execution. If SPEC.md is read-only, approve prints a warning and still exits 0 after writing the record. Agents never run approve. ac-run reject SPEC.md removes the record for the current verify lines and sets status: draft; it runs no command and exits 0 whether or not a record existed. ac-run status SPEC.md prints approved (record matches), draft (no record) or stale (spec changed since approval; approve again), and exits 0 only when approved.SPEC.md when its branch: matches the current branch, works only toward its AC ids, and obeys its Boundaries.verify-spec skill runs ~/dotfiles/scripts/ac-run check SPEC.md and ~/dotfiles/scripts/floor-guard. check exits 0 when every AC is PASS or MANUAL, 1 on FAIL, TIMEOUT or PRE-SATISFIED (an AC that was already true before the change), 2 on a lint or branch error, and 3 when no approval record exists. floor-guard is advisory: exit 0 clean, 1 findings, 2 error. It diffs against the merge-base with origin/HEAD, main or master; when none exists it exits 2 with no base; pass --base <ref>, so pass --base <ref> (a repo with no commits exits 2 even then). It flags added suppressions, skipped or deleted tests, removed assertions, and stubs or swallowed errors, and scans untracked files too. On exit 3 the agent stops and asks the human for approval; on FAIL, TIMEOUT or PRE-SATISFIED it fixes the code and reruns, and it reports floor-guard findings as they are, without rewording code to dodge them. Rule 6 says stop after 3 tries, while verify-spec allows 3 fix-and-rerun cycles after the first run; this README does not reconcile the two, and where they differ the rule governs. Rule 4 forbids editing a verify: line or a test to make a check pass, and verify-spec also forbids editing baseline: lines. verify-spec permits one narrower edit that rule 4 does not mention: replacing the placeholder body of a test stub the agent wrote for this spec with real assertions.docs/workflows/agent-review.md before it is pushed or merged. The gate is a human workflow; neither script enforces it. Then push the branch and open a draft PR. Before the PR is marked ready or merged, rule 7 archives the spec as the branch's last commit (git mv SPEC.md docs/specs/<YYYY-MM-DD>-<slug>.md, verify-spec Step 5), so main never keeps a root SPEC.md and the next spec cannot collide with it. Run check and floor-guard before the archive; both expect SPEC.md at the root. The approval record is keyed outside the repo and is not touched.In /gates, j/k select a row, a approves, x rejects (press twice to confirm), e edits a spec in Neovim, o opens a Pi review, and r refreshes. Spec state comes from ac-run status: draft, approved, stale, or invalid (with the error and approval disabled). Review rows show landed, processing, error and orphan tags; rejecting an orphan skips its leftover refs. b/f cycle open mod panes, w opens Worktrees, and q closes Gates. Review approval still uses agent-review's own macOS dialog; detailed diff review stays in Neovim.
Tests for both scripts: python3 scripts/tests/test_spec_loop.py. Pane tests: cd session-band-plugin && claude plugin test ..
Use GitHub's gh stack extension for a single feature split into dependent, reviewable layers. Plan layer boundaries before coding; review and approve each layer through the existing review gate before committing it. Keep unrelated work in separate stacks.
# From a clean trunk, create the first named layer (never invoke bare init).
gh stack init feature/foundation
# Commit its reviewed changes, then add the dependent layer.
gh stack add feature/integration
# Publish draft PRs without interactive prompts.
gh stack submit --auto
# Inspect or update the stack non-interactively.
gh stack view --json
gh stack sync --remote origin
Agent invocations must use named init/add branches, submit --auto, and view --json; see docs/workflows/stacked-prs.md for recovery and review rules.
jj (Jujutsu) is the default VCS for both the human and agent sessions. Each checkout or worktree is colocated with git (jj git init --colocate), so agent-review, ac-run, floor-guard and session-band keep reading git state. Agents commit only through scripts/commit-funnel, which in jj mode also tracks the paths, moves the bookmark and runs git switch <branch>; inside agent worktrees plain git commit/jj commit and other branch moves are blocked (see the "Git history" section of shared/research-tool-routing.md and docs/workflows/worktree-guard-bandaid.md). The workflows below are the human's. Claude's settings.json allows jj and denies pushing or moving main/master.
Three workflows:
jj log -r 'main..feat/x', then jj abandon / jj squash --from A --into B / jj split -r C, then jj git push -b feat/x. Undo with jj op undo.jj git fetch && jj rebase -b feat/x -d main@origin.jj new main, edit, jj file track <path>, jj describe -m ..., jj bookmark create fix/x -r @, jj git push -b fix/x, gh pr create.After any jj operation git HEAD is detached, so run git switch <branch> before running agents or ac-run. Never rewrite a branch that a running Pi worktree has checked out.
Pi is the only supported agent harness. Commandr is the task service, DiffView is the review service, and Obsidian is the human UI. Other vendors are model providers or explicit CLI bridges, not parallel harnesses.
# Pi TUI
/sessions
/review
Legacy scripts/agent-session and .agents/sessions/ remain compatibility surfaces. New workflow features should target Pi and Commandr, not add another harness-specific state store.
RTK is a rewrite-only optimization layer: it does not replace permission gates or context-mode. Inspect savings with rtk gain or rtk gain --history.
opencode/plugins/commandr-checkpoint.js and diffviewer.js are symlinks into ~/repos/Commandr and ~/repos/DiffViewer. Clone those repos first.~/.zshrc.local (not tracked).nvim/.config/nvim/.claude/ is gitignored — Claude Code writes local state there.claude/ rule files: learning.md and research.md are niche-domain rules, available at @~/.claude/rules/learning.md but not auto-loaded. @-import them in project CLAUDE.md when working in those domains.opencode/opencode.json uses hardcoded absolute paths for skills.paths and instructions — opencode does not expand ${env:HOME} in those fields.extended-keys is disabled — it breaks readline Ctrl shortcuts (C-a/e/u/k/w/r/d) in zsh. Standard key sequences work correctly without it.zsh/.zsh/functions.zsh wraps nvim to re-emit SGR reset, show-cursor, and bracketed-paste sequences after exit — nvim's terminal cleanup (rs2/RIS) wipes these and breaks Starship colors and fast-syntax-highlighting.vim.fn.exepath().hooks/register.tsx 341 lines1import { atom, read, update, type EngineInterface, type Register } from 'claude-code'
2
3import type { Usage } from '../types'
4import { drawBand } from './band'
5import { captureSession, register as registerBlast } from './blast'
6import { register as registerClear } from './clear'
7import { register as registerHandoff } from './handoff.tsx'
8import { register as registerHistory } from './history.tsx'
9import { register as registerPane } from './pane.tsx'
10import { refreshSendIt, register as registerSendIt } from './send-it.tsx'
11import { register as registerWorktrees } from './worktree-pane.tsx'
12import { register as registerDraftPrs } from './draft-prs.tsx'
13import { PANE as BLOCKS_PANE, register as registerSafetyBlocks } from './safety-blocks.tsx'
14import { loadSessionBlocks, pendingCount } from './safety-blocks'
15import { onSessionStart as lifecycleSessionStart, register as registerLifecycle } from './lifecycle.tsx'
16import { register as registerGates } from './gates.tsx'
17import { register as registerReviewPane, startReviewAnswers } from './review-pane.tsx'
18import { setTurn } from './review-land'
19import { register as registerReviewTouch } from './review-touch'
20import { deliverOwn, startDelivery } from './review-deliver'
21import { register as registerReviewReply, registerTool as registerReviewReplyTool } from './review-reply'
22import { ensureSessionBase } from './review-touch'
23import { summarize, type TrackedTask } from './handoff'
24import type { PiProgress } from './pisession'
25import { parsePending, pendingRecordFor, reviewState, type ReviewState } from './review'
26import { shortDir, shortModel, whole } from './format'
27import { toSnapshot, type GitFacts } from './git'
28import { toRepoInfo, type RepoInfo } from './repo'
29import { drawnPath, heartbeatBody, heartbeatPath, HEARTBEAT_INTERVAL_MS } from './heartbeat'
30import { openForSession, parseAlerts } from './mistake-alerts'
31import { guardAgent, softStop, type SoftStopCheck } from './threshold'
32
33const usage = atom({ plugin: 'session-band', key: 'usage' } as const, {})
34const tick = atom({ plugin: 'session-band', key: 'tick' } as const, 0)
35const git = atom({ plugin: 'session-band', key: 'git' } as const, null)
36const outputStyle = atom({ plugin: 'session-band', key: 'outputStyle' } as const, null)
37const isNotified = atom({ plugin: 'session-band', key: 'isNotified' } as const, false)
38const handoff = atom({ plugin: 'session-band', key: 'handoff' } as const, { tasks: [] as TrackedTask[], available: true })
39const progress = atom({ plugin: 'session-band', key: 'progress' } as const, {} as Record<number, PiProgress>)
40
41const asWhole = (percent: number | undefined) => (percent === undefined ? undefined : whole(percent))
42
43const measuredUsage = (context: { percent?: number }, rateLimits: readonly { kind: string; percentUsed: number }[]): Usage => ({
44 ctx: asWhole(context.percent),
45 five: asWhole(rateLimits.find(limit => limit.kind === 'five_hour')?.percentUsed),
46 seven: asWhole(rateLimits.find(limit => limit.kind === 'seven_day')?.percentUsed),
47})
48
49const refreshGit = async ($: EngineInterface) => {
50 const cwd = await $.session.cwd()
51 const run = async (args: string[]) => {
52 const r = await $.process.run(['git', '-C', cwd, '--no-optional-locks', ...args])
53 return r.exitCode === 0 ? r.stdout.trim() : undefined
54 }
55 const branch = await run(['branch', '--show-current'])
56 let facts: GitFacts = { isDirty: false }
57
58 if (branch) {
59 const [unstaged, staged, upstream, stash, gitDir, common] = await Promise.all([
60 $.process.run(['git', '-C', cwd, '--no-optional-locks', 'diff', '--quiet']),
61 $.process.run(['git', '-C', cwd, '--no-optional-locks', 'diff', '--cached', '--quiet']),
62 run(['rev-parse', '--abbrev-ref', `${branch}@{upstream}`]),
63 run(['stash', 'list']),
64 run(['rev-parse', '--absolute-git-dir']),
65 run(['rev-parse', '--path-format=absolute', '--git-common-dir']),
66 ])
67 const counts = upstream ? await run(['rev-list', '--left-right', '--count', `${upstream}...HEAD`]) : undefined
68 facts = { branch, isDirty: unstaged.exitCode !== 0 || staged.exitCode !== 0, upstream, counts, stash, gitDir, common }
69 }
70
71 await update($, git, () => toSnapshot(facts))
72}
73
74const resolveRepo = async ($: EngineInterface): Promise<RepoInfo> => {
75 const out = await $.process.run(['git', 'rev-parse', '--path-format=absolute', '--show-toplevel', '--git-common-dir'])
76 const [top, common] = out.stdout.trim().split('\n')
77
78 if (out.exitCode !== 0 || !top || !common) return {}
79
80 const taskId = (await $.fs.read(`${top}/.agent-task-id`).catch(() => '')).trim() || undefined
81
82 return toRepoInfo(common, taskId)
83}
84
85const settingStyle = async ($: EngineInterface): Promise<string | null> => {
86 const settings = await $.settings.read()
87 const style = settings.outputStyle
88
89 return typeof style === 'string' ? style : null
90}
91
92const styleForBand = (style: string | null) => (style === 'default' ? null : style)
93
94async function reviewRoot($: EngineInterface, cwd: string): Promise<string> {
95 const result = await $.process.run(['git', '-C', cwd, 'rev-parse', '--show-toplevel']).catch(() => undefined)
96 return result?.exitCode === 0 && result.stdout.trim() ? result.stdout.trim() : cwd
97}
98
99async function reviewStates($: EngineInterface, tasks: readonly TrackedTask[]): Promise<Record<number, ReviewState>> {
100 const remembered = new Map<number, string>()
101 const values = await Promise.all(tasks.map(async task => {
102 const root = `${await reviewRoot($, task.cwd)}/.pi/agent-review`
103 const pendingFiles = await $.fs.list(`${root}/pending`).catch(() => [])
104 const pending = [] as NonNullable<ReturnType<typeof parsePending>>[]
105 for (const file of pendingFiles) {
106 if (file.kind !== 'file') continue
107 const match = file.name.match(/^(.+)\.(json|processing)$/)
108 if (!match) continue
109 const runId = match[1]!
110 const parsed = parsePending(await $.fs.read(`${root}/pending/${file.name}`).catch(() => ''))
111 if (parsed && parsed.runId === runId) pending.push(parsed)
112 else if (match[2] === 'processing') pending.push({ runId, files: [] })
113 }
114 const current = pendingRecordFor(task, pending)
115 const runId = task.runId ?? current?.runId
116 if (!task.runId && runId) remembered.set(task.id, runId)
117 let decision: unknown
118 if (runId) {
119 try { decision = JSON.parse(await $.fs.read(`${root}/decisions/${runId}.json`)) } catch { /* absent or malformed decision is opaque */ }
120 }
121 return [task.id, reviewState(current, decision)] as const
122 }))
123 if (remembered.size > 0) {
124 await update($, handoff, state => ({
125 ...state,
126 tasks: state.tasks.map(task => remembered.has(task.id) ? { ...task, runId: remembered.get(task.id) } : task),
127 }))
128 }
129 return Object.fromEntries(values)
130}
131
132// Every HEARTBEAT_INTERVAL_MS: write the liveness file (.alive: this process is alive, read by the pueue lifecycle
133// and the worktrees pane), bump the tick so a band on screen redraws and refreshes its .drawn file, and re-read
134// usage and git so the band does not depend on Bash calls or turn ends to stay current.
135const startHeartbeat = async ($: EngineInterface) => {
136 const tmp = await $.env.get('TMPDIR') ?? '/tmp'
137 // A failed id lookup must not cost the session its start hooks: an empty id yields no heartbeat path.
138 const path = heartbeatPath(tmp, await $.session.id().catch(() => ''))
139 const beat = async () => {
140 if (path) await $.fs.write(path, heartbeatBody(await $.clock.now(), await $.session.cwd()))
141 await update($, tick, n => n + 1)
142 const current = await $.session.usage()
143 await update($, usage, () => measuredUsage(current.context, current.rateLimits))
144 await refreshGit($)
145 }
146 if (path) await $.fs.write(path, heartbeatBody(await $.clock.now(), await $.session.cwd()))
147 $.clock.every(HEARTBEAT_INTERVAL_MS, () => { void beat().catch(() => undefined) })
148}
149
150// The .drawn file tells statusline-command.sh the band is on screen, so the fallback stays silent only while it is.
151// Written from the draw at most every DRAWN_MIN_GAP_MS (one small write per tick, not per keystroke); a failed
152// write never costs the draw its band.
153// The throttle reads the file's own time: a draw may not write $.state, and a module variable would not survive a
154// reload or keep sessions apart.
155const DRAWN_MIN_GAP_S = 5
156const markDrawn = async ($: EngineInterface, sessionId: string, nowMs: number) => {
157 const path = drawnPath(await $.env.get('TMPDIR') ?? '/tmp', sessionId)
158 if (!path) return
159 const nowS = Math.floor(nowMs / 1000)
160 const last = Number.parseInt(String(await $.fs.read(path).catch(() => '')), 10)
161 if (Number.isFinite(last) && nowS - last < DRAWN_MIN_GAP_S) return
162 await $.fs.write(path, `${nowS}\n`).catch(() => undefined)
163}
164
165export const register: Register = on => {
166 registerBlast(on)
167 registerClear(on)
168 registerHandoff(on)
169 registerHistory(on)
170 registerPane(on)
171 registerWorktrees(on)
172 registerDraftPrs(on)
173 registerSafetyBlocks(on)
174 registerLifecycle(on)
175 registerGates(on)
176 registerReviewPane(on)
177 registerSendIt(on)
178 registerReviewReply(on)
179 // Last, so its Bash snapshot runs only for a call the guards above let through.
180 registerReviewTouch(on)
181
182 // The settings fallback only matters before the first prompt.compose names the style.
183 let hasComposed = false
184 let settingsStyle: Promise<string | null> | undefined
185
186 on('session.start', async ($, e, next) => {
187 captureSession(e.isInteractive)
188 // A heartbeat failure must not cost the session its command registrations (F3).
189 await startHeartbeat($).catch(() => undefined)
190 // A settings read failure leaves send-it off for this session rather than failing the start.
191 await refreshSendIt($).catch(() => false)
192 await $.command.register({ name: 'pi', description: 'Open Pi hand-off controls, or kill/pause/resume/rm/hold Pi tasks', argumentHint: '[kill|pause|resume|rm|hold] [ids|all] | release', immediate: true })
193 await $.command.register({ name: 'pi-history', description: 'Open Pi hand-off history' })
194 await $.command.register({ name: 'worktrees', description: 'Open the worktrees and branches pane' })
195 await $.command.register({ name: 'draft-prs', description: 'Open the draft PRs pane: open drafts, ready PRs and merges from the last 7 days' })
196 await $.command.register({ name: BLOCKS_PANE.command, description: "Open the blocks pane: this session's bash-safety blocks, o marks ok, f marks false-positive" })
197 await $.command.register({ name: 'gates', description: 'Open spec approvals and pending Pi reviews across worktrees' })
198 await $.command.register({ name: 'diff-review', description: 'Review the worktree: one tab per unapproved file, with comments, questions and proposed patches' })
199 await $.command.register({ name: 'send-it', description: 'Turn send-it mode on or off for this repo, or show its state', argumentHint: 'on|off|status' })
200 const current = await $.session.usage()
201 await Promise.all([
202 update($, usage, () => measuredUsage(current.context, current.rateLimits)),
203 refreshGit($),
204 ])
205 await lifecycleSessionStart($).catch(() => undefined)
206 // The review base is the snapshot at the session's start, so a failure here never costs the start.
207 await ensureSessionBase($, await $.session.id().catch(() => ''), await $.session.cwd().catch(() => '')).catch(() => undefined)
208 // One 60-second tick for the review queue: no-reply timeouts, and a retry for a queued Pi batch.
209 startDelivery($)
210 // Answers and agreed patches are noticed while the review pane is open; closed, the tick is a no-op.
211 startReviewAnswers($)
212 // The tool an agent answers a review batch with; a failure here costs only that tool.
213 await registerReviewReplyTool($).catch(() => undefined)
214
215 return next(e)
216 })
217
218 on('session.measure', async ($, e, next) => {
219 await update($, usage, () => measuredUsage(e.context, e.rateLimits))
220
221 return next(e)
222 })
223
224 // The review pane lands and commits patches only between turns; turn.start/turn.complete are
225 // the one pair that records this session's own turn in review-land's atom.
226 on('turn.start', async ($, e, next) => {
227 if (e.agentId === undefined) await setTurn($, true).catch(() => undefined)
228 return next(e)
229 })
230
231 on('turn.complete', async ($, e, next) => {
232 if (e.agentId === undefined) await setTurn($, false).catch(() => undefined)
233 await refreshGit($)
234 // Notes never interrupt a running turn: the main loop's end is when this session's batches go in.
235 if (e.agentId === undefined) {
236 const [worktree, sessionId] = await Promise.all([$.session.cwd().catch(() => ''), $.session.id().catch(() => '')])
237 if (worktree !== '' && sessionId !== '') await deliverOwn($, worktree, sessionId).catch(() => undefined)
238 }
239
240 return next(e)
241 })
242
243 on('tool.call', async ($, e, next) => {
244 const { context } = await $.session.usage()
245 const r = await next(e)
246
247 // Not awaited: the band catches up on redraw, and the tool result must not wait on ~7 git calls.
248 if (e.tool === 'Bash') void refreshGit($).catch(() => undefined)
249 if ('deny' in r) return r
250
251 return (async () => {
252 const { taskId, statePath } = await resolveRepo($)
253 const lastSavedMs = statePath
254 ? await $.fs.stat(statePath).then(stat => stat.mtimeMs).catch(() => undefined)
255 : undefined
256 const filePath = 'file_path' in e && typeof e.file_path === 'string' ? e.file_path : undefined
257 const check: SoftStopCheck = {
258 percent: asWhole(context.percent),
259 tool: e.tool,
260 filePath,
261 command: e.tool === 'Bash' ? e.command : undefined,
262 nowMs: await $.clock.now(),
263 isNotified: await read($, isNotified),
264 taskId,
265 lastSavedMs,
266 }
267 const stop = softStop(check)
268
269 if (stop.action === 'clear') {
270 await update($, isNotified, () => false)
271 } else if (stop.action === 'notify') {
272 await update($, isNotified, () => true)
273
274 return { ...r, context: [...(r.context ?? []), stop.text] }
275 }
276
277 return r
278 })().catch(() => r)
279 })
280
281 on('tool.call', { tool: 'Agent' }, async ($, e, next) => {
282 const { context } = await $.session.usage()
283 const denial = guardAgent(asWhole(context.percent), e.tool)
284
285 return denial ? { deny: denial } : next(e)
286 }).catch(($, e, next) => next.called ? next(e) : { deny: 'session-band guard failed' })
287
288 on('prompt.compose', async ($, e, next) => {
289 hasComposed = true
290 await update($, outputStyle, () => e.outputStyle?.name ?? null)
291
292 return next(e)
293 })
294
295 on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
296 if (e.props.hasSurvey) return next(e)
297
298 const [cwd, home, model, currentUsage, _tick, currentGit, capturedStyle, currentHandoff, currentProgress, nowMs] = await Promise.all([
299 $.session.cwd(),
300 $.env.get('HOME'),
301 $.session.model(),
302 read($, usage),
303 // Read only so each heartbeat tick redraws the band, and the draw below rewrites the liveness file.
304 read($, tick),
305 read($, git),
306 read($, outputStyle),
307 read($, handoff),
308 read($, progress),
309 $.clock.now(),
310 ])
311 const currentReview = await reviewStates($, currentHandoff.tasks)
312 // Mistake alerts are written by the PostToolUseFailure hook; the band shows only this session's open ones.
313 const sessionId = await $.session.id().catch(() => '')
314 await markDrawn($, sessionId, nowMs).catch(() => undefined)
315 const alertsRaw = home ? await $.fs.read(`${home}/.claude/state/mistake-alerts.json`).catch(() => undefined) : undefined
316 const openAlerts = openForSession(parseAlerts(typeof alertsRaw === 'string' ? alertsRaw : undefined), sessionId)
317 // The block chip counts only this session's unjudged blocks; the pane lists them for marking.
318 const pendingBlocks = pendingCount(await loadSessionBlocks($).catch(() => []))
319 if (!hasComposed) settingsStyle ??= settingStyle($).catch(() => null)
320 const style = styleForBand(capturedStyle ?? (hasComposed ? null : await settingsStyle))
321
322 return drawBand($.ui.resolve(e), {
323 dir: shortDir(cwd, home),
324 model: shortModel(model),
325 usage: currentUsage,
326 git: currentGit,
327 style,
328 handoff: currentHandoff.available ? summarize(currentHandoff.tasks, currentProgress, currentReview, nowMs) ?? undefined : undefined,
329 piQueue: currentHandoff.queue,
330 width: e.props.bodyColumns,
331 onPi: () => { void $.ui.open({ id: 'pi-handoff', title: 'Pi hand-off', focus: true }) },
332 onWorktrees: () => { void $.ui.open({ id: 'worktrees', title: 'Worktrees', focus: true }) },
333 onPiHistory: () => { void $.ui.open({ id: 'pi-history', title: 'Pi history', focus: true }) },
334 onDraftPrs: () => { void $.ui.open({ id: 'draft-prs', title: 'Draft PRs', focus: true }) },
335 onBlocks: () => { void $.ui.open({ id: BLOCKS_PANE.id, title: BLOCKS_PANE.title, focus: true }) },
336 blocks: pendingBlocks,
337 openAlerts,
338 })
339 })
340}
341hooks/band.tsx 44 lines1import type { EngineInterface } from 'claude-code'
2
3import type { GitSnapshot, Usage } from '../types'
4import type { HandoffSegment } from './handoff'
5import { layoutBand, SEP, type Seg } from './band-text'
6import { PALETTE, type Tone } from './palette'
7
8type Elements = ReturnType<EngineInterface['ui']['resolve']>
9export type BandData = { dir: string; model: string; usage: Usage; git: GitSnapshot | null; style: string | null; handoff?: HandoffSegment; width?: number; onPi?: () => void; onWorktrees?: () => void; onPiHistory?: () => void; onDraftPrs?: () => void; onBlocks?: () => void; openAlerts?: number; blocks?: number; piQueue?: string }
10
11const handoffTone = (state: HandoffSegment['state'] | undefined, review: HandoffSegment['review']): Tone => {
12 if (review === 'pending' || review === 'decided, waiting for the next Pi run in this repo' || state === 'Queued' || state === 'Paused') return 'yellow'
13 if (state === 'Failed' || state === 'Killed') return 'red'
14 if (state === 'Done') return 'green'
15 return 'teal'
16}
17
18// Left: the worktrees (⎇), Pi history (⟲), draft PRs (⑂) and blocks (⛔N) icon chips, then where · budget · alerts · who. Right: the Pi hand-off icon (π), coloured by state. The strings come from band-text.ts.
19export const drawBand = ({ Box, Text, Button }: Elements, d: BandData) => {
20 const lay = layoutBand({ ...d, wt: !!d.onWorktrees, history: !!d.onPiHistory, drafts: !!d.onDraftPrs, blocks: d.blocks, piChip: !!d.onPi })
21 const run = (seg: Seg, key: string) => <Text key={key} color={PALETTE[seg.tone]}>{seg.text}</Text>
22 const status = lay.status.flatMap((group, gi) => [
23 ...(gi > 0 ? [<Text key={`sep-${gi}`} color={PALETTE.muted}>{SEP}</Text>] : []),
24 ...group.flatMap((seg, si) => (si > 0 ? [' ', run(seg, `seg-${gi}-${si}`)] : [run(seg, `seg-${gi}-${si}`)])),
25 ])
26 const piColor = d.handoff ? PALETTE[handoffTone(d.handoff.state, d.handoff.review)] : PALETTE.muted
27
28 return (
29 <Box flexDirection="row" justifyContent="space-between" columnGap={1}>
30 {/* Buttons sit beside the Text, never inside it: the engine refuses a Button inside an inline element. */}
31 <Box flexDirection="row" columnGap={1} flexShrink={1}>
32 {lay.wt && <Button key="wt-open" plain dimColor label={lay.wt} onPress={() => d.onWorktrees?.()} />}
33 {lay.history && <Button key="hist-open" plain dimColor label={lay.history} onPress={() => d.onPiHistory?.()} />}
34 {lay.drafts && <Button key="prs-open" plain dimColor label={lay.drafts} onPress={() => d.onDraftPrs?.()} />}
35 {lay.blocks && <Button key="blocks-open" plain dimColor label={lay.blocks} onPress={() => d.onBlocks?.()} />}
36 <Text mono wrap="truncate-end">{status}</Text>
37 </Box>
38 {lay.pi && (d.onPi
39 ? <Button key="pi-open" plain onPress={() => d.onPi?.()}><Text mono color={piColor}>{lay.pi}</Text></Button>
40 : <Text mono color={piColor}>{lay.pi}</Text>)}
41 </Box>
42 )
43}
44hooks/blast.tsx 162 lines1import type { EngineInterface, Register } from 'claude-code'
2
3import { classify, type Classification, type CommandFact } from './classify'
4import { preview, type PreviewFacts, type PreviewTarget } from './preview'
5import { hideBlast, register as registerPane, showBlast } from './blast-pane.tsx'
6
7const hasGlob = (value: string) => /[*?[]/.test(value)
8const cannotExpandGlob = (value: string) => value.includes('**') || value.includes('{') || value.includes('}')
9
10const inClass = (source: string, value: string) => {
11 for (let index = 0; index < source.length; index += 1) {
12 const start = source[index] ?? ''
13 const end = source[index + 2]
14 if (source[index + 1] === '-' && end !== undefined) {
15 if (start <= value && value <= end) return true
16 index += 2
17 } else if (start === value) return true
18 }
19 return false
20}
21
22const matches = (pattern: string, name: string) => {
23 let patternIndex = 0
24 let nameIndex = 0
25 let starIndex = -1
26 let retryNameIndex = 0
27
28 while (nameIndex < name.length) {
29 const token = pattern[patternIndex]
30 if (token === '*') {
31 starIndex = patternIndex
32 patternIndex += 1
33 retryNameIndex = nameIndex
34 } else if (token === '?' || token === name[nameIndex]) {
35 patternIndex += 1
36 nameIndex += 1
37 } else if (token === '[') {
38 const close = pattern.indexOf(']', patternIndex + 1)
39 if (close !== -1 && inClass(pattern.slice(patternIndex + 1, close), name[nameIndex] ?? '')) {
40 patternIndex = close + 1
41 nameIndex += 1
42 } else if (starIndex !== -1) {
43 patternIndex = starIndex + 1
44 retryNameIndex += 1
45 nameIndex = retryNameIndex
46 } else return false
47 } else if (starIndex !== -1) {
48 patternIndex = starIndex + 1
49 retryNameIndex += 1
50 nameIndex = retryNameIndex
51 } else return false
52 }
53
54 while (pattern[patternIndex] === '*') patternIndex += 1
55 return patternIndex === pattern.length
56}
57
58const globParts = (target: string) => {
59 const slash = target.lastIndexOf('/')
60 if (slash === -1) return { directory: '.', pattern: target, prefix: '' }
61 const directory = slash === 0 ? '/' : target.slice(0, slash)
62 return { directory, pattern: target.slice(slash + 1), prefix: target.slice(0, slash + 1) }
63}
64
65const tracked = async ($: EngineInterface, path: string) => {
66 const result = await $.process.run(['git', 'ls-files', '--error-unmatch', '--', path]).catch(() => undefined)
67 return result?.exitCode === 0
68}
69
70const expandedTargets = async ($: EngineInterface, target: string): Promise<{ targets: PreviewTarget[]; unexpanded?: string }> => {
71 if (!hasGlob(target)) {
72 const stat = await $.fs.stat(target).catch(() => undefined)
73 if (!stat) return { targets: [{ path: target }] }
74 return { targets: [{ path: target, bytes: stat.size, tracked: await tracked($, target) }] }
75 }
76 if (cannotExpandGlob(target)) return { targets: [], unexpanded: target }
77
78 const { directory, pattern, prefix } = globParts(target)
79 const entries = await $.fs.list(directory).catch(() => undefined)
80 if (!entries) return { targets: [], unexpanded: target }
81
82 return {
83 targets: await Promise.all(entries.flatMap(entry => {
84 if (!matches(pattern, entry.name)) return []
85 const path = `${prefix}${entry.name}`
86 return [(async () => ({ path, bytes: entry.size, tracked: await tracked($, path) }))()]
87 })),
88 }
89}
90
91const dryRun = async ($: EngineInterface, commands: readonly CommandFact[]) => {
92 const command = commands.find(item => item.program === 'git' && item.args[0] === 'clean')
93 if (command) {
94 const result = await $.process.run(['git', 'clean', '-n', ...command.args.slice(1)]).catch(() => undefined)
95 if (result) return { label: 'git clean -n', output: result.stdout || result.stderr }
96 }
97
98 if (commands.some(item => item.program === 'git' && ['reset', 'checkout', 'restore'].includes(item.args[0] ?? ''))) {
99 const result = await $.process.run(['git', 'diff', '--stat']).catch(() => undefined)
100 if (result) return { label: 'git diff --stat', output: result.stdout || result.stderr }
101 }
102
103 const rsync = commands.find(item => item.program === 'rsync')
104 if (rsync) {
105 const result = await $.process.run(['rsync', '-n', ...rsync.args]).catch(() => undefined)
106 if (result) return { label: 'rsync -n', output: result.stdout || result.stderr }
107 }
108
109 return undefined
110}
111
112const previewFacts = async ($: EngineInterface, command: string, result: Classification): Promise<PreviewFacts> => {
113 const expanded = await Promise.all(result.commands.flatMap(item => item.targets).map(target => expandedTargets($, target)))
114 const targets = expanded.flatMap(item => item.targets)
115 const totalBytes = targets.reduce((total, target) => total + (target.bytes ?? 0), 0)
116
117 return {
118 command,
119 reason: result.reason ?? 'this command may have a broad effect',
120 targets,
121 totalBytes: targets.some(target => target.bytes !== undefined) ? totalBytes : undefined,
122 unexpandedGlobs: expanded.flatMap(item => item.unexpanded ? [item.unexpanded] : []),
123 dryRun: await dryRun($, result.commands),
124 }
125}
126
127const refusal = (command: string, reason: string) => `Bash command ${JSON.stringify(command)} was refused by blast-radius: ${reason}.`
128
129let isInteractive = false
130
131export const captureSession = (interactive: boolean) => {
132 isInteractive = interactive
133}
134
135export const register: Register = on => {
136 registerPane(on)
137 on('tool.call', { tool: 'Bash' }, async ($, e, next) => {
138 const result = classify(e.command)
139 if (result.tier === 'pass') return next(e)
140 if (result.tier === 'deny') return { deny: refusal(e.command, result.reason ?? 'it is unconditionally dangerous') }
141 if (!isInteractive) return { deny: refusal(e.command, 'nobody is available to answer the blast-radius prompt') }
142
143 const facts = await previewFacts($, e.command, result).catch(() => ({
144 command: e.command,
145 reason: result.reason ?? 'this command may have a broad effect',
146 }))
147 // The pane is a read-only view of the same facts; only the question decides.
148 await showBlast($, facts).catch(() => undefined)
149 let answer: string
150 try {
151 answer = await $.ui.ask(`${preview(facts)}\n\nAllow this Bash command?`, ['Allow', 'Deny'])
152 } catch {
153 return { deny: refusal(e.command, 'the blast-radius prompt was dismissed') }
154 } finally {
155 await hideBlast($).catch(() => undefined)
156 }
157 return answer === 'Allow'
158 ? next(e)
159 : { deny: refusal(e.command, 'the blast-radius prompt was not allowed') }
160 }).catch(($, e, next) => next.called ? next(e) : { deny: 'Bash command was refused by blast-radius: the guard failed closed.' })
161}
162hooks/clear.tsx 188 lines1import {
2 atom,
3 read,
4 update,
5 type CommandRunInput,
6 type CommandRunResult,
7 type EngineInterface,
8 type Next,
9 type Register,
10} from 'claude-code'
11
12import { toRepoInfo, type RepoInfo } from './repo'
13import {
14 buildDigest,
15 extractSavedPath,
16 isRealWork,
17 parseReply,
18 RECENT_SAVE_MS,
19 summaryPrompt,
20 SYSTEM_PROMPT,
21 taskStateFile,
22 type ParsedSummary,
23} from './summary'
24
25const edits = atom({ plugin: 'session-band', key: 'edits' } as const, 0)
26const prompts = atom({ plugin: 'session-band', key: 'prompts' } as const, 0)
27
28const REFUSED =
29 'Clear refused: the transcript is already gone, nothing to summarise. Run save-session first, or re-run /clear.'
30const CANCELLED = 'Clear cancelled: nothing was saved.'
31const SAVE_FAILED = 'Clear cancelled: the save step failed.'
32
33const reset = async ($: EngineInterface) => {
34 await update($, edits, () => 0)
35 await update($, prompts, () => 0)
36}
37
38const resolveRepo = async ($: EngineInterface): Promise<RepoInfo> => {
39 const out = await $.process.run(['git', 'rev-parse', '--path-format=absolute', '--show-toplevel', '--git-common-dir'])
40 const [top, common] = out.stdout.trim().split('\n')
41
42 if (out.exitCode !== 0 || !top || !common) return {}
43
44 const taskId = (await $.fs.read(`${top}/.agent-task-id`).catch(() => '')).trim() || undefined
45
46 return toRepoInfo(common, taskId)
47}
48
49const sessionsDir = async ($: EngineInterface): Promise<string | undefined> => {
50 const out = await $.process.run(['agent-session', 'path'])
51 return out.exitCode === 0 && out.stdout.trim() !== '' ? out.stdout.trim() : undefined
52}
53
54// A save in the last five minutes counts as "already saved by hand": the task
55// state file's mtime in a task worktree, else the newest file in the sessions
56// directory. (The non-task statePath is .claude/session-state.md, which the CLI
57// maintains, so it is not the signal here.)
58const recentlySaved = async ($: EngineInterface, repo: RepoInfo, nowMs: number): Promise<boolean> => {
59 if (repo.taskId !== undefined && repo.statePath !== undefined) {
60 const stat = await $.fs.stat(repo.statePath).catch(() => undefined)
61 return stat !== undefined && nowMs - stat.mtimeMs <= RECENT_SAVE_MS
62 }
63
64 const dir = await sessionsDir($)
65 if (dir === undefined) return false
66
67 const entries = await $.fs.list(dir).catch(() => undefined)
68 if (entries === undefined) return false
69
70 let newest: number | undefined
71 for (const entry of entries) {
72 // Only session files count; index.json is rewritten by any save, by any harness.
73 if (entry.kind === 'file' && entry.name.endsWith('.md') && (newest === undefined || entry.mtimeMs > newest)) {
74 newest = entry.mtimeMs
75 }
76 }
77
78 return newest !== undefined && nowMs - newest <= RECENT_SAVE_MS
79}
80
81const saveSession = async ($: EngineInterface, repo: RepoInfo, summary: ParsedSummary): Promise<string> => {
82 // Task worktrees write the claimed state file; the orchestrator goes through
83 // the agent-session CLI, which resolves the sessions directory itself.
84 if (repo.statePath !== undefined && repo.taskId !== undefined) {
85 await $.fs.write(repo.statePath, taskStateFile(repo.taskId, summary.body))
86 return repo.statePath
87 }
88
89 const root = await $.session.root()
90 const saved = await $.process.run(
91 ['agent-session', 'save', '--harness', 'cc', '--goal', summary.goal, '--stdin'],
92 { cwd: root, stdin: summary.body, timeoutMs: 30_000 },
93 )
94 if (saved.exitCode !== 0) throw new Error(`agent-session exit ${saved.exitCode}`)
95
96 const path = extractSavedPath(saved.stdout)
97 if (path !== undefined) return path
98
99 const active = await $.process.run(['agent-session', 'active'])
100 if (active.exitCode === 0 && active.stdout.trim() !== '') return active.stdout.trim()
101
102 throw new Error('agent-session printed no path')
103}
104
105const fail = async (
106 $: EngineInterface,
107 e: CommandRunInput,
108 next: Next<'command.run'>,
109 reason: string,
110): Promise<CommandRunResult> => {
111 // A plugin or headless run has nobody to answer; refuse rather than hang.
112 if (e.origin.kind !== 'composer') return { text: CANCELLED }
113
114 try {
115 const answer = await $.ui.ask(`Save failed (${reason}). Clear anyway?`, ['Clear anyway', 'Cancel'])
116 if (answer === 'Clear anyway') {
117 await reset($)
118 return next(e)
119 }
120 return { text: CANCELLED }
121 } catch {
122 return { text: CANCELLED }
123 }
124}
125
126export const register: Register = on => {
127 // The module's own counters: real work is a successful edit tool or enough
128 // prompts. The transcript may already be wiped by the time /clear runs.
129 on('prompt.submit', async ($, e, next) => {
130 await update($, prompts, n => n + 1)
131 return next(e)
132 })
133
134 on('tool.call', { tool: ['Edit', 'Write', 'MultiEdit', 'NotebookEdit'] }, async ($, e, next) => {
135 const result = await next(e)
136 if (!('deny' in result)) {
137 await update($, edits, n => n + 1)
138 }
139 return result
140 })
141
142 on('command.run', { command: 'clear' }, async ($, e, next) => {
143 const [editCount, promptCount] = await Promise.all([read($, edits), read($, prompts)])
144 if (!isRealWork({ edits: editCount, prompts: promptCount })) {
145 await reset($)
146 return next(e)
147 }
148
149 const repo = await resolveRepo($)
150 const nowMs = await $.clock.now()
151 if (await recentlySaved($, repo, nowMs)) {
152 await reset($)
153 return next(e)
154 }
155
156 const messages = await $.session.messages()
157 if (messages.length === 0) {
158 // Counters say work happened but the transcript is gone: refuse, and do
159 // not reset, so a later save + /clear still reaches the recent-save skip.
160 return { text: REFUSED }
161 }
162
163 const reply = await $.model.complete({
164 model: 'sonnet',
165 system: SYSTEM_PROMPT,
166 prompt: summaryPrompt(buildDigest(messages)),
167 maxTokens: 2000,
168 effort: 'low',
169 timeoutMs: 60_000,
170 })
171
172 const summary = reply.isAnswered ? parseReply(reply.text) : undefined
173 if (summary === undefined) {
174 return fail($, e, next, reply.isAnswered ? 'the summary was not parseable' : `model ${reply.reason}`)
175 }
176
177 try {
178 const path = await saveSession($, repo, summary)
179 await reset($)
180 // The answer's text, not a toast: /clear ends the session and the toast went with it.
181 const result = await next(e)
182 return { ...result, text: `Session saved: ${path}` }
183 } catch (error) {
184 return fail($, e, next, String(error))
185 }
186 }).catch(($, e, next) => next.called ? next(e) : { text: SAVE_FAILED })
187}
188hooks/handoff.tsx 140 lines1import { atom, read, update, type EngineInterface, type Register } from 'claude-code'
2
3import { emptyProgress, fold, sessionDir, sessionFileName, type PiProgress } from './pisession'
4import { parsePiCommand, parseStatus, type Task } from './pueue'
5import { finishNotice, type TrackedTask } from './handoff'
6import { daemonState, queueBadge } from './lifecycle'
7
8export type HandoffState = { tasks: TrackedTask[]; available: boolean; selectedId?: number; showThinking?: boolean; showAll?: boolean; confirm?: { action: 'kill' | 'hold'; ids: number[]; atMs: number }; queue?: string }
9
10const handoff = atom({ plugin: 'session-band', key: 'handoff' } as const, { tasks: [], available: true } satisfies HandoffState)
11const progress = atom({ plugin: 'session-band', key: 'progress' } as const, {} as Record<number, PiProgress>)
12let timer: { cancel(): void } | undefined
13let polling = false
14
15const liveState = (state: Task['state'] | undefined) => state === 'Queued' || state === 'Running' || state === 'Paused'
16const isLive = (task: Task | undefined) => liveState(task?.state)
17export const hasLiveTrackedTask = (tasks: readonly TrackedTask[]) => tasks.some(item => isLive(item.task))
18const inside = (path: string, root: string) => path === root || path.startsWith(`${root}/`)
19
20// A dispatch into a sibling worktree sits outside this session's cwd and root, so a task whose
21// pueue label appears as a whole word in the dispatching command is this session's too.
22const labelledIn = (command: string, label: string | undefined) =>
23 !!label && command.split(/[\s"'=]+/).includes(label)
24
25export const trackedFrom = (tasks: readonly Task[], startedMs: number, cwd: string, root: string, command = ''): TrackedTask[] =>
26 tasks.flatMap(task => {
27 const ours = inside(task.cwd, cwd) || inside(task.cwd, root) || labelledIn(command, task.label)
28 if ((task.createdMs ?? -Infinity) < startedMs || !ours) return []
29 const parsed = parsePiCommand(task.command)
30 if (!parsed.model) return []
31 return [{ id: task.id, cwd: task.cwd, addedMs: task.createdMs ?? startedMs, task, ...(parsed.sessionId ? { sessionId: parsed.sessionId } : {}), ...(task.label ?? parsed.label ? { label: task.label ?? parsed.label } : {}) }]
32 })
33
34// A task missing from the snapshot is dropped only when it was tracked before the snapshot was
35// taken: one the tracker added while `pueue status` was running is simply not in it yet.
36const mergeTasks = (old: readonly TrackedTask[], fresh: readonly Task[], nowMs: number, snapshotMs: number): TrackedTask[] => {
37 const byId = new Map(fresh.map(task => [task.id, task]))
38 return old.flatMap(item => {
39 const task = byId.get(item.id)
40 if (!task) return item.addedMs >= snapshotMs ? [item] : []
41 const finishedMs = item.finishedMs ?? (isLive(task) ? undefined : nowMs)
42 return [{ ...item, task, ...(finishedMs ? { finishedMs } : {}) }]
43 })
44}
45
46const tail = async ($: EngineInterface, item: TrackedTask, current: PiProgress, home: string | undefined): Promise<PiProgress | undefined> => {
47 if (!item.sessionId || !home) return undefined
48 const dir = `${home}/.pi/agent/sessions/${sessionDir(item.cwd)}`
49 const files = await $.fs.list(dir).catch(() => [])
50 const name = files.find(file => file.kind === 'file' && sessionFileName(item.sessionId!).test(file.name))?.name
51 if (!name) return undefined
52 const path = `${dir}/${name}`
53 const stat = await $.fs.stat(path).catch(() => undefined)
54 if (!stat || stat.size <= current.offset) return undefined
55 const from = current.offset > stat.size ? 0 : current.offset
56 const result = await $.process.run(['tail', '-c', `+${from + 1}`, path])
57 return result.exitCode === 0 ? fold(from === current.offset ? current : emptyProgress(), result.stdout) : undefined
58}
59
60async function poll($: EngineInterface) {
61 if (polling) return
62 polling = true
63 try {
64 const snapshotMs = await $.clock.now()
65 const result = await $.process.run(['pueue', 'status', '--json'])
66 const daemon = daemonState(result.exitCode, result.stdout)
67 if (result.exitCode !== 0) {
68 console.debug('session-band: pueue daemon unavailable')
69 await update($, handoff, state => ({ ...state, available: false, queue: queueBadge(daemon, hasLiveTrackedTask(state.tasks)) }))
70 return
71 }
72 const fresh = parseStatus(result.stdout)
73 const nowMs = await $.clock.now()
74 const before = new Map((await read($, handoff)).tasks.map(item => [item.id, item.task?.state]))
75 // Merge inside the update so a task the tracker added meanwhile is not overwritten.
76 await update($, handoff, value => {
77 const tasks = mergeTasks(value.tasks, fresh, nowMs, snapshotMs)
78 return { ...value, tasks, available: true, queue: queueBadge(daemon, hasLiveTrackedTask(tasks)) }
79 })
80 const { tasks } = await read($, handoff)
81 const home = await $.env.get('HOME')
82 const existing = await read($, progress)
83 const next = { ...existing }
84 for (const item of tasks) {
85 const updateProgress = await tail($, item, next[item.id] ?? emptyProgress(), home)
86 if (updateProgress) next[item.id] = updateProgress
87 }
88 await update($, progress, () => next)
89 // Act only on a transition this poller saw live: a repeat poll sees it finished in `before`.
90 const ended = (await read($, handoff)).tasks.filter(item => liveState(before.get(item.id)) && !isLive(item.task))
91 // A pick that finishes lets go, so the transcript follows the newest running task again.
92 await update($, handoff, value => ended.some(item => item.id === value.selectedId) ? { ...value, selectedId: undefined } : value)
93 for (const item of ended) {
94 const notice = finishNotice(item, next[item.id] ?? existing[item.id])
95 const sent = await $.ui.notify(notice, { title: 'Pi hand-off' }).catch(() => undefined)
96 if (!sent?.isSent) await $.ui.toast(notice)
97 }
98 await syncTimer($)
99 } finally {
100 polling = false
101 }
102}
103
104async function syncTimer($: EngineInterface) {
105 const state = await read($, handoff)
106 if (hasLiveTrackedTask(state.tasks)) {
107 if (!timer) timer = $.clock.every(2_000, () => { void poll($) })
108 } else if (timer) {
109 timer.cancel()
110 timer = undefined
111 }
112}
113
114export const register: Register = on => {
115 on('tool.call', { tool: 'Bash' }, async ($, e, next) => {
116 const startedMs = await $.clock.now()
117 const result = await next(e)
118 if ('deny' in result || !e.command.includes('pueue add')) return result
119 const status = await $.process.run(['pueue', 'status', '--json']).catch(() => undefined)
120 if (!status || status.exitCode !== 0) return result
121 const [cwd, root, nowMs] = await Promise.all([$.session.cwd(), $.session.root(), $.clock.now()])
122 const candidates = trackedFrom(parseStatus(status.stdout), startedMs, cwd, root, e.command)
123 if (candidates.length > 0) {
124 // A simultaneous session can race here; v1 intentionally accepts that narrow attribution race.
125 await update($, handoff, state => ({ ...state, available: true, tasks: [...state.tasks, ...candidates.filter(candidate => !state.tasks.some(item => item.id === candidate.id))].map(item => item.task ? { ...item, task: item.task, finishedMs: isLive(item.task) ? item.finishedMs : nowMs } : item) }))
126 await syncTimer($)
127 }
128 return result
129 })
130
131 on('ui.open', { id: 'pi-handoff' }, async ($, e, next) => {
132 const result = await next(e)
133 void poll($).catch(() => undefined)
134 return result
135 })
136}
137
138export const handoffAtom = handoff
139export const progressAtom = progress
140hooks/history.tsx 272 lines1import { atom, read, update, type EngineInterface, type Register } from 'claude-code'
2
3import type { HistoryState, PiProgress } from '../types'
4import { finalMessage, historyRowsPage, leftReview, type HistoryFilter, type HistoryUsage, truncateCommand } from './history'
5import { focusRing, moveTo, type Motion } from './motion'
6import { FOCUS_ACTION, FOCUS_REFUSED, JUMP_KEYS, nextPane, PANE_TITLES, switchSteps } from './pane-nav'
7import { emptyProgress, fold, sessionDir, sessionFileName } from './pisession'
8import { isPiDispatch, parsePiCommand, parseStatus, type Task } from './pueue'
9import { PALETTE } from './palette'
10import { parsePending, pendingRecordFor, reviewState, type PendingReview, type ReviewState } from './review'
11import type { HandoffState } from './handoff.tsx'
12
13const history = atom({ plugin: 'session-band', key: 'history' } as const, {
14 tasks: [], reviews: {}, usage: {}, leftReviews: {}, filter: 'all', limit: 50, open: false, available: true,
15} satisfies HistoryState)
16const handoff = atom({ plugin: 'session-band', key: 'handoff' } as const, { tasks: [], available: true } satisfies HandoffState)
17let timer: { cancel(): void } | undefined
18let refreshing = false
19
20export const HISTORY_LEGEND = '✓ success · ✓ review · ✗ exit · ✗ killed'
21const pageSize = 50
22const finishedPi = (task: Task) => isPiDispatch(task.command) && ['Done', 'Failed', 'Killed'].includes(task.state)
23const usageKey = (task: Task, sessionId: string) => `${task.cwd}\u0000${sessionId}`
24const resultText = (task: Task) => {
25 if (task.state === 'Killed') return 'killed'
26 if (task.state === 'Failed') return `exit ${task.exit ?? '?'}`
27 return 'success'
28}
29
30const historyText = (row: ReturnType<typeof historyRowsPage>[number], columns: number): string => {
31 const fields: { name?: 'repo' | 'usage' | 'model'; text: string }[] = [
32 { text: row.style.result }, { text: `#${row.task.id}` }, { text: row.label },
33 ...(row.modelEffort ? [{ name: 'model' as const, text: row.modelEffort }] : []),
34 { text: row.duration }, { text: row.finished }, { name: 'repo', text: row.repo }, { name: 'usage', text: row.usage },
35 ...(row.review ? [{ text: row.review }] : []),
36 ]
37 const joined = () => fields.map(field => field.text).join(' · ')
38 for (const name of ['repo', 'usage', 'model'] as const) {
39 if (joined().length <= columns) break
40 const index = fields.findIndex(field => field.name === name)
41 if (index >= 0) fields.splice(index, 1)
42 }
43 return joined()
44}
45
46async function reviewRoot($: EngineInterface, cwd: string): Promise<string> {
47 const result = await $.process.run(['git', '-C', cwd, 'rev-parse', '--show-toplevel']).catch(() => undefined)
48 return result?.exitCode === 0 && result.stdout.trim() ? result.stdout.trim() : cwd
49}
50
51async function reviewFor($: EngineInterface, task: Task, tracked: HandoffState['tasks'][number] | undefined): Promise<ReviewState> {
52 const root = `${await reviewRoot($, task.cwd)}/.pi/agent-review`
53 const files = await $.fs.list(`${root}/pending`).catch(() => [])
54 const records: PendingReview[] = []
55 for (const file of files) {
56 if (file.kind !== 'file') continue
57 const match = file.name.match(/^(.+)\.(json|processing)$/)
58 if (!match) continue
59 const runId = match[1]
60 const parsed = parsePending(await $.fs.read(`${root}/pending/${file.name}`).catch(() => ''))
61 if (parsed) records.push(parsed)
62 else if (match[2] === 'processing' && runId) records.push({ runId, files: [] })
63 }
64 const current = pendingRecordFor(tracked ?? { task }, records)
65 const runId = tracked?.runId ?? current?.runId
66 let decision: unknown
67 if (runId) {
68 try { decision = JSON.parse(await $.fs.read(`${root}/decisions/${runId}.json`)) } catch { /* absent decisions are normal */ }
69 }
70 return reviewState(current, decision)
71}
72
73const logKey = (task: Task) => `${task.id}:${task.endMs ?? 0}`
74
75// Read once per finished Failed(1) task, whose log is final: only the log still shows that the run
76// left a review after the review is resolved. A failed read is not cached, so it is retried.
77async function logLeftReview($: EngineInterface, task: Task): Promise<boolean | undefined> {
78 const result = await $.process.run(['pueue', 'log', String(task.id), '--json']).catch(() => undefined)
79 if (!result || result.exitCode !== 0) return undefined
80 try {
81 const entry = Object.values(JSON.parse(result.stdout) as Record<string, { output?: unknown }>)[0]
82 return leftReview(typeof entry?.output === 'string' ? entry.output : '')
83 } catch { return undefined }
84}
85
86async function refresh($: EngineInterface) {
87 if (refreshing || !(await read($, history)).open) return
88 refreshing = true
89 try {
90 const result = await $.process.run(['pueue', 'status', '--json'])
91 if (result.exitCode !== 0) {
92 await update($, history, state => ({ ...state, available: false }))
93 return
94 }
95 const tasks = parseStatus(result.stdout).filter(finishedPi)
96 const tracked = await read($, handoff)
97 const trackedById = new Map(tracked.tasks.map(task => [task.id, task]))
98 const reviews = Object.fromEntries(await Promise.all(tasks.map(async task => [task.id, await reviewFor($, task, trackedById.get(task.id))] as const)))
99 const known = (await read($, history)).leftReviews
100 const unchecked = tasks.filter(task => task.state === 'Failed' && task.exit === 1 && known[logKey(task)] === undefined)
101 const checked = (await Promise.all(unchecked.map(async task => [logKey(task), await logLeftReview($, task)] as const)))
102 .filter((entry): entry is readonly [string, boolean] => entry[1] !== undefined)
103 await update($, history, state => ({ ...state, tasks, reviews, leftReviews: { ...state.leftReviews, ...Object.fromEntries(checked) }, available: true }))
104 // A Continue appends to a finished run's session; the tick, not a redraw, picks that up.
105 for (const task of tasks) void loadUsage($, task, true)
106 } finally {
107 refreshing = false
108 }
109}
110
111async function syncTimer($: EngineInterface) {
112 const open = (await read($, history)).open
113 if (open && !timer) timer = $.clock.every(10_000, () => { void refresh($) })
114 if (!open && timer) { timer.cancel(); timer = undefined }
115}
116
117const sessionUsage = (task: Task, cache: HistoryState['usage']): HistoryUsage | undefined => {
118 const sessionId = parsePiCommand(task.command).sessionId
119 if (!sessionId) return undefined
120 const entry = cache[usageKey(task, sessionId)]
121 return entry ? { tokens: entry.tokens, cost: entry.cost, loading: entry.loading, available: entry.available } : { loading: true }
122}
123
124const finalMessageLabel = (cache: HistoryState['usage'][string] | undefined): string => {
125 if (cache?.loading) return '…'
126 return cache?.tail ? finalMessage(cache.tail) ?? 'n/a' : 'n/a'
127}
128
129export const tailChunkArgv = (path: string, offset: number): string[] =>
130 ['sh', '-c', 'tail -c "+$1" "$2" | head -c 1048576', 'pi-history-tail', String(offset + 1), path]
131
132const inFlight = new Set<string>()
133
134// Every write here redraws the pane, and a redraw calls this again, so a call writes only when it
135// has something new: a redraw (`revalidate` false) starts only a row's first load, and the
136// refresh tick re-checks loaded rows, writing nothing while the session file is unchanged.
137async function loadUsage($: EngineInterface, task: Task, revalidate = false) {
138 const sessionId = parsePiCommand(task.command).sessionId
139 if (!sessionId) return
140 const key = usageKey(task, sessionId)
141 // Claimed before the read, so a call cannot act on a read taken before another call's write.
142 if (inFlight.has(key)) return
143 inFlight.add(key)
144 let current: HistoryState['usage'][string] | undefined
145 try {
146 current = (await read($, history)).usage[key]
147 if (current && !revalidate) return
148 const home = await $.env.get('HOME')
149 if (!home) throw new Error('HOME unavailable')
150 const directory = `${home}/.pi/agent/sessions/${sessionDir(task.cwd)}`
151 const files = await $.fs.list(directory)
152 const file = files.find(item => item.kind === 'file' && sessionFileName(sessionId).test(item.name))
153 if (!file) throw new Error('session file unavailable')
154 const path = `${directory}/${file.name}`
155 const stat = await $.fs.stat(path)
156 if (current?.path === path && current.size === stat.size && current.mtimeMs === stat.mtimeMs) return
157 let offset = 0
158 let progress: PiProgress = emptyProgress()
159 let tail = ''
160 while (offset < stat.size) {
161 const result = await $.process.run(tailChunkArgv(path, offset))
162 if (result.exitCode !== 0 || result.stdout.length === 0) break
163 progress = fold(progress, result.stdout)
164 tail = `${tail}${result.stdout}`.slice(-1_048_576)
165 offset += new TextEncoder().encode(result.stdout).byteLength
166 }
167 await update($, history, state => ({
168 ...state,
169 usage: { ...state.usage, [key]: { path, size: stat.size, mtimeMs: stat.mtimeMs, tokens: progress.tokens, cost: progress.cost, tail, loading: false, available: true } },
170 }))
171 } catch {
172 if (current?.available === false) return
173 await update($, history, state => ({ ...state, usage: { ...state.usage, [key]: { ...state.usage[key], loading: false, available: false } } }))
174 } finally {
175 inFlight.delete(key)
176 }
177}
178
179/** j/k/g: select the history row the motion lands on and put the focus ring on it. */
180async function move($: EngineInterface, ids: readonly number[], current: number | undefined, motion: Motion) {
181 const to = moveTo(ids, current, motion)
182 if (to === undefined) return
183 await update($, history, value => ({ ...value, selectedId: to }))
184 await focusRing($, 'pi-history', `pi-hist-${to}`)
185}
186
187// `$` cannot cross an import, so this pane runs pane-nav's switch itself.
188const goTo = async ($: EngineInterface, to: string | undefined) => {
189 for (const s of switchSteps('pi-history', to)) await ('close' in s ? $.ui.close({ id: s.close }) : $.ui.open({ id: s.open, title: s.title, focus: s.focus }))
190}
191const cycle = async ($: EngineInterface, step: 1 | -1) => goTo($, nextPane((await $.ui.panes()).map(pane => pane.id), 'pi-history', step))
192
193// Keep engine calls local: `$` cannot cross an import.
194async function focusSelf($: EngineInterface) {
195 if ((await $.prompt.read()).text.trim()) {
196 await $.ui.toast(FOCUS_REFUSED)
197 return
198 }
199 await $.ui.open({ id: 'pi-history', title: PANE_TITLES['pi-history'], focus: true })
200 if (!(await $.ui.panes()).some(pane => pane.id === 'pi-history' && pane.isFocused)) await $.ui.toast(FOCUS_REFUSED)
201}
202
203export const register: Register = on => {
204 on('command.run', { command: 'pi-history' }, async ($, _e, _next) => {
205 await $.ui.open({ id: 'pi-history', title: 'Pi history', focus: true })
206 return { text: 'Pi history opened.' }
207 })
208
209 on('ui.open', async ($, e, next) => {
210 const result = await next(e)
211 if (e.id === 'pi-history') {
212 await update($, history, state => ({ ...state, open: true }))
213 await refresh($)
214 await syncTimer($)
215 }
216 return result
217 })
218
219 on('ui.close', async ($, e, next) => {
220 const result = await next(e)
221 if (e.id === 'pi-history' && !('deny' in result)) {
222 await update($, history, state => ({ ...state, open: false }))
223 await syncTimer($)
224 }
225 return result
226 })
227
228 on('ui.render', { component: 'Pane', requestId: 'pi-history' }, async ($, e, _next) => {
229 const { Box, Text, Button } = $.ui.resolve(e)
230 const [state, nowMs] = await Promise.all([read($, history), $.clock.now()])
231 const selected = state.selectedId
232 const usage = Object.fromEntries(state.tasks.map(task => [task.id, sessionUsage(task, state.usage)]))
233 const rows = historyRowsPage(state.tasks, state.reviews, usage, nowMs, state.filter, state.limit, new Set(state.tasks.filter(task => state.leftReviews[logKey(task)]).map(task => task.id)))
234 const task = rows.find(row => row.task.id === selected)?.task ?? rows[0]?.task
235 const selectedSession = task ? parsePiCommand(task.command).sessionId : undefined
236 const selectedCache = task && selectedSession ? state.usage[usageKey(task, selectedSession)] : undefined
237 for (const row of rows) void loadUsage($, row.task)
238 if (task && !rows.some(row => row.task.id === task.id)) void loadUsage($, task)
239 const filters: HistoryFilter[] = ['all', 'done', 'failed', 'killed']
240 const ids = rows.map(row => row.task.id)
241 return <Box flexDirection="column">
242 <Text>Pi history</Text>
243 {/* Hotkeys, not hints: a key the pane does not bind falls through to the composer. */}
244 <Box flexDirection="row" flexWrap="wrap" columnGap={2} marginBottom={1}>
245 <Button key="pi-history-key-down" plain dimColor hotkey="j" label="down" onPress={() => void move($, ids, task?.id, 'down')} />
246 <Button key="pi-history-key-up" plain dimColor hotkey="k" label="up" onPress={() => void move($, ids, task?.id, 'up')} />
247 <Button key="pi-history-key-top" plain dimColor hotkey="g" label="top" onPress={() => void move($, ids, task?.id, 'top')} />
248 <Button key="pi-history-key-reload" plain dimColor hotkey="r" label="reload" onPress={() => void refresh($)} />
249 <Button key="pi-history-key-prev" plain dimColor hotkey="b" label="prev" onPress={() => void cycle($, -1)} />
250 <Button key="pi-history-key-next" plain dimColor hotkey="f" label="next" onPress={() => void cycle($, 1)} />
251 <Button key="pi-history-key-quit" plain dimColor hotkey="q" label="close" onPress={() => void $.ui.close({ id: 'pi-history' })} />
252 <Button key="pi-history-key-focus" plain dimColor action={FOCUS_ACTION} label="ctrl+x b" onPress={() => void focusSelf($)} />
253 {JUMP_KEYS.map(j => <Button key={`pi-history-key-jump-${j.key}`} plain dimColor hotkey={j.key} label={j.label} onPress={() => void (j.id === 'pi-history' ? undefined : goTo($, j.id))} />)}
254 </Box>
255 <Box><Text color={PALETTE.green}>✓ success</Text><Text color={PALETTE.yellow}> · ✓ review</Text><Text color={PALETTE.red}> · ✗ exit</Text><Text color={PALETTE.mauve}> · ✗ killed</Text></Box>
256 <Box flexDirection="row" columnGap={2} marginBottom={1}>{filters.map(filter => <Button key={`pi-history-${filter}`} plain label={filter === state.filter ? `[${filter}]` : filter} onPress={() => void update($, history, value => ({ ...value, filter, limit: pageSize }))} />)}</Box>
257 {!state.available && <Text color={PALETTE.red}>pueue daemon unavailable</Text>}
258 {rows.length === 0 && <Text>No completed Pi hand-offs in the last 7 days.</Text>}
259 {rows.map(row => <Box key={`pi-history-row-${row.task.id}`} flexDirection="row">
260 <Text color={PALETTE[row.style.tone]}>{row.style.glyph}</Text>
261 <Button key={`pi-hist-${row.task.id}`} plain label={` ${row.task.id === task?.id ? '› ' : ' '}${historyText(row, Math.max(1, e.props.bodyColumns - 4))}`} onPress={() => void update($, history, value => ({ ...value, selectedId: row.task.id }))} />
262 </Box>)}
263 {rows.length === state.limit && <Button key="pi-history-older" onPress={() => void update($, history, value => ({ ...value, limit: value.limit + pageSize }))}>show older</Button>}
264 {task && <Box flexDirection="column">
265 <Text>{`\nStart: ${task.startMs ? new Date(task.startMs).toISOString() : 'n/a'}\nEnd: ${task.endMs ? new Date(task.endMs).toISOString() : 'n/a'}\nResult: ${resultText(task)}\nWorking directory: ${task.cwd}\nModel: ${[parsePiCommand(task.command).model, parsePiCommand(task.command).effort].filter(Boolean).join(':') || 'n/a'}\nLabel: ${task.label ?? 'n/a'}\nCommand: ${truncateCommand(task.command)}`}</Text>
266 <Text>{`Final message:\n${finalMessageLabel(selectedCache)}`}</Text>
267 </Box>}
268 </Box>
269 })
270}
271
272hooks/pane.tsx 528 lines1import { atom, read, update, type EngineInterface, type Register } from 'claude-code'
2
3import { dispatchCommand, parseAddResult, parsePiCommand, parseStatus } from './pueue'
4import { controlArgv, eligible, holdArgv, parsePiArgs, PS_ARGV, releaseArgv, resolveTargets, signalGroupArgv, stopArgvs, strayGroups, type ControlAction, type Targets } from './controls'
5import { monitorRows, selectStale, type MonitorRow, type StaleSelection, type TrackedTask } from './handoff'
6import type { HandoffState } from './handoff.tsx'
7import { focusRing, moveTo, type Motion } from './motion'
8import { FOCUS_ACTION, FOCUS_REFUSED, JUMP_KEYS, nextPane, PANE_TITLES, switchSteps } from './pane-nav'
9import { PALETTE } from './palette'
10import type { PiProgress, TranscriptEntry } from './pisession'
11import { parsePending, pendingRecordFor, type PendingReview } from './review'
12import { editRefusal, killNote, parseEdit, readdArgv } from './lifecycle'
13
14const handoff = atom({ plugin: 'session-band', key: 'handoff' } as const, { tasks: [] as TrackedTask[], available: true } satisfies HandoffState)
15const progress = atom({ plugin: 'session-band', key: 'progress' } as const, {} as Record<number, PiProgress>)
16let rejecting: string | undefined
17type StaleDryRun = { selection: StaleSelection; atMs: number }
18
19let stale: StaleDryRun | undefined
20
21const complete = (task: TrackedTask) => ['Done', 'Failed', 'Killed'].includes(task.task?.state ?? '')
22// The default prefers tasks with a Monitor row (`rowIds`), so the marked row and the controls
23// agree; with no rows it falls back to any open task, so a long-finished one can still Continue.
24export const selectedTask = (tasks: readonly TrackedTask[], selectedId?: number, rowIds?: readonly number[]): TrackedTask | undefined => {
25 const open = tasks.filter(task => !task.dismissed)
26 const shown = rowIds ? open.filter(task => rowIds.includes(task.id)) : open
27 const newest = (list: readonly TrackedTask[]) => [...list].sort((left, right) => right.addedMs - left.addedMs)[0]
28 return open.find(task => task.id === selectedId)
29 ?? newest(shown.filter(task => task.task?.state === 'Running'))
30 ?? newest(shown)
31 ?? newest(open)
32}
33const taskLabel = (task: TrackedTask) => `pi#${task.id} ${task.task?.state ?? 'Other'}${task.label ? ` · ${task.label}` : ''}`
34
35type MonitorField = 'modelEffort' | 'activity' | 'tokens' | 'cost'
36
37export const monitorText = (row: MonitorRow, columns: number): string => {
38 const fields: { name?: MonitorField; text: string }[] = [
39 { text: `${row.glyph} #${row.id}` },
40 ...(row.modelEffort ? [{ name: 'modelEffort' as const, text: row.modelEffort }] : []),
41 { text: row.elapsed },
42 { name: 'activity', text: row.activity },
43 { name: 'tokens', text: row.tokens },
44 { name: 'cost', text: row.cost },
45 ...(row.label ? [{ text: row.label }] : []),
46 ]
47 const gap = ' '
48 const joined = () => fields.map(field => field.text).join(gap)
49 // The model always stays: it is how a row says which tier is working. Activity shrinks instead.
50 for (const name of ['cost', 'tokens'] as const) {
51 if (joined().length <= columns) break
52 const index = fields.findIndex(field => field.name === name)
53 if (index >= 0) fields.splice(index, 1)
54 }
55 const activity = fields.find(field => field.name === 'activity')
56 if (activity && joined().length > columns) {
57 const others = fields.filter(field => field !== activity).map(field => field.text).join(gap)
58 const available = Math.max(1, columns - others.length - (others ? gap.length : 0))
59 activity.text = activity.text.length <= available ? activity.text : `${activity.text.slice(0, Math.max(0, available - 1))}…`
60 }
61 return joined()
62}
63
64export const selectedProgress = (tasks: readonly TrackedTask[], selectedId: number | undefined, allProgress: Readonly<Record<number, PiProgress>>, rowIds?: readonly number[]): PiProgress | undefined => {
65 const task = selectedTask(tasks, selectedId, rowIds)
66 return task ? allProgress[task.id] : undefined
67}
68
69export const hasMonitorRows = (rows: readonly MonitorRow[]): boolean => rows.length > 0
70
71async function open($: EngineInterface) {
72 await $.ui.open({ id: 'pi-handoff', title: 'Pi hand-off', focus: true })
73}
74
75const describeRefused = (refused: Targets['refused']) =>
76 refused.length ? ` Skipped ${refused.map(item => `#${item.id} (${item.reason})`).join(', ')}.` : ''
77
78/** Signal the detached tool groups of the given started tasks. The tree is intact while stopped, so strays still trace. */
79async function signalStrays($: EngineInterface, ids: readonly number[], signal: 'STOP' | 'CONT') {
80 const tasks = parseStatus((await $.process.run(['pueue', 'status', '--json'])).stdout)
81 const commands = tasks.filter(task => ids.includes(task.id) && task.state !== 'Queued').map(task => task.command)
82 if (commands.length === 0) return
83 for (const pgid of strayGroups((await $.process.run(PS_ARGV)).stdout, commands)) await $.process.run(signalGroupArgv(signal, pgid))
84}
85
86/** Run one /pi control action, updating the tracked list for `rm`; returns the reply text. */
87export async function runControl($: EngineInterface, action: ControlAction, ids: readonly number[], group: string): Promise<string> {
88 // Each pueue call is checked: the reply must never claim what pueue refused.
89 const run = async (argv: string[]) => {
90 const result = await $.process.run(argv)
91 if (result.exitCode === 0) return undefined
92 return `${argv.slice(0, 2).join(' ')} failed: ${(result.stderr || result.stdout).trim().split('\n')[0] || `exit ${result.exitCode}`}`
93 }
94 const list = (items: readonly number[]) => items.map(id => `#${id}`).join(' ')
95 if (action === 'release') return (await run(releaseArgv(group))) ?? `Queue ${group} released.`
96 if (ids.length === 0) return 'Nothing to do.'
97 if (action === 'kill' || action === 'hold') {
98 if (action === 'hold') {
99 const failed = await run(holdArgv(group))
100 if (failed) return `${failed}. Nothing was killed.`
101 }
102 const status = await $.process.run(['pueue', 'status', '--json'])
103 const tasks = parseStatus(status.stdout)
104 const states = new Map(tasks.map(task => [task.id, task.state]))
105 // Snapshot before the kill: afterwards the strays hang off launchd and no longer trace to the task.
106 const commands = tasks.filter(task => ids.includes(task.id) && task.state !== 'Queued').map(task => task.command)
107 const strays = commands.length ? strayGroups((await $.process.run(PS_ARGV)).stdout, commands) : []
108 for (const argv of stopArgvs(ids, states)) {
109 const failed = await run(argv)
110 if (failed) return failed
111 }
112 // A group already gone exits 1 ("No such process"); nothing is left to kill then.
113 for (const pgid of strays) await $.process.run(signalGroupArgv('KILL', pgid))
114 const queued = ids.filter(id => states.get(id) === 'Queued')
115 const started = ids.filter(id => states.get(id) !== 'Queued')
116 const stopped = [started.length ? `Killed ${list(started)}` : '', queued.length ? `removed queued ${list(queued)}` : ''].filter(Boolean).join(', ')
117 return action === 'hold' ? `Held queue ${group}. ${stopped}. Run /pi release to start the queue again.` : `${stopped}.`
118 }
119 const failed = await run(controlArgv(action, ids))
120 if (failed) return failed
121 if (action === 'pause' || action === 'resume') await signalStrays($, ids, action === 'pause' ? 'STOP' : 'CONT')
122 if (action === 'rm') await update($, handoff, state => ({ ...state, tasks: state.tasks.filter(item => !ids.includes(item.id)) }))
123 const verb = { pause: 'Paused', resume: 'Resumed', rm: 'Removed' }[action]
124 return `${verb} ${list(ids)}.`
125}
126
127export const CONFIRM_MS = 60_000
128
129/** Record a pending kill/hold in the handoff atom; the pane draws the confirm row from it. */
130export async function askConfirm($: EngineInterface, action: 'kill' | 'hold', ids: number[]) {
131 const atMs = await $.clock.now()
132 await update($, handoff, state => ({ ...state, confirm: { action, ids, atMs } }))
133}
134
135/** Stop: the group starts nothing new; running tasks finish and queued ones wait. /pi release starts it again. */
136async function stopQueue($: EngineInterface, group: string) {
137 const result = await $.process.run(holdArgv(group))
138 await $.ui.toast(result.exitCode === 0
139 ? `Stopped queue ${group}; running tasks finish, queued tasks wait. Run /pi release to start it again.`
140 : `pueue pause failed: ${(result.stderr || result.stdout).trim().split('\n')[0] || `exit ${result.exitCode}`}`)
141}
142
143/** Read-only: how much each killed task's worktree holds uncommitted. The band never reverts a worktree. */
144async function uncommitted($: EngineInterface, tasks: readonly TrackedTask[], ids: readonly number[]): Promise<string> {
145 const notes = [] as string[]
146 for (const cwd of new Set(tasks.filter(task => ids.includes(task.id)).map(task => task.cwd))) {
147 const status = await $.process.run(['git', '-C', cwd, 'status', '--porcelain']).catch(() => undefined)
148 if (status?.exitCode === 0) notes.push(killNote(cwd, status.stdout))
149 }
150 return notes.join('')
151}
152
153/** Edit = remove and re-add with a new model and label. Remove goes first: pueue refuses to remove a started task, so a race cannot run it twice. */
154async function editTask($: EngineInterface, task: TrackedTask, text: string) {
155 const edit = parseEdit(text)
156 if (!edit) return
157 const live = parseStatus((await $.process.run(['pueue', 'status', '--json'])).stdout).find(item => item.id === task.id)
158 const refused = editRefusal(live?.state)
159 if (refused || !live) { await $.ui.toast(refused ?? 'Edit refused.'); return }
160 const removed = await $.process.run(controlArgv('rm', [task.id]))
161 if (removed.exitCode !== 0) { await $.ui.toast(`Edit refused: pueue would not remove #${task.id}.`); return }
162 const label = edit.label ?? task.label ?? `edit-${task.id}`
163 const added = await $.process.run(readdArgv(live, edit.model, label), { cwd: live.cwd })
164 const id = parseAddResult(added.stdout)
165 await update($, handoff, state => ({ ...state, selectedId: id ?? state.selectedId, tasks: state.tasks.flatMap(item => item.id !== task.id ? [item] : id === undefined ? [] : [{ ...item, id, label, task: { ...live, id, label } }]) }))
166 await $.ui.toast(id === undefined
167 ? `Removed #${task.id}, but the re-add failed: ${(added.stderr || added.stdout).trim() || `exit ${added.exitCode}`}`
168 : `Edited #${task.id}: re-added as #${id} with ${edit.model}.`)
169}
170
171/** Re-read state, act only on ids still eligible; an expired or finished confirm does nothing. */
172export async function confirmNow($: EngineInterface) {
173 const state = await read($, handoff)
174 const confirm = state.confirm
175 await update($, handoff, value => ({ ...value, confirm: undefined }))
176 if (!confirm) return
177 if ((await $.clock.now()) - confirm.atMs > CONFIRM_MS) { await $.ui.toast('Confirmation expired; press again.'); return }
178 const status = await $.process.run(['pueue', 'status', '--json'])
179 const pueue = parseStatus(status.stdout)
180 const { ids, refused } = resolveTargets(confirm.action, confirm.ids, state.tasks, pueue)
181 if (ids.length === 0) { await $.ui.toast(`Nothing to ${confirm.action}.${describeRefused(refused)}`); return }
182 const group = pueue.find(task => ids.includes(task.id))?.group ?? 'default'
183 const reply = await runControl($, confirm.action, ids, group)
184 await $.ui.toast(`${reply}${await uncommitted($, state.tasks, ids)}${describeRefused(refused)}`)
185}
186
187/** j/k/g: select the row the motion lands on and put the focus ring on it, so the two agree. */
188async function move($: EngineInterface, rowIds: readonly number[], current: number | undefined, motion: Motion) {
189 const to = moveTo(rowIds, current, motion)
190 if (to === undefined) return
191 await update($, handoff, value => ({ ...value, selectedId: to }))
192 await focusRing($, 'pi-handoff', `pi-row-${to}`)
193}
194
195async function dismiss($: EngineInterface, task: TrackedTask) {
196 await update($, handoff, state => ({ ...state, tasks: state.tasks.map(item => item.id === task.id ? { ...item, dismissed: true } : item) }))
197}
198
199export const continueModel = (task: TrackedTask, pi: PiProgress | undefined): string | undefined => {
200 if (pi?.model) return [pi.model, pi.effort].filter(Boolean).join(':')
201 // Quote-aware: a Continue's own command quotes the model, which a plain regex would keep.
202 const parsed = task.task ? parsePiCommand(task.task.command) : {}
203 return parsed.model ? [parsed.model, parsed.effort].filter(Boolean).join(':') : undefined
204}
205
206export const continueArgv = (task: TrackedTask, model: string, path: string): string[] =>
207 ['pueue', 'add', '-i', '--print-task-id', '--label', task.label ?? `continue-${task.id}`, '--', dispatchCommand(model, task.sessionId ?? '', path)]
208
209export const continuePath = (tmp: string, sessionId: string, nowMs = Date.now()): string =>
210 `${tmp.replace(/\/$/, '')}/pi-continue-${sessionId.replace(/[^A-Za-z0-9_-]/g, '-')}-${nowMs}.md`
211
212async function continueTask($: EngineInterface, task: TrackedTask, pi: PiProgress | undefined, text: string) {
213 if (!task.sessionId || text.trim() === '') return
214 const model = continueModel(task, pi)
215 if (!model) { await $.ui.toast('Cannot continue: model unknown'); return }
216 const tmp = await $.env.get('TMPDIR') ?? '/tmp'
217 const path = continuePath(tmp, task.sessionId)
218 await $.fs.write(path, text)
219 const label = task.label ?? `continue-${task.id}`
220 const result = await $.process.run(continueArgv(task, model, path))
221 const id = parseAddResult(result.stdout)
222 if (id === undefined) return
223 const status = await $.process.run(['pueue', 'status', '--json'])
224 const queued = parseStatus(status.stdout).find(item => item.id === id)
225 const addedMs = await $.clock.now()
226 await update($, handoff, state => ({ ...state, tasks: [...state.tasks, { id, cwd: task.cwd, addedMs, task: queued, sessionId: task.sessionId, label }] }))
227}
228
229async function reviewRoot($: EngineInterface, cwd: string): Promise<string> {
230 const result = await $.process.run(['git', '-C', cwd, 'rev-parse', '--show-toplevel']).catch(() => undefined)
231 return result?.exitCode === 0 && result.stdout.trim() ? result.stdout.trim() : cwd
232}
233
234async function pendingFor($: EngineInterface, task: TrackedTask): Promise<PendingReview | undefined> {
235 const dir = `${await reviewRoot($, task.cwd)}/.pi/agent-review/pending`
236 const files = await $.fs.list(dir).catch(() => [])
237 const records = [] as PendingReview[]
238 for (const file of files) {
239 if (file.kind !== 'file' || !file.name.endsWith('.json')) continue
240 const pending = parsePending(await $.fs.read(`${dir}/${file.name}`).catch(() => ''))
241 if (pending) records.push(pending)
242 }
243 return pendingRecordFor(task, records)
244}
245
246export const matchingSocket = (repo: string, sockets: readonly { path: string; cwd: string }[]): string | undefined =>
247 sockets.find(socket => socket.cwd === repo || socket.cwd.startsWith(`${repo}/`))?.path
248export const reviewSplitArgv = (repo: string): string[] => ['herdr', 'pane', 'split', '--current', '--direction', 'right', '--cwd', repo]
249export const reviewPaneRunArgv = (pane: string, socket: string): string[] => ['herdr', 'pane', 'run', pane, 'nvim', '--listen', socket]
250export const approvalAction = (stdout: string, _stderr?: string): 'approved' | 'open-review' | 'refused' | 'unavailable' => {
251 try {
252 const reply = JSON.parse(stdout.trim()) as { ok?: boolean; reason?: string }
253 if (reply.ok) return 'approved'
254 return reply.reason === 'tree-changed' ? 'open-review' : 'refused'
255 } catch { return 'unavailable' }
256}
257
258async function waitForSocket($: EngineInterface, socket: string): Promise<boolean> {
259 if (await $.fs.exists(socket)) return true
260 return new Promise(resolve => {
261 let attempts = 0
262 const timer = $.clock.every(100, async () => {
263 const exists = await $.fs.exists(socket)
264 attempts += 1
265 if (exists || attempts >= 30) {
266 timer.cancel()
267 resolve(exists)
268 }
269 })
270 })
271}
272
273async function socketFor($: EngineInterface, repo: string): Promise<string> {
274 const tmp = await $.env.get('TMPDIR') ?? '/tmp'
275 const user = await $.env.get('USER') ?? 'user'
276 const found = await $.process.run(['fd', '-HI', '--type', 's', '^nvim\\..*\\.0$', `${tmp.replace(/\/$/, '')}/nvim.${user}`]).catch(() => ({ stdout: '' }))
277 const candidates = [] as { path: string; cwd: string }[]
278 for (const path of found.stdout.split('\n').filter(Boolean)) {
279 const cwd = await $.process.run(['nvim', '--server', path, '--remote-expr', 'getcwd()'])
280 if (cwd.exitCode === 0) candidates.push({ path, cwd: cwd.stdout.trim() })
281 }
282 const existing = matchingSocket(repo, candidates)
283 if (existing) return existing
284 const split = await $.process.run(reviewSplitArgv(repo))
285 let pane: string | undefined
286 try { pane = JSON.parse(split.stdout).result?.pane?.pane_id as string | undefined } catch { /* invalid herdr output is unavailable */ }
287 if (!pane) throw new Error('could not open review pane')
288 const socket = `${tmp.replace(/\/$/, '')}/nvim.${user}/pi-review-${Date.now()}.sock`
289 await $.process.run(reviewPaneRunArgv(pane, socket))
290 if (await waitForSocket($, socket)) return socket
291 throw new Error('review Neovim did not start')
292}
293
294export const reviewRemoteArgv = (socket: string, command: 'AgentReview' | 'AgentReviewRejectAll', runId?: string): string[] =>
295 ['nvim', '--server', socket, '--remote-send', `<C-\\><C-N>:${command}${command === 'AgentReviewRejectAll' && runId ? ` ${runId}` : ''}<CR>`]
296export const approveArgv = (home: string, runId: string): string[] => [`${home}/dotfiles/scripts/agent-review`, 'approve', runId]
297export const needsRejectConfirm = (current: string | undefined, runId: string): boolean => current !== runId
298export const rejectToast = (exitCode: number): string =>
299 exitCode === 0 ? 'Sent Reject all to Neovim; the decision appears in the band when recorded.' : 'Could not send Reject all to Neovim.'
300
301async function openReview($: EngineInterface, task: TrackedTask, message?: string) {
302 try {
303 const socket = await socketFor($, await reviewRoot($, task.cwd))
304 await $.process.run(reviewRemoteArgv(socket, 'AgentReview'))
305 if (message) await $.ui.toast(message)
306 } catch {
307 await $.ui.toast('Could not open review.')
308 }
309}
310
311async function approve($: EngineInterface, task: TrackedTask, pending: PendingReview) {
312 const home = await $.env.get('HOME')
313 if (!home) { await $.ui.toast('Review gate not available.'); return }
314 const result = await $.process.run(approveArgv(home, pending.runId), {
315 cwd: await reviewRoot($, task.cwd),
316 timeoutMs: 60_000,
317 }).catch(() => undefined)
318 const action = result ? approvalAction(result.stdout) : 'unavailable'
319 if (action === 'unavailable') { await $.ui.toast('Review gate not available.'); return }
320 if (action === 'approved') { await $.ui.toast('Review approved.'); return }
321 let message: string | undefined
322 try { message = (JSON.parse(result!.stdout) as { message?: string }).message } catch { /* outcome was already parsed */ }
323 if (action === 'open-review') { await openReview($, task, message ?? 'Tree changed; opening review.'); return }
324 await $.ui.toast(message ?? 'Review approval refused.')
325}
326
327async function rejectAll($: EngineInterface, task: TrackedTask, runId: string, confirmed: boolean) {
328 if (!confirmed) { await $.ui.toast('Press Reject all again to confirm.'); return false }
329 try {
330 const socket = await socketFor($, await reviewRoot($, task.cwd))
331 const result = await $.process.run(reviewRemoteArgv(socket, 'AgentReviewRejectAll', runId))
332 await $.ui.toast(rejectToast(result.exitCode))
333 return result.exitCode === 0
334 } catch {
335 await $.ui.toast(rejectToast(1))
336 return false
337 }
338}
339
340const sameStaleSelection = (left: StaleSelection, right: StaleSelection) =>
341 left.tasks.length === right.tasks.length
342 && left.sessions.length === right.sessions.length
343 && left.tasks.every(task => right.tasks.some(item => item.id === task.id))
344 && left.sessions.every(session => right.sessions.some(item => item.path === session.path))
345
346export const confirmedStale = (dryRun: StaleDryRun, current: StaleSelection, nowMs: number): StaleSelection | undefined =>
347 nowMs - dryRun.atMs <= 60_000 && sameStaleSelection(dryRun.selection, current) ? current : undefined
348
349async function staleSelection($: EngineInterface, state: { tasks: TrackedTask[] }): Promise<StaleSelection> {
350 const home = await $.env.get('HOME')
351 const files = [] as { path: string; name: string; mtimeMs: number; size: number }[]
352 if (home) {
353 for (const task of state.tasks) {
354 if (!task.sessionId?.startsWith('pueue-')) continue
355 const dir = `${home}/.pi/agent/sessions/--${task.cwd.replace(/^\/+/, '').replaceAll('/', '-')}--`
356 const listed = await $.fs.list(dir).catch(() => [])
357 for (const file of listed) if (file.kind === 'file' && file.name.endsWith(`_${task.sessionId}.jsonl`)) files.push({ path: `${dir}/${file.name}`, name: file.name, mtimeMs: file.mtimeMs, size: file.size })
358 }
359 }
360 return selectStale(state.tasks, files, await $.clock.now())
361}
362
363async function cleanStale($: EngineInterface) {
364 const state = await read($, handoff)
365 const current = await staleSelection($, state)
366 const nowMs = await $.clock.now()
367 if (stale) {
368 const selected = confirmedStale(stale, current, nowMs)
369 const expired = nowMs - stale.atMs > 60_000
370 stale = undefined
371 if (!selected) { await $.ui.toast(expired ? 'Clean stale dry run expired; run it again.' : 'Clean stale selection changed; run a new dry run.'); return }
372 for (const task of selected.tasks) await $.process.run(['pueue', 'remove', String(task.id)])
373 for (const session of selected.sessions) await $.process.run(['rm', session.path])
374 const ids = new Set(selected.tasks.map(task => task.id))
375 await update($, handoff, value => ({ ...value, tasks: value.tasks.filter(task => !ids.has(task.id)) }))
376 await $.ui.toast('Pi stale hand-offs removed')
377 return
378 }
379 stale = { selection: current, atMs: nowMs }
380 await $.ui.toast(`Clean stale dry run: ${current.tasks.length} tasks, ${current.sessions.length} sessions, ${current.bytes} B. Press again to remove.`)
381}
382
383// `$` cannot cross an import, so this pane runs pane-nav's switch itself.
384const goTo = async ($: EngineInterface, to: string | undefined) => {
385 for (const s of switchSteps('pi-handoff', to)) await ('close' in s ? $.ui.close({ id: s.close }) : $.ui.open({ id: s.open, title: s.title, focus: s.focus }))
386}
387const cycle = async ($: EngineInterface, step: 1 | -1) => goTo($, nextPane((await $.ui.panes()).map(pane => pane.id), 'pi-handoff', step))
388
389// Keep engine calls local: `$` cannot cross an import.
390async function focusSelf($: EngineInterface) {
391 if ((await $.prompt.read()).text.trim()) {
392 await $.ui.toast(FOCUS_REFUSED)
393 return
394 }
395 await $.ui.open({ id: 'pi-handoff', title: PANE_TITLES['pi-handoff'], focus: true })
396 if (!(await $.ui.panes()).some(pane => pane.id === 'pi-handoff' && pane.isFocused)) await $.ui.toast(FOCUS_REFUSED)
397}
398
399export const transcriptLines = (entries: readonly TranscriptEntry[], showThinking: boolean): { key: string; text: string; dim: boolean }[] =>
400 entries.flatMap((entry, index) => {
401 if (entry.kind === 'thinking' && !showThinking) return []
402 if (entry.kind === 'thinking') return [{ key: `entry-${index}`, text: entry.text ? ` · ${entry.text}` : ' · thinking…', dim: true }]
403 if (entry.kind === 'text') return [{ key: `entry-${index}`, text: entry.text.slice(0, 280), dim: false }]
404 if (entry.kind === 'tool') return [{ key: `entry-${index}`, text: entry.text, dim: false }]
405 if (entry.kind === 'error') return [{ key: `entry-${index}`, text: `ERROR ${entry.text}`, dim: false }]
406 return entry.text.split('\n').map((line, lineIndex) => ({ key: `entry-${index}-${lineIndex}`, text: ` ↳ ${line}`, dim: true }))
407 })
408
409/** The all view: `rows` shared evenly across the tasks, one row each for its header, never fewer than 3 lines. */
410export const stackedSections = (ids: readonly number[], allProgress: Readonly<Record<number, PiProgress | undefined>>, showThinking: boolean, rows: number) => {
411 const per = Math.max(3, Math.floor(rows / Math.max(1, ids.length)) - 1)
412 return ids.map(id => ({ id, lines: transcriptLines(allProgress[id]?.entries ?? [], showThinking).slice(-per) }))
413}
414
415export const register: Register = on => {
416 on('command.run', { command: 'pi' }, async ($, e, _next) => {
417 const parsed = parsePiArgs(e.args)
418 if (parsed.kind === 'open') { await open($); return { text: 'Pi hand-off pane opened.' } }
419 if (parsed.kind === 'error') return { text: parsed.text }
420 const status = await $.process.run(['pueue', 'status', '--json'])
421 if (status.exitCode !== 0) return { text: 'pueue daemon unavailable.' }
422 const pueue = parseStatus(status.stdout)
423 const state = await read($, handoff)
424 const selected = selectedTask(state.tasks, state.selectedId)?.id
425 const { ids, refused } = resolveTargets(parsed.action, parsed.target, state.tasks, pueue, selected)
426 if (parsed.target === 'all' && parsed.action !== 'release' && ids.length > 0 && (parsed.action === 'kill' || parsed.action === 'hold')) {
427 const nowMs = await $.clock.now()
428 await update($, handoff, value => ({ ...value, confirm: { action: parsed.action, ids, atMs: nowMs } }))
429 await open($)
430 return { text: `Press Kill in the Pi hand-off pane to confirm ${parsed.action} of ${ids.map(id => `#${id}`).join(' ')}.` }
431 }
432 const group = pueue.find(task => ids.includes(task.id))?.group ?? 'default'
433 if (ids.length === 0 && parsed.action !== 'release') return { text: `Nothing to ${parsed.action}.${describeRefused(refused)}` }
434 return { text: `${await runControl($, parsed.action, ids, group)}${describeRefused(refused)}` }
435 })
436
437 on('ui.render', { component: 'Pane', requestId: 'pi-handoff' }, async ($, e, _next) => {
438 const { Box, Text, Button, Input } = $.ui.resolve(e)
439 const [state, allProgress, nowMs] = await Promise.all([read($, handoff), read($, progress), $.clock.now()])
440 const rows = monitorRows(state.tasks, allProgress, state.tasks.flatMap(item => item.task ? [item.task] : []), nowMs)
441 const rowIds = rows.map(row => row.id)
442 const task = selectedTask(state.tasks, state.selectedId, rowIds)
443 const pending = task ? await pendingFor($, task) : undefined
444 const pi = selectedProgress(state.tasks, state.selectedId, allProgress, rowIds)
445 const transcript = pi?.entries.slice(-200) ?? []
446 const confirm = state.confirm && nowMs - state.confirm.atMs <= CONFIRM_MS ? state.confirm : undefined
447 // The all view stacks every working task's transcript; the rows left after the strip and monitor are shared out.
448 const working = rowIds.flatMap(id => state.tasks.filter(item => item.id === id && (item.task?.state === 'Running' || item.task?.state === 'Paused')))
449 const sections = state.showAll && working.length > 0
450 ? stackedSections(working.map(item => item.id), allProgress, state.showThinking ?? false, e.props.scroll.bodyRows - rows.length - 8)
451 : undefined
452 return <Box flexDirection="column">
453 {state.tasks.length === 0 && <Text>No Pi hand-offs tracked in this session.</Text>}
454 {/* Hotkeys, not hints: a key the pane does not bind falls through to the composer. */}
455 <Box flexDirection="row" flexWrap="wrap" columnGap={2} marginBottom={1}>
456 <Button key="pi-key-down" plain dimColor hotkey="j" label="down" onPress={() => void move($, rowIds, task?.id, 'down')} />
457 <Button key="pi-key-up" plain dimColor hotkey="k" label="up" onPress={() => void move($, rowIds, task?.id, 'up')} />
458 <Button key="pi-key-top" plain dimColor hotkey="g" label="top" onPress={() => void move($, rowIds, task?.id, 'top')} />
459 <Button key="pi-key-insert" plain dimColor hotkey="i" label="continue" onPress={() => { if (task) void focusRing($, 'pi-handoff', 'pi-continue') }} />
460 <Button key="pi-key-reload" plain dimColor hotkey="r" label="reload" onPress={() => void open($)} />
461 <Button key="pi-key-prev" plain dimColor hotkey="b" label="prev" onPress={() => void cycle($, -1)} />
462 <Button key="pi-key-next" plain dimColor hotkey="f" label="next" onPress={() => void cycle($, 1)} />
463 <Button key="pi-key-quit" plain dimColor hotkey="q" label="close" onPress={() => void $.ui.close({ id: 'pi-handoff' })} />
464 <Button key="pi-key-focus" plain dimColor action={FOCUS_ACTION} label="ctrl+x b" onPress={() => void focusSelf($)} />
465 <Button key="pi-key-thinking" plain dimColor hotkey="t" label={state.showThinking ? 'hide thinking' : 'thinking'} onPress={() => void update($, handoff, value => ({ ...value, showThinking: !value.showThinking }))} />
466 <Button key="pi-key-all" plain dimColor hotkey="v" label={state.showAll ? 'one task' : 'all tasks'} onPress={() => void update($, handoff, value => ({ ...value, showAll: !value.showAll }))} />
467 {JUMP_KEYS.map(j => <Button key={`pi-key-jump-${j.key}`} plain dimColor hotkey={j.key} label={j.label} onPress={() => void (j.id === 'pi-handoff' ? undefined : goTo($, j.id))} />)}
468 {task && <Text dimColor>x kill s stop h hold p pause y/n confirm</Text>}
469 {(!task || complete(task)) && <Button key="pi-key-abort" plain dimColor hotkey="x" label="kill" onPress={() => undefined} />}
470 {(!task?.task || !eligible('kill', task.task.state)) && <Button key="pi-key-hold" plain dimColor hotkey="h" label="hold" onPress={() => undefined} />}
471 {(!task || complete(task)) && <Button key="pi-key-pause" plain dimColor hotkey="p" label="pause" onPress={() => undefined} />}
472 {(!task?.task || !eligible('pause', task.task.state)) && <Button key="pi-key-stop" plain dimColor hotkey="s" label="stop" onPress={() => undefined} />}
473 {!confirm && <Button key="pi-key-yes" plain dimColor hotkey="y" label="confirm" onPress={() => undefined} />}
474 {!confirm && <Button key="pi-key-no" plain dimColor hotkey="n" label="cancel" onPress={() => undefined} />}
475 </Box>
476 {confirm && <Box flexDirection="row" columnGap={1}>
477 <Text color={PALETTE.red}>{`${confirm.action === 'hold' ? 'Hold queue and kill' : 'Kill'} ${confirm.ids.map(id => `#${id}`).join(' ')}?`}</Text>
478 <Button key="pi-confirm-ok" hotkey="y" onPress={() => void confirmNow($)}>{confirm.action === 'hold' ? 'Hold + kill' : 'Kill'}</Button>
479 <Button key="pi-confirm-cancel" hotkey="n" onPress={() => void update($, handoff, value => ({ ...value, confirm: undefined }))}>Cancel</Button>
480 </Box>}
481 {hasMonitorRows(rows) && <Box flexDirection="column">
482 <Text>Monitor</Text>
483 {rows.map(row => {
484 const selected = row.id === task?.id
485 const idle = row.idle?.text
486 const columns = e.props.bodyColumns - (idle ? idle.length + 1 : 0) - 2
487 // The row is its only focus stop, so ↑↓ move one row; x/p act on the selected row.
488 return <Box key={`pi-monitor-${row.id}`} flexDirection="row">
489 <Button key={`pi-row-${row.id}`} plain label={`${selected ? '› ' : ' '}${monitorText(row, columns)}`} onPress={() => void update($, handoff, value => ({ ...value, selectedId: row.id }))} />
490 {idle && <Text color={PALETTE[row.idle!.tone]}>{` ${idle}`}</Text>}
491 </Box>
492 })}
493 </Box>}
494 {sections && working.map((item, index) => <Box key={`pi-all-${item.id}`} flexDirection="column">
495 <Text>{`\n── ${taskLabel(item)}${allProgress[item.id]?.lastActivity ? ` · ${allProgress[item.id]!.lastActivity}` : ''}`}</Text>
496 {sections[index]!.lines.map(line => <Text key={`${item.id}-${line.key}`} dimColor={line.dim}>{line.text}</Text>)}
497 </Box>)}
498 {!sections && task && <Text>{`\n${taskLabel(task)}${pi?.lastActivity ? ` · ${pi.lastActivity}` : ''}\n${pi ? `${pi.tokens} tokens · $${pi.cost.toFixed(3)}` : 'usage n/a'}`}</Text>}
499 {!sections && transcriptLines(transcript, state.showThinking ?? false).map(line => <Text key={line.key} dimColor={line.dim}>{line.text}</Text>)}
500 {task && <Box flexDirection="row" flexWrap="wrap" columnGap={1} marginTop={1}>
501 {!complete(task) && <Button key="pi-abort" hotkey="x" onPress={() => void askConfirm($, 'kill', [task.id])}>Abort</Button>}
502 {task.task && eligible('kill', task.task.state) && <Button key="pi-hold" hotkey="h" onPress={() => void askConfirm($, 'hold', [task.id])}>Hold queue</Button>}
503 {task.task && eligible('pause', task.task.state) && <Button key="pi-stop" hotkey="s" onPress={() => void stopQueue($, task.task?.group ?? 'default')}>Stop queue</Button>}
504 {!complete(task) && <Button key="pi-pause" hotkey="p" onPress={() => void runControl($, task.task?.state === 'Paused' ? 'resume' : 'pause', [task.id], task.task?.group ?? 'default')}>{task.task?.state === 'Paused' ? 'Resume' : 'Pause'}</Button>}
505 {complete(task) && <Button key="pi-remove" onPress={() => void runControl($, 'rm', [task.id], task.task?.group ?? 'default')}>Remove</Button>}
506 <Button key="pi-dismiss" onPress={() => void dismiss($, task)}>Dismiss</Button>
507 {pending && <Button key="pi-open-review" onPress={() => void openReview($, task)}>Open review</Button>}
508 {pending && <Button key="pi-approve" onPress={() => void approve($, task, pending)}>Approve</Button>}
509 {pending && <Button key="pi-reject-all" onPress={() => { const confirmed = !needsRejectConfirm(rejecting, pending.runId); rejecting = confirmed ? undefined : pending.runId; void rejectAll($, task, pending.runId, confirmed) }}>Reject all</Button>}
510 </Box>}
511 {task && <Input key="pi-continue" label="Continue" placeholder="Follow-up for Pi" submitLabel="send" onSubmit={value => void continueTask($, task, pi, value)} />}
512 {task?.task?.state === 'Queued' && <Input key="pi-edit" label="Edit" placeholder="model[:effort] [label]" submitLabel="re-add" onSubmit={value => void editTask($, task, value).catch(error => $.ui.toast(`Edit failed: ${String(error)}`))} />}
513 <Box flexDirection="row" columnGap={1} marginTop={1}>
514 <Button key="pi-history" onPress={() => void goTo($, 'pi-history')}>history</Button>
515 <Button key="pi-clean-stale" onPress={() => void cleanStale($)}>Clean stale</Button>
516 </Box>
517 </Box>
518 })
519
520 // The person's arrows move the focus ring over the row Buttons; the task under the ring is the selected one.
521 // A plugin's move (j/k already selected; an autoFocus) is not a pick, so it never pins the transcript.
522 on('ui.focus', { requestId: 'pi-handoff' }, async ($, e, next) => {
523 const id = /^pi-row-(\d+)$/.exec(e.element ?? '')?.[1]
524 if (id !== undefined && e.origin?.kind === 'person') await update($, handoff, value => ({ ...value, selectedId: Number(id) }))
525 return next(e)
526 })
527}
528hooks/send-it.tsx 104 lines1import { atom, read, update, type CommandRunInput, type CommandRunResult, type EngineInterface, type Register } from 'claude-code'
2
3import { acceptsOrigin, disable, enable, hasSendItBlock, isEligible, isOn, refusedRepos, SEND_IT_SINCE, sendItOn } from './send-it'
4
5const LOG = '.claude/state/send-it.log'
6const SETTINGS = '.claude/settings.local.json'
7const CONFLICT_PREFIX = 'send-it: refused, these keys already hold other values:'
8const RULE = '.claude/rules/send-it.md'
9const MISSING_RULE = 'send-it is on but ~/.claude/rules/send-it.md is missing or unreadable; the mode runs without its rules.'
10const REFUSED_CHANGE = 'send-it: this settings change is refused mid-session and applies at the next session start.'
11
12// True while send-it runs in this session. Set at session start, read by the rule and the ConfigChange guard.
13const sendItAtom = atom({ plugin: 'session-band', key: 'sendIt' } as const, false)
14
15// Reads the repo's local settings as loaded and records whether send-it runs in this session.
16export async function refreshSendIt($: EngineInterface): Promise<boolean> {
17 const on = sendItOn(await $.settings.read({ source: 'local' }))
18 await update($, sendItAtom, () => on)
19 return on
20}
21
22// The local settings as they are on disk now: a mid-session edit is visible here, not in the loaded settings.
23const onDiskLocalText = async ($: EngineInterface): Promise<string> => {
24 const top = (await git($, ['rev-parse', '--show-toplevel'])).split('\n')[0] ?? ''
25 return top ? $.fs.read(`${top}/${SETTINGS}`).catch(() => '') : ''
26}
27
28const git = async ($: EngineInterface, args: string[]): Promise<string> => {
29 const r = await $.process.run(['git', ...args]).catch(() => undefined)
30 return r?.exitCode === 0 ? r.stdout.trim() : ''
31}
32
33// Appends one line. A failed read skips the write, so an unreadable log is never overwritten.
34const appendLog = async ($: EngineInterface, home: string, line: string) => {
35 const path = `${home}/${LOG}`
36 try {
37 const prior = (await $.fs.exists(path)) ? await $.fs.read(path) : ''
38 await $.fs.write(path, `${prior}${line}\n`)
39 } catch { /* logging must not block the command */ }
40}
41
42const reply = async ($: EngineInterface, home: string, args: string, repo: string, result: string): Promise<CommandRunResult> => {
43 await appendLog($, home, `${new Date(await $.clock.now()).toISOString()} /send-it ${args} ${repo} ${result}`)
44 return { text: result }
45}
46
47const handle = async ($: EngineInterface, e: CommandRunInput): Promise<CommandRunResult> => {
48 if (!acceptsOrigin(e.origin.kind)) return { text: 'send-it: refused, only the person can run /send-it at the composer' }
49 const args = e.args.trim()
50 if (!['on', 'off', 'status'].includes(args)) return { text: 'send-it: usage /send-it on|off|status' }
51 const home = await $.env.get('HOME')
52 if (!home) return { text: 'send-it: HOME is unset, not editing anything' }
53
54 const [top, common] = (await git($, ['rev-parse', '--path-format=absolute', '--show-toplevel', '--git-common-dir'])).split('\n')
55 if (!top || !common) return { text: 'send-it: not inside a git repo' }
56 const root = (await git($, ['rev-list', '--max-parents=0', 'HEAD'])).split('\n')[0] ?? ''
57 const rootDate = root ? await git($, ['show', '-s', '--format=%cI', root]) : ''
58
59 if (!isEligible(common, rootDate, home)) {
60 const why = refusedRepos(home).includes(common)
61 ? 'this repo is on the refused list'
62 : `its root commit is before ${SEND_IT_SINCE} or unreadable`
63 return reply($, home, args, common, `send-it: refused, ${why}`)
64 }
65
66 const path = `${top}/${SETTINGS}`
67 try {
68 const text = (await $.fs.exists(path)) ? await $.fs.read(path) : '{}'
69 if (args === 'status') return reply($, home, args, common, `send-it is ${isOn(text) ? 'on' : 'off'} for this repo`)
70 await $.fs.write(path, args === 'on' ? enable(text) : disable(text))
71 } catch (err) {
72 // Only the conflict refusal is shown as-is: it names key paths, never values.
73 // Any other error keeps the fixed text, since parse errors can quote the file.
74 const msg = err instanceof Error ? err.message : ''
75 if (msg.startsWith(CONFLICT_PREFIX)) return reply($, home, args, common, msg)
76 return reply($, home, args, common, `send-it: ${SETTINGS} could not be read as a JSON object; not editing it`)
77 }
78 return reply($, home, args, common, 'written; restart to apply')
79}
80
81export const register: Register = on => {
82 on('command.run', { command: 'send-it' }, async ($, e, _next) => handle($, e))
83
84 // Settings changes are refused while send-it runs or its block sits in the repo; they apply at the next start.
85 on('classic.ConfigChange', async ($, e, next) => {
86 if (e.source !== 'local_settings' && e.source !== 'user_settings') return next(e)
87 const guarded = await read($, sendItAtom) || hasSendItBlock(await onDiskLocalText($))
88 return guarded ? { block: REFUSED_CHANGE } : next(e)
89 })
90
91 // The rule is injected only while send-it is on. Refreshing here too keeps it right whichever start hook runs first.
92 on('classic.SessionStart', async ($, e, next) => {
93 const result = await next(e)
94 if (!(await refreshSendIt($))) return result
95 const home = await $.env.get('HOME')
96 const text = home ? await $.fs.read(`${home}/${RULE}`).catch(() => undefined) : undefined
97 if (text === undefined) {
98 $.ui.toast(MISSING_RULE, { timeoutMs: 15_000 })
99 return { ...result, additionalContext: [...(result.additionalContext ?? []), MISSING_RULE] }
100 }
101 return { ...result, additionalContext: [...(result.additionalContext ?? []), text] }
102 })
103}
104hooks/worktree-pane.tsx 127 lines1import { atom, read, update, type EngineInterface, type Register } from 'claude-code'
2
3import type { WorktreeBranch, WorktreeRow, WorktreeState } from '../types'
4import { FOCUS_ACTION, FOCUS_REFUSED, JUMP_KEYS, nextPane, PANE_TITLES, switchSteps } from './pane-nav'
5import { countChanges, liveByTree, paneLines, parseAheadBehind, parseHeartbeat, parseWorktrees, treeKeys, type Worktree } from './worktrees'
6
7const view = atom({ plugin: 'session-band', key: 'worktrees' } as const, { open: false, legend: true } as WorktreeState)
8// Same key as send-it.tsx, which sets it at session start; the state scan needs the atom declared in each file that reads it.
9const sendItAtom = atom({ plugin: 'session-band', key: 'sendIt' } as const, false)
10
11const FRESH_MS = 60_000
12
13// Read-only git: a failing call (no upstream, not a repo) yields undefined rather than an error.
14const git = async ($: EngineInterface, cwd: string, args: string[]): Promise<string | undefined> => {
15 const r = await $.process.run(['git', '-C', cwd, '--no-optional-locks', ...args]).catch(() => undefined)
16 return r && r.exitCode === 0 ? r.stdout : undefined
17}
18
19// A session's heartbeat names its cwd; a worktree has a live session when a fresh cwd sits inside its path.
20const liveCwds = async ($: EngineInterface): Promise<string[]> => {
21 const tmp = await $.env.get('TMPDIR') ?? '/tmp'
22 const entries = await $.fs.list(tmp).catch(() => [])
23 const now = await $.clock.now()
24 const beats = entries.filter(entry => entry.kind === 'file' && entry.name.startsWith('session-band-') && entry.name.endsWith('.alive') && now - entry.mtimeMs < FRESH_MS)
25 const bodies = await Promise.all(beats.map(entry => $.fs.read(`${tmp}/${entry.name}`).catch(() => '')))
26 return bodies.flatMap(body => { const beat = parseHeartbeat(typeof body === 'string' ? body : ''); return beat ? [beat.cwd] : [] })
27}
28
29export const gather = async ($: EngineInterface, cwd: string): Promise<WorktreeState['data']> => {
30 const trees: Worktree[] = parseWorktrees((await git($, cwd, ['worktree', 'list', '--porcelain'])) ?? '')
31 const cwds = await liveCwds($)
32 const liveByPath = liveByTree(cwds, trees.map(tree => tree.path))
33 const rows: WorktreeRow[] = await Promise.all(trees.map(async tree => {
34 const changes = countChanges((await git($, tree.path, ['status', '--porcelain'])) ?? '')
35 const ab = await git($, tree.path, ['rev-list', '--left-right', '--count', '@{u}...HEAD'])
36 const { ahead, behind } = ab ? parseAheadBehind(ab) : { ahead: 0, behind: 0 }
37 const live = liveByPath.get(tree.path) ?? 0
38 return { ...tree, changes, ahead, behind, live }
39 }))
40 const refs = (await git($, cwd, ['for-each-ref', '--format=%(refname:short)\t%(upstream:short)\t%(worktreepath)', 'refs/heads'])) ?? ''
41 // A branch with no worktree has no row, so its ahead and behind come from its own upstream here.
42 const branches: WorktreeBranch[] = await Promise.all(refs.split('\n').filter(Boolean).map(async line => {
43 const [name = '', upstream = '', worktree = ''] = line.split('\t')
44 const branch: WorktreeBranch = { name, upstream: upstream || undefined, worktree: worktree || undefined }
45 if (branch.worktree || !branch.upstream) return branch
46 const ab = await git($, cwd, ['rev-list', '--left-right', '--count', `${name}@{u}...${name}`])
47 return { ...branch, ...(ab ? parseAheadBehind(ab) : {}) }
48 }))
49 return { rows, branches, at: await $.clock.now() }
50}
51
52const refresh = async ($: EngineInterface) => {
53 const data = await gather($, await $.session.cwd())
54 await update($, view, state => ({ ...state, data }))
55}
56
57// j/k move through the root and the tree items in display order; wraps at both ends.
58const move = async ($: EngineInterface, step: 1 | -1) => {
59 const state = await read($, view)
60 const keys = treeKeys(state.data?.rows ?? [], state.data?.branches ?? [])
61 if (keys.length === 0) return
62 const at = Math.max(keys.indexOf(state.selected ?? keys[0]), 0)
63 await update($, view, value => ({ ...value, selected: keys[(at + step + keys.length) % keys.length] }))
64}
65
66// `$` cannot cross an import, so this pane runs pane-nav's switch itself.
67const goTo = async ($: EngineInterface, to: string | undefined) => {
68 for (const s of switchSteps('worktrees', to)) await ('close' in s ? $.ui.close({ id: s.close }) : $.ui.open({ id: s.open, title: s.title, focus: s.focus }))
69}
70const cycle = async ($: EngineInterface, step: 1 | -1) => goTo($, nextPane((await $.ui.panes()).map(pane => pane.id), 'worktrees', step))
71
72// Keep engine calls local: `$` cannot cross an import.
73async function focusSelf($: EngineInterface) {
74 if ((await $.prompt.read()).text.trim()) {
75 await $.ui.toast(FOCUS_REFUSED)
76 return
77 }
78 await $.ui.open({ id: 'worktrees', title: PANE_TITLES['worktrees'], focus: true })
79 if (!(await $.ui.panes()).some(pane => pane.id === 'worktrees' && pane.isFocused)) await $.ui.toast(FOCUS_REFUSED)
80}
81
82export const register: Register = on => {
83 on('command.run', { command: 'worktrees' }, async ($, _e, _next) => {
84 await $.ui.open({ id: 'worktrees', title: 'Worktrees', focus: true })
85 return { text: 'Worktrees opened.' }
86 })
87
88 on('ui.open', { id: 'worktrees' }, async ($, e, next) => {
89 const result = await next(e)
90 await update($, view, state => ({ ...state, open: true }))
91 await refresh($)
92 return result
93 })
94
95 on('ui.close', { id: 'worktrees' }, async ($, e, next) => {
96 const result = await next(e)
97 if (!('deny' in result)) await update($, view, state => ({ ...state, open: false }))
98 return result
99 })
100
101 on('ui.render', { component: 'Pane', requestId: 'worktrees' }, async ($, e, _next) => {
102 const { Box, Text, Button } = $.ui.resolve(e)
103 const state = await read($, view)
104 const rows = state.data?.rows ?? []
105 const branches = state.data?.branches ?? []
106 const selectedKey = state.selected ?? treeKeys(rows, branches)[0]
107 const sendIt = await read($, sendItAtom)
108 const lines = paneLines(rows, branches, state.legend, selectedKey, sendIt)
109 return <Box flexDirection="column">
110 <Text weight="bold">Worktrees</Text>
111 {/* Hotkeys, not hints: a key the pane does not bind falls through to the composer. */}
112 <Box flexDirection="row" flexWrap="wrap" columnGap={2} marginBottom={1}>
113 <Button key="wt-key-down" plain dimColor hotkey="j" label="down" onPress={() => void move($, 1)} />
114 <Button key="wt-key-up" plain dimColor hotkey="k" label="up" onPress={() => void move($, -1)} />
115 <Button key="wt-key-legend" plain dimColor hotkey="h" label="legend" onPress={() => void update($, view, value => ({ ...value, legend: !value.legend }))} />
116 <Button key="wt-key-refresh" plain dimColor hotkey="r" label="refresh" onPress={() => void refresh($)} />
117 <Button key="wt-key-prev" plain dimColor hotkey="b" label="prev pane" onPress={() => void cycle($, -1)} />
118 <Button key="wt-key-next" plain dimColor hotkey="f" label="next pane" onPress={() => void cycle($, 1)} />
119 <Button key="wt-key-quit" plain dimColor hotkey="q" label="close" onPress={() => void $.ui.close({ id: 'worktrees' })} />
120 <Button key="wt-key-focus" plain dimColor action={FOCUS_ACTION} label="ctrl+x b" onPress={() => void focusSelf($)} />
121 {JUMP_KEYS.map(j => <Button key={`wt-key-jump-${j.key}`} plain dimColor hotkey={j.key} label={j.label} onPress={() => void (j.id === 'worktrees' ? undefined : goTo($, j.id))} />)}
122 </Box>
123 {lines.map((line, index) => <Text key={`wt-line-${index}`} mono color={line.color} weight={line.strong ? 'bold' : undefined}>{line.text}</Text>)}
124 </Box>
125 })
126}
127hooks/draft-prs.tsx 100 lines1import { atom, read, update, type EngineInterface, type Register } from 'claude-code'
2
3import type { DraftPrsState } from '../types'
4import { CHECK_MARK, groups, prLine } from './draft-prs'
5import { forgeById, NO_REMOTE, noForge, pickRemote, REMOTE_ARGV } from './forge'
6import { FOCUS_ACTION, FOCUS_REFUSED, JUMP_KEYS, nextPane, PANE_TITLES, switchSteps } from './pane-nav'
7
8const view = atom({ plugin: 'session-band', key: 'draftPrs' } as const, { loading: false } as DraftPrsState)
9
10// Read-only: the repo's remotes pick the forge, then that forge's list command is the only other call.
11// A spawn failure or timeout resolves undefined, which the forge's reader names.
12const refresh = async ($: EngineInterface) => {
13 await update($, view, state => ({ ...state, loading: true }))
14 const cwd = await $.session.cwd()
15 const remote = await $.process.run(REMOTE_ARGV, { cwd, timeoutMs: 15_000 }).catch(() => undefined)
16 const { host, forge } = remote?.exitCode === 0 ? pickRemote(remote.stdout) : {}
17 if (!forge) {
18 const error = host === undefined ? NO_REMOTE : noForge(host)
19 await update($, view, state => ({ ...state, loading: false, prs: [], error, forge: undefined }))
20 return
21 }
22 const r = await $.process.run(forge.argv, { cwd, timeoutMs: 15_000 }).catch(() => undefined)
23 const now = await $.clock.now()
24 await update($, view, state => ({ ...state, loading: false, ...forge.read(r, now), forge: forge.id }))
25}
26
27// j/k move through the rows in display order; wraps at both ends, as the worktrees pane does.
28const move = async ($: EngineInterface, step: 1 | -1) => {
29 const state = await read($, view)
30 const ids = (state.prs ?? []).map(pr => pr.number)
31 if (ids.length === 0) return
32 const at = Math.max(state.selected === undefined ? 0 : ids.indexOf(state.selected), 0)
33 await update($, view, value => ({ ...value, selected: ids[(at + step + ids.length) % ids.length] }))
34}
35
36// `$` cannot cross an import, so this pane runs pane-nav's switch itself.
37const goTo = async ($: EngineInterface, to: string | undefined) => {
38 for (const s of switchSteps('draft-prs', to)) await ('close' in s ? $.ui.close({ id: s.close }) : $.ui.open({ id: s.open, title: s.title, focus: s.focus }))
39}
40const cycle = async ($: EngineInterface, step: 1 | -1) => goTo($, nextPane((await $.ui.panes()).map(pane => pane.id), 'draft-prs', step))
41
42// Keep engine calls local: `$` cannot cross an import.
43async function focusSelf($: EngineInterface) {
44 if ((await $.prompt.read()).text.trim()) {
45 await $.ui.toast(FOCUS_REFUSED)
46 return
47 }
48 await $.ui.open({ id: 'draft-prs', title: PANE_TITLES['draft-prs'], focus: true })
49 if (!(await $.ui.panes()).some(pane => pane.id === 'draft-prs' && pane.isFocused)) await $.ui.toast(FOCUS_REFUSED)
50}
51
52export const register: Register = on => {
53 on('command.run', { command: 'draft-prs' }, async ($, _e, _next) => {
54 await $.ui.open({ id: 'draft-prs', title: 'Draft PRs', focus: true })
55 return { text: 'Draft PRs opened.' }
56 })
57
58 // No timer: the list loads when the pane opens and on r.
59 on('ui.open', { id: 'draft-prs' }, async ($, e, next) => {
60 const result = await next(e)
61 await refresh($)
62 return result
63 })
64 on('ui.render', { component: 'Pane', requestId: 'draft-prs' }, async ($, e, _next) => {
65 const { Box, Text, Button, Link } = $.ui.resolve(e)
66 const state = await read($, view)
67 const now = await $.clock.now()
68 const prs = state.prs ?? []
69 const pick = prs.find(pr => pr.number === state.selected) ?? prs[0]
70 const sigil = forgeById(state.forge)?.sigil
71 const note = state.error ?? (state.loading ? 'Loading…' : prs.length === 0 ? `No open or recently merged ${state.forge === 'gitlab' ? 'MRs' : 'PRs'}.` : undefined)
72 return <Box flexDirection="column">
73 <Text weight="bold">Draft PRs</Text>
74 {/* Hotkeys, not hints: a key the pane does not bind falls through to the composer. */}
75 <Box flexDirection="row" flexWrap="wrap" columnGap={2} marginBottom={1}>
76 <Button key="pr-key-down" plain dimColor hotkey="j" label="down" onPress={() => void move($, 1)} />
77 <Button key="pr-key-up" plain dimColor hotkey="k" label="up" onPress={() => void move($, -1)} />
78 <Button key="pr-key-reload" plain dimColor hotkey="r" label="reload" onPress={() => void refresh($)} />
79 <Button key="pr-key-copy" plain dimColor hotkey="y" label="copy" onPress={press => { if (pick) void $.ui.copy({ text: pick.url, surface: press.surface }) }} />
80 <Button key="pr-key-prev" plain dimColor hotkey="b" label="prev" onPress={() => void cycle($, -1)} />
81 <Button key="pr-key-next" plain dimColor hotkey="f" label="next" onPress={() => void cycle($, 1)} />
82 <Button key="pr-key-quit" plain dimColor hotkey="q" label="close" onPress={() => void $.ui.close({ id: 'draft-prs' })} />
83 <Button key="pr-key-focus" plain dimColor action={FOCUS_ACTION} label="ctrl+x b" onPress={() => void focusSelf($)} />
84 {JUMP_KEYS.map(j => <Button key={`pr-key-jump-${j.key}`} plain dimColor hotkey={j.key} label={j.label} onPress={() => void (j.id === 'draft-prs' ? undefined : goTo($, j.id))} />)}
85 </Box>
86 {note !== undefined && <Text dimColor>{note}</Text>}
87 {/* A header per state separates drafts from the rest; the row keeps only what tells PRs apart. */}
88 {groups(prs).map(group => <Box key={`pr-group-${group.header}`} flexDirection="column" marginBottom={1}>
89 <Text weight="bold">{group.header}</Text>
90 {group.prs.map(pr => <Box key={`pr-row-${pr.number}`} flexDirection="row" columnGap={1}>
91 <Text mono>{pr === pick ? '›' : ' '}</Text>
92 <Text mono color={CHECK_MARK[pr.checks].color} dimColor={!CHECK_MARK[pr.checks].color}>{CHECK_MARK[pr.checks].glyph}</Text>
93 <Text mono weight={pr === pick ? 'bold' : undefined} dimColor={pr.state === 'merged' && pr !== pick}>{prLine(pr, now, sigil)}</Text>
94 </Box>)}
95 </Box>)}
96 {pick && <Text mono dimColor>{pick.branch} · <Link href={pick.url} label={pick.url} /></Text>}
97 </Box>
98 })
99}
100hooks/safety-blocks.tsx 81 lines1import { atom, read, update, type EngineInterface, type Register } from 'claude-code'
2
3import type { SafetyBlocksState } from '../types'
4import { loadSessionBlocks, safetyBlockLine, safetyLogArgv, type SafetyVerdict } from './safety-blocks'
5
6export const PANE = { id: 'safety-blocks', title: 'Blocks', command: 'blocks' } as const
7const view = atom({ plugin: 'session-band', key: 'safetyBlocks' } as const, { loading: false, rows: [] } as SafetyBlocksState)
8
9// No timer: the list loads when the pane opens, on r, and after each verdict.
10const refresh = async ($: EngineInterface) => {
11 await update($, view, state => ({ ...state, loading: true }))
12 const rows = await loadSessionBlocks($).catch(() => [])
13 await update($, view, state => ({
14 ...state,
15 loading: false,
16 rows,
17 selected: rows.some(row => row.id === state.selected) ? state.selected : rows[0]?.id,
18 }))
19}
20
21// j/k move through the rows in display order; wraps at both ends, as the other panes do.
22const move = async ($: EngineInterface, step: 1 | -1) => {
23 const state = await read($, view)
24 const ids = state.rows.map(row => row.id)
25 if (ids.length === 0) return
26 const at = Math.max(state.selected === undefined ? 0 : ids.indexOf(state.selected), 0)
27 await update($, view, value => ({ ...value, selected: ids[(at + step + ids.length) % ids.length] }))
28}
29
30// A verdict only records the human's judgement; the CLI writes it and nothing here can allow a block.
31const mark = async ($: EngineInterface, verdict: SafetyVerdict) => {
32 const state = await read($, view)
33 const row = state.rows.find(value => value.id === state.selected)
34 const home = await $.env.get('HOME').catch(() => undefined)
35 if (!row || !home) {
36 await $.ui.toast('No block selected.')
37 return
38 }
39 const result = await $.process.run(safetyLogArgv(home, row.id, verdict), { timeoutMs: 10_000 }).catch(() => undefined)
40 await $.ui.toast(result?.exitCode === 0 ? `Marked ${row.id} ${verdict}.` : (result?.stderr.trim() || 'safety-log mark failed.'))
41 await refresh($)
42}
43
44export const register: Register = on => {
45 on('command.run', { command: PANE.command }, async ($, _e, _next) => {
46 await $.ui.open({ id: PANE.id, title: PANE.title, focus: true })
47 return { text: 'Blocks opened.' }
48 })
49
50 on('ui.open', { id: PANE.id }, async ($, e, next) => {
51 const result = await next(e)
52 await refresh($)
53 return result
54 })
55 on('ui.render', { component: 'Pane', requestId: PANE.id }, async ($, e, _next) => {
56 const { Box, Text, Button } = $.ui.resolve(e)
57 const state = await read($, view)
58 const rows = state.rows
59 const pick = rows.find(row => row.id === state.selected) ?? rows[0]
60 const note = state.loading ? 'Loading…' : rows.length === 0 ? 'No blocked commands in this session.' : undefined
61 return <Box flexDirection="column">
62 <Text weight="bold">{PANE.title}</Text>
63 {/* Hotkeys, not hints: a key the pane does not bind falls through to the composer. */}
64 <Box flexDirection="row" flexWrap="wrap" columnGap={2} marginBottom={1}>
65 <Button key="sb-key-down" plain dimColor hotkey="j" label="down" onPress={() => void move($, 1)} />
66 <Button key="sb-key-up" plain dimColor hotkey="k" label="up" onPress={() => void move($, -1)} />
67 <Button key="sb-key-ok" plain dimColor hotkey="o" label="ok" onPress={() => void mark($, 'ok')} />
68 <Button key="sb-key-false-positive" plain dimColor hotkey="f" label="false-positive" onPress={() => void mark($, 'false-positive')} />
69 <Button key="sb-key-reload" plain dimColor hotkey="r" label="reload" onPress={() => void refresh($)} />
70 <Button key="sb-key-quit" plain dimColor hotkey="q" label="close" onPress={() => void $.ui.close({ id: PANE.id })} />
71 </Box>
72 {note !== undefined && <Text dimColor>{note}</Text>}
73 {rows.map(row => <Box key={`sb-row-${row.id}`} flexDirection="row" columnGap={1}>
74 <Text mono>{row.id === pick?.id ? '›' : ' '}</Text>
75 <Text mono weight={row.id === pick?.id ? 'bold' : undefined} dimColor={row.verdict !== undefined}>{safetyBlockLine(row)}</Text>
76 </Box>)}
77 {pick && <Text mono dimColor>{`${pick.cwd} · ${pick.transcript}`}</Text>}
78 </Box>
79 })
80}
81hooks/safety-blocks.ts 128 lines1// Reads the bash-safety block log the PreToolUse hook appends and the human verdicts
2// scripts/safety-log writes (docs/workflows/bash-safety-log.md). Pure reading and shaping:
3// the band counts this session's pending blocks, the pane lists them and marks through the CLI.
4import type { EngineInterface } from 'claude-code'
5
6export type SafetyVerdict = 'ok' | 'false-positive'
7
8export type SafetyBlock = {
9 id: string
10 ts: string
11 session: string
12 cwd: string
13 transcript: string
14 rule: string
15 command: string
16 reason: string
17}
18
19/** One logged block with the human verdict it has, if any. */
20export type SafetyBlockRow = SafetyBlock & { verdict?: SafetyVerdict }
21
22export const BLOCKS_FILE = 'bash-safety-blocks.jsonl'
23export const VERDICTS_FILE = 'bash-safety-verdicts.jsonl'
24export const SAFETY_LOG = 'dotfiles/scripts/safety-log'
25
26/** The one CLI write the pane makes: `safety-log mark <id> ok|false-positive`. */
27export const safetyLogArgv = (home: string, id: string, verdict: SafetyVerdict): string[] =>
28 [`${home}/${SAFETY_LOG}`, 'mark', id, verdict]
29
30// The hook honours SAFETY_LOG_DIR, so the band follows it and both read the same directory.
31export const stateDir = (home: string | undefined, override: string | undefined): string | undefined =>
32 override || (home ? `${home}/.claude/state` : undefined)
33
34const objects = (text: string | undefined): Record<string, unknown>[] =>
35 (text ?? '').split('\n').flatMap(line => {
36 if (!line.trim()) return []
37 try {
38 const value: unknown = JSON.parse(line)
39 return value !== null && typeof value === 'object' ? [value as Record<string, unknown>] : []
40 } catch {
41 return []
42 }
43 })
44
45const text = (value: unknown): string => (typeof value === 'string' ? value : '')
46
47/** Every block line with an id; malformed lines and foreign objects read as nothing. */
48export const parseBlocks = (texts: readonly (string | undefined)[]): SafetyBlock[] =>
49 texts.flatMap(body => objects(body).flatMap(entry => {
50 const id = text(entry.id)
51 if (!id) return []
52 return [{
53 id,
54 ts: text(entry.ts),
55 session: text(entry.session),
56 cwd: text(entry.cwd),
57 transcript: text(entry.transcript),
58 rule: text(entry.rule),
59 command: text(entry.command),
60 reason: text(entry.reason),
61 }]
62 }))
63
64/** Verdicts by id; the last line for an id wins, as `safety-log` does. */
65export const parseVerdicts = (body: string | undefined): Map<string, SafetyVerdict> => {
66 const latest = new Map<string, SafetyVerdict>()
67 for (const entry of objects(body)) {
68 const id = text(entry.id)
69 const verdict = text(entry.verdict)
70 if (id && (verdict === 'ok' || verdict === 'false-positive')) latest.set(id, verdict)
71 }
72 return latest
73}
74
75const moment = (ts: string): number => {
76 const parsed = Date.parse(ts)
77 return Number.isNaN(parsed) ? 0 : parsed
78}
79
80/** Newest first, as `safety-log` lists them. */
81export const newestFirst = (blocks: readonly SafetyBlock[]): SafetyBlock[] =>
82 [...blocks].sort((a, b) => moment(b.ts) - moment(a.ts))
83
84export const judge = (blocks: readonly SafetyBlock[], verdicts: ReadonlyMap<string, SafetyVerdict>): SafetyBlockRow[] =>
85 blocks.map(block => ({ ...block, verdict: verdicts.get(block.id) }))
86
87export const sessionRows = (rows: readonly SafetyBlockRow[], sessionId: string): SafetyBlockRow[] =>
88 sessionId ? rows.filter(row => row.session === sessionId) : []
89
90/** The chip's count: this session's blocks a human has not judged yet. */
91export const pendingCount = (rows: readonly SafetyBlockRow[]): number => rows.filter(row => row.verdict === undefined).length
92
93const clock = (ts: string): string => (ts.length >= 19 ? ts.slice(11, 19) : ts || '?')
94
95/** One pane row: time, rule, verdict or pending, then the redacted command the hook recorded. */
96export const safetyBlockLine = (row: SafetyBlockRow): string =>
97 `${clock(row.ts)} ${row.rule || 'other'} ${row.verdict ?? 'pending'} ${row.command.replace(/\s+/g, ' ').trim()}`
98
99/** This session's blocks, newest first, across the current log and its rotated predecessor. */
100export async function loadSessionBlocks($: EngineInterface): Promise<SafetyBlockRow[]> {
101 let home: string | undefined
102 let override: string | undefined
103 try {
104 home = await $.env.get('HOME')
105 } catch {
106 home = undefined
107 }
108 try {
109 override = await $.env.get('SAFETY_LOG_DIR')
110 } catch {
111 override = undefined
112 }
113 const dir = stateDir(home, override)
114 if (!dir) return []
115 const [rotated, current, verdictsBody] = await Promise.all([
116 $.fs.read(`${dir}/${BLOCKS_FILE}.1`).catch(() => undefined),
117 $.fs.read(`${dir}/${BLOCKS_FILE}`).catch(() => undefined),
118 $.fs.read(`${dir}/${VERDICTS_FILE}`).catch(() => undefined),
119 ])
120 let sessionId = ''
121 try {
122 sessionId = await $.session.id()
123 } catch {
124 sessionId = ''
125 }
126 return sessionRows(judge(newestFirst(parseBlocks([rotated, current])), parseVerdicts(verdictsBody)), sessionId)
127}
128