SLOPSHOPPER

PR Pilot

Shows the current branch's pull request above the prompt, with its checks and whether it can merge, toasts when checks finish, and merges it, or its whole…

bandcommandtoastprocesstimer
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · pr-pilot
› fix the failing auth test and add an audit log call ⏺ Read(src/auth.ts) ⎿ Read 6 lines ⏺ Update(src/auth.ts) ⎿ Added 2 lines, removed 1 line ⏺ Bash(bun test) ⎿ 3 pass, 1 fail ● Done. refresh now rejects expired claims and logs an audit event. ✻ Worked for 42s · done 4:20 PM › /merge ⎿ pr-pilot: No open pull request for this branch. ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts
README

🧩 Claude Code Mods

Live panes, prompt bands, status line entries, toasts, and hooks for Claude Code, each shipped as a plugin.

Release CI License: MIT

🚀 Install

/plugin marketplace add tartinerlabs/claude-code-mods
/plugin install <mod> --marketplace tartinerlabs/claude-code-mods

🧰 Mods

| | Mod | Where it shows | In one line | | :-: | --- | --- | --- | | ⏸ | auto-resume | Status line, toast | Picks a turn back up once a usage limit resets | | 🏷 | auto-session-name | Session title | Names each session from its first prompt and keeps the name current as the work moves on | | ⏱ | cache-clock | Band above the prompt | Counts down to the prompt cache going cold | | 📊 | limit-watch | Band above the prompt, toasts | Shows the 5-hour and weekly usage limits and the session's cost | | 🛫 | pr-pilot | Band above the prompt, toasts | Shows the branch's PR checks and merges it with /merge | | 📝 | release-notes | Band above the prompt, toast | Drafts App Store release notes for Xcode projects when the version is bumped | | 📱 | resource-watch | Band above the prompt, toast | Shows which session is using each simulator, Claude Design project or the Xcode app, and messages the other session on a clash | | 🗜 | smart-compact | Toast | Compacts between turns, sooner at checkpoints or when the cache is cooling | | ⛅ | token-weather | Band above the prompt | Forecasts how full the context window is |


⏸ auto-resume

When a turn stops on a usage limit, waits until the limit resets and sends continue. Typing a prompt yourself or running /auto-resume cancel stops the wait.

⏸ auto-resume in 1h 12m                                    ← status line
Usage limit reset, resuming                                 ← toast

<sub>📁 plugins/auto-resume</sub>

🏷 auto-session-name

Names each session from its first prompt using Haiku and can give it a prompt bar colour, so it is easy to find with claude -r after a crash. When the first prompt is short, such as continue or look at this, it titles the session again from the last four prompts on the fourth. Every eighth prompt it checks the title against the last four prompts and renames the session only when the work has moved to a different task; small shifts keep the title. Sessions already named with -n or /rename are left alone, and a rename stops any re-title. Set the color option to red, blue, green, yellow, purple, orange, pink or cyan to colour named sessions; default leaves the colour alone.

> fix the flaky retry test in the upload worker
                                    → session titled "Fix flaky upload retry test"

<sub>📁 plugins/auto-session-name</sub>

⏱ cache-clock

Draws a countdown above the prompt to when the prompt cache goes cold, with the last request's hit rate. Once cold, it shows how much the next turn re-writes. Set the ttl option to 1h when extended caching is on.

🔥 cache 3:42 left · 96% hit                                ← green, yellow under a minute
🧊 cache cold · next turn re-writes 84.3k                   ← red

<sub>📁 plugins/cache-clock</sub>

📊 limit-watch

Draws the 5-hour and weekly usage limits above the prompt with live reset countdowns, green under 60%, yellow to 80% and red past it. Toasts once a window passes 80% and again at 95%. Any other window the API reports, such as a gateway spend limit, shows under its own name. The session's cost so far follows the limits.

🕔 5h 42% · 2h17m  📅 7d 81% · 3d4h  💰 $2.36              ← band
7d limit at 81%, resets in 3d4h                             ← toast

<sub>📁 plugins/limit-watch</sub>

🛫 pr-pilot

Draws the current branch's open pull request above the prompt with its checks and whether it can merge, refreshed each minute and after every turn. Toasts when a run of checks finishes. /merge merges it with gh and deletes the branch, but only once every check has passed and nothing blocks it. On a gh-stack layer the band shows its place in the stack, and /merge merges the whole stack with gh stack merge once every unmerged layer has passed its checks and has no unpushed commits, then switches to the trunk and deletes every layer's branch, local and remote, once all of them have merged. Set the method option to merge (default), squash or rebase. Needs the GitHub CLI, signed in.

🔀 PR #42  ⏳ 3/5 checks  waiting                            ← band
PR #42  ✗ 1 failing: SonarCloud  blocked                     ← red
PR #42  ✓ 5/5 checks  ready · /merge                         ← green
PR #42  stack 2/3  ✓ 5/5 checks  ready · /merge              ← a gh-stack layer
PR #42 checks passed, ready to /merge                        ← toast

<sub>📁 plugins/pr-pilot</sub>

📝 release-notes

In an Xcode project, draws the app's MARKETING_VERSION and build above the prompt with the commits since the last release. When a turn, or anything between sessions, changes the version, Haiku drafts App Store "What's New" notes from those commits and a toast says where they went. With fastlane they go to fastlane/metadata/<locale>/release_notes.txt for the default locale, else en-US, else the first. Without fastlane they become a ## <version> section in CHANGELOG.md, and a section that is already there is left alone. The last release is the newest tag, or the commit that set the previous version when the repository has no tags. The first time it sees a repository it only records the version. /draft-release-notes drafts the notes again, replacing what is there.

📝 v2.4.0 (41)  12 commits since v2.3.0  notes drafted      ← band
Release notes for 2.4.0 drafted in fastlane/metadata/en-US/release_notes.txt   ← toast

<sub>📁 plugins/release-notes</sub>

📱 resource-watch

Shows which Claude Code session is using each shared thing on the machine, so parallel agents do not fight over one. Booted Apple simulators and Claude Design projects are the baseline; the Xcode app sits on top.

  • Simulators: in an Xcode project, or once the session has used one, every booted simulator with the sessions holding it. A session takes a simulator when simctl or xcodebuild names it by UDID or name, or uses booted or an Xcode MCP run while only one is booted; commands that only look, as simctl list or xcodebuild -showdestinations, do not count.
  • Claude Design: a project, on any claude-design tool call on it.
  • Xcode app: on Xcode MCP calls that change its shared state: switching scheme, run destination or test plan, opening or closing a workspace, building, running, testing or stopping.

A hold lasts the hold option's minutes (10 by default) after the last call, and ends with the session. Sessions share their holds as files in ~/.claude/resource-watch/, labelled by their project's folder. A simulator call on one another session holds is refused the first time: the holding session is asked, and the agent is told to wait for its reply, then repeat the call to go ahead, and never to switch to or create another simulator without asking you. The holder tells the waiting sessions once it is done: after StopProject or DeviceInteractionEndSession, when its hold runs out, or when it ends. For a Claude Design project or the Xcode app nothing is refused: it toasts, messages the holding session so its agent can reply asking it to wait, and tells its own agent who holds it; a session that ends tells the sessions it shared with.

📱 iPhone 18 Pro (iOS 27.2) · this session  🛠 the Xcode app · ⚠ also the web session   ← band
iPhone 18 Pro is in use by the web session; asked it, waiting                            ← toast

<sub>📁 plugins/resource-watch</sub>

🗜 smart-compact

Compacts the conversation between turns, never during one, weighing several factors against the context's fill. Past the threshold option (60, 70 default, or 80%) it compacts about ten seconds after a turn ends. It compacts sooner when compacting is cheapest or most worth it:

  • Checkpoints, 20 points lower: a turn that committed, opened or merged a PR (gh pr, gh stack), had a plan approved, finished its todo list, or switched branch or worktree. The summary is told what to keep for each, such as the approved plan verbatim. A checkpoint counts only until the next turn starts. Set checkpoints to off to ignore them.
  • Cache cooling, 20 points lower in the last minute before the prompt cache goes cold, so the summary still reads the conversation from cache. Once the cache is cold it does not compact sooner, since the summary would re-read the whole conversation uncached.
  • 5-hour limit, 10 points lower while it is at 80% or more.

Nothing takes it under the floor option (30, 40 default, or 50%), and it tries at most once per idle stretch. The ttl option defaults to auto: 1h on a subscription, 5m on an API key or cloud provider. Set it to 5m while a subscription draws on usage credits, or to 1h when you set a one-hour cache yourself.

Set continue to tasks to carry on after compacting while todos or tasks are still open. It sends Continue with the remaining tasks., unless the turn was interrupted or ended on a question.

Compacted at 52%: committed                                  ← toast
Compacted at 55%: cache cooling                              ← toast
Compacted at 74%: context high, 5h limit at 86%              ← toast
Compacted at 75%: context high; continuing                   ← toast

<sub>📁 plugins/smart-compact</sub>

⛅ token-weather

Draws a forecast of the context window above the prompt, with tokens used, a sparkline of the last 12 turns and the change since the last turn.

⛅ Cloudy  38% of context  76.4k / 200k   last turns ▁▂▂▃▄▄▅▆  ▲ +4.1k last turn

| 🌞 Clear | ⛅ Cloudy | ☔ Showers | ⚡ Storm | 🚨 Compact soon | | :-: | :-: | :-: | :-: | :-: | | under 25% | under 50% | under 75% | under 90% | 90% and up |

<sub>📁 plugins/token-weather</sub>


MIT © Tartiner Labs

Source 2 files
hooks/register.tsx 246 lines
1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, Register } from 'claude-code'
3
4import type { Checks, Pr, Stack } from '../types'
5
6const FIELDS = 'number,url,headRefOid,state,isDraft,mergeable,mergeStateStatus,statusCheckRollup'
7const FAILED = ['FAILURE', 'ERROR', 'TIMED_OUT', 'CANCELLED', 'ACTION_REQUIRED', 'STARTUP_FAILURE']
8
9// Held by the host, so a hot reload keeps the band and does not toast the same result twice.
10const current = atom({ plugin: 'pr-pilot', key: 'pr' } as const, null as Pr | null)
11
12/** Drops control characters, so a check name or gh output cannot carry terminal escapes. */
13export const clean = (text: string) => text.replace(/[\u0000-\u001f\u007f-\u009f]/g, '')
14
15type Rollup = { __typename?: string; name?: string; context?: string; status?: string; conclusion?: string; state?: string }
16
17/** Tallies `statusCheckRollup`, which mixes check runs (`status`, `conclusion`) and commit statuses (`state`). */
18export function tally(rollup: readonly Rollup[]): Checks {
19  const checks: Checks = { total: rollup.length, passed: 0, pending: 0, failed: [] }
20  for (const check of rollup) {
21    const result = check.__typename === 'StatusContext' ? check.state : check.status === 'COMPLETED' ? check.conclusion : 'PENDING'
22    if (FAILED.includes(result ?? '')) checks.failed.push(clean(check.name ?? check.context ?? '?'))
23    else if (result === 'PENDING' || result === 'EXPECTED' || !result) checks.pending += 1
24    else checks.passed += 1
25  }
26
27  return checks
28}
29
30/** True once the pull request can merge as is: open, checks green, nothing blocking it. */
31export function isReady(pr: Pr) {
32  return !pr.isDraft && pr.mergeable === 'MERGEABLE' && pr.checks.failed.length === 0 && pr.checks.pending === 0 && ['CLEAN', 'HAS_HOOKS'].includes(pr.mergeStateStatus)
33}
34
35/** The band's checks entry and its colour. */
36export function checksEntry({ total, passed, pending, failed }: Checks): [string, string] {
37  if (total === 0) return ['no checks', 'gray']
38  if (failed.length) return [`❌ ${failed.length} failing: ${failed.join(', ')}`, 'red']
39  if (pending) return [`⏳ ${passed}/${total} checks`, 'yellow']
40
41  return [`✅ ${total}/${total} checks`, 'green']
42}
43
44/** The band's merge entry and its colour. */
45export function mergeEntry(pr: Pr): [string, string] {
46  if (pr.isDraft) return ['draft', 'gray']
47  if (pr.mergeable === 'CONFLICTING') return ['conflicts', 'red']
48  if (pr.mergeStateStatus === 'BEHIND') return ['behind base', 'yellow']
49  if (pr.mergeStateStatus === 'BLOCKED') return ['blocked', 'yellow']
50  if (isReady(pr)) return ['ready · /merge', 'green']
51
52  return ['waiting', 'gray']
53}
54
55type StackView = { trunk: string; currentBranch: string; branches: { name: string; isMerged: boolean; pr?: { number: number } }[] }
56
57/** The current branch's place among the unmerged layers of `gh stack view --json`, or null when it is not one. */
58export function parseStack(view: StackView): Stack | null {
59  const layers = view.branches.filter(b => !b.isMerged).map(b => ({ branch: b.name, pr: b.pr?.number }))
60  const index = layers.findIndex(l => l.branch === view.currentBranch)
61
62  return index < 0 ? null : { position: index + 1, total: layers.length, trunk: view.trunk, layers }
63}
64
65async function fetchStack($: EngineInterface): Promise<Stack | null> {
66  // Exits non-zero off a stack, and where the gh-stack extension is not installed.
67  const ran = await $.process.run(['gh', 'stack', 'view', '--json'], { timeoutMs: 15_000 }).catch(() => null)
68  if (!ran || ran.exitCode !== 0) return null
69
70  try {
71    return parseStack(JSON.parse(ran.stdout))
72  } catch {
73    return null
74  }
75}
76
77async function fetchPr($: EngineInterface, number?: number): Promise<Pr | null> {
78  const argv = ['gh', 'pr', 'view', ...(number ? [String(number)] : []), '--json', FIELDS]
79  const ran = await $.process.run(argv, { timeoutMs: 15_000 }).catch(() => null)
80  if (!ran || ran.exitCode !== 0) return null
81  const view = JSON.parse(ran.stdout)
82  if (view.state !== 'OPEN') return null
83
84  return {
85    number: view.number,
86    url: view.url,
87    head: view.headRefOid,
88    isDraft: view.isDraft,
89    mergeable: view.mergeable,
90    mergeStateStatus: view.mergeStateStatus,
91    checks: tally(view.statusCheckRollup ?? []),
92  }
93}
94
95// Bumped by every refresh and by a merge, so a slower, older refresh cannot overwrite a newer result.
96let latest = 0
97
98async function refresh($: EngineInterface) {
99  const id = ++latest
100  const pr = await fetchPr($)
101  const stack = pr && (await fetchStack($))
102  if (id !== latest) return
103  if (pr && stack) pr.stack = stack
104  const was = await read($, current)
105  await update($, current, () => pr)
106
107  // Toast when the same pull request's checks finish, not on first sight.
108  if (!pr || was?.number !== pr.number || !was.checks.pending || pr.checks.pending) return
109  $.ui.toast(
110    pr.checks.failed.length
111      ? `PR #${pr.number} checks failed: ${pr.checks.failed.join(', ')}`
112      : `PR #${pr.number} checks passed${isReady(pr) ? ', ready to /merge' : ''}`,
113    { timeoutMs: 8000 },
114  )
115}
116
117/** True when `branch` is at `head` locally, so merging and deleting it loses no unpushed commits. */
118async function isPushed($: EngineInterface, branch: string, head: string) {
119  const local = await $.process.run(['git', 'rev-parse', '--verify', `refs/heads/${branch}^{commit}`]).catch(() => null)
120
121  return local?.exitCode === 0 && local.stdout.trim() === head
122}
123
124/**
125 * Merges the whole stack with `gh stack merge`, after checking every unmerged layer, since it is all
126 * or nothing and has no head pin. It runs without an argument, as a number would be read as a stack
127 * number before a pull request number.
128 */
129async function mergeStack($: EngineInterface, pr: Pr, stack: Stack, method: string) {
130  const numbers: number[] = []
131  for (const layer of stack.layers) {
132    if (!layer.pr) return `${layer.branch} has no pull request yet: run gh stack submit first.`
133    const one = layer.pr === pr.number ? pr : await fetchPr($, layer.pr)
134    if (!one) return `PR #${layer.pr} (${layer.branch}) is not open.`
135    if (!isReady(one)) return `PR #${one.number} (${layer.branch}) is not ready to merge: ${checksEntry(one.checks)[0]}, ${mergeEntry(one)[0]}.`
136    if (!(await isPushed($, layer.branch, one.head))) return `${layer.branch} is not at PR #${one.number}'s head: push or pull first.`
137    numbers.push(one.number)
138  }
139
140  const ran = await $.process.run(['gh', 'stack', 'merge', '--yes', `--${method}`], { timeoutMs: 300_000 })
141  if (ran.exitCode !== 0) return `gh stack merge failed: ${clean((ran.stderr || ran.stdout).trim())}`
142
143  return `Merged stack: PR #${numbers.join(', #')}.${await deleteLayers($, stack)}`
144}
145
146/**
147 * Deletes every layer's branch, local and remote, and switches to the trunk, as `gh pr merge -d` does
148 * for one pull request, which `gh stack merge` has no flag for. It waits until every pull request has
149 * merged, since deleting a head branch while the stack sits in a merge queue would close it.
150 */
151async function deleteLayers($: EngineInterface, stack: Stack) {
152  for (const layer of stack.layers) {
153    const state = await $.process.run(['gh', 'pr', 'view', String(layer.pr), '--json', 'state', '--jq', '.state'], { timeoutMs: 15_000 }).catch(() => null)
154    if (state?.stdout.trim() !== 'MERGED') return ' Branches kept until every pull request has merged.'
155  }
156  const checkout = await $.process.run(['git', 'checkout', stack.trunk]).catch(() => null)
157  if (checkout?.exitCode !== 0) return ` Could not switch to ${stack.trunk}, so the branches were kept.`
158  await $.process.run(['git', 'pull', '--ff-only'], { timeoutMs: 60_000 }).catch(() => null)
159
160  const kept: string[] = []
161  for (const { branch } of stack.layers) {
162    // Fails harmlessly when the repository already deleted the head branch on merge.
163    await $.process.run(['gh', 'api', '-X', 'DELETE', `repos/{owner}/{repo}/git/refs/heads/${branch}`], { timeoutMs: 15_000 }).catch(() => null)
164    const deleted = await $.process.run(['git', 'branch', '-D', branch]).catch(() => null)
165    if (deleted?.exitCode !== 0) kept.push(branch)
166  }
167
168  return kept.length ? ` Switched to ${stack.trunk}, but could not delete ${kept.join(', ')} locally.` : ` Deleted ${stack.layers.map(l => l.branch).join(', ')} and switched to ${stack.trunk}.`
169}
170
171export const register: Register = (on, options) => {
172  const method = typeof options.method === 'string' ? options.method : 'merge'
173
174  on('session.start', async ($, e, next) => {
175    const result = await next(e)
176    await $.command.register({ name: 'merge', description: "Merge this branch's pull request, or its whole stack, once checks pass" })
177    await refresh($)
178    $.clock.every(60_000, () => refresh($))
179
180    return result
181  })
182
183  // A turn may have pushed or opened a pull request.
184  on('turn.complete', async ($, e, next) => {
185    const result = await next(e)
186    if (e.agentId === undefined) void refresh($)
187
188    return result
189  })
190
191  on('command.run', { command: 'merge' }, async $ => {
192    await refresh($)
193    const pr = await read($, current)
194    if (!pr) return { text: 'No open pull request for this branch.' }
195    if (pr.stack) {
196      const text = await mergeStack($, pr, pr.stack, method)
197      await refresh($)
198
199      return { text }
200    }
201    if (!isReady(pr)) return { text: `PR #${pr.number} is not ready to merge: ${checksEntry(pr.checks)[0]}, ${mergeEntry(pr)[0]}.` }
202
203    // --delete-branch drops the local branch, so refuse while it holds commits the PR does not.
204    const local = await $.process.run(['git', 'rev-parse', 'HEAD']).catch(() => null)
205    if (local?.stdout.trim() !== pr.head) return { text: `This branch is not at PR #${pr.number}'s head: push or pull first.` }
206
207    // Pinned to the head that was checked, so a push since then is not merged unchecked.
208    const ran = await $.process.run(['gh', 'pr', 'merge', String(pr.number), `--${method}`, '--delete-branch', '--match-head-commit', pr.head], { timeoutMs: 120_000 })
209    if (ran.exitCode === 0) {
210      // GitHub may still report the pull request as open right after the merge, so clear the band instead of asking.
211      latest += 1
212      await update($, current, () => null)
213    } else {
214      await refresh($)
215    }
216
217    return { text: ran.exitCode === 0 ? `Merged PR #${pr.number}.` : `gh pr merge failed: ${clean((ran.stderr || ran.stdout).trim())}` }
218  })
219
220  on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
221    const pr = await read($, current)
222
223    if (e.props.hasSurvey || !pr) {
224      return next(e)
225    }
226
227    const { Box, Text } = $.ui.resolve(e)
228    const [checks, checksColour] = checksEntry(pr.checks)
229    const [merge, mergeColour] = mergeEntry(pr)
230    // Stack above whatever the plugins beneath draw, so other bands stay.
231    const below = await next(e)
232
233    return (
234      <Box flexDirection="column">
235        <Box flexDirection="row" paddingX={1} gap={2}>
236          <Text dimColor>🔀 PR #{pr.number}</Text>
237          {pr.stack && <Text dimColor>📚 stack {pr.stack.position}/{pr.stack.total}</Text>}
238          <Text color={checksColour} wrap="truncate-end">{checks}</Text>
239          <Text color={mergeColour}>{merge}</Text>
240        </Box>
241        {below}
242      </Box>
243    )
244  })
245}
246
types/index.d.ts 26 lines
1/** How the pull request's checks stand: `failed` names the failing ones. */
2export type Checks = { total: number; passed: number; pending: number; failed: string[] }
3
4/** The unmerged layers of a gh-stack stack, bottom first, where the current branch sits among them, and the trunk they merge into. */
5export type Stack = { position: number; total: number; trunk: string; layers: { branch: string; pr?: number }[] }
6
7/** The open pull request for the current branch, as `gh pr view` last reported it. */
8export type Pr = {
9  number: number
10  url: string
11  /** The head commit the checks ran on. */
12  head: string
13  isDraft: boolean
14  mergeable: string
15  mergeStateStatus: string
16  checks: Checks
17  /** Set when the branch is a layer of a gh-stack stack. */
18  stack?: Stack
19}
20
21declare module 'claude-code' {
22  interface PluginState {
23    'pr-pilot': { pr: Pr | null }
24  }
25}
26