SLOPSHOPPER

auto-handoff

Band above the prompt that watches context fill and saves a HANDOFF.md before you lose your place.

bandcommandtoastprompttimer
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · auto-handoff
› 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 › /auto-handoff ⎿ auto-handoff: auto-handoff on, mode ask, threshold 80%, band shown, context 49% ⎿ auto-handoff: usage: /auto-handoff on|off|now|resume|threshold <n>|mode auto|ask|hide|show|status ⟨Claude Code's own drawing⟩ handoff │ default: opus 5.5 · ctx ▰▰▰▱▱▱ 49% · saves at 80% h: h: save now ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Band
⟨Claude Code's own drawing⟩ handoff │ default: opus 5.5 · ctx ▰▰▰▱▱▱ 49% · saves at 80% h: h: save now
README

lchase

Lawrence Chase's Claude Code marketplace: code review, diagram, test-evidence and software factory skills, plus a set of small Claude Code mods that add band lines and panes to the terminal UI.

/plugin marketplace add lchase/coding-agent-plugins
/plugin install smart-review@lchase
/plugin install tldraw@lchase
/plugin install test-drive@lchase
/plugin install cache-clock@lchase
/plugin install usage-gauge@lchase
/plugin install auto-handoff@lchase
/plugin install agent-watch@lchase
/plugin install recording-mode@lchase
/plugin install factory@lchase

Each plugin is independent; install only what you want. @lchase is the marketplace name (from .claude-plugin/marketplace.json), not the GitHub slug.

Updating

New versions ship whenever the version string in a plugin's manifest changes. Claude Code refreshes marketplaces in the background by default, so you normally pick up updates without doing anything. To pull them right now:

/plugin marketplace update lchase      # refresh this marketplace's manifest
/plugin update smart-review@lchase     # apply a pending update to one plugin
/plugin update tldraw@lchase

/plugin marketplace update (no name) refreshes every marketplace. From a shell: claude plugin marketplace update lchase and claude plugin update <plugin>@lchase.

Reinstalling

If a plugin gets into a bad state (stale cached script, half-applied update), do a clean reinstall:

/plugin uninstall tldraw
/plugin marketplace update lchase
/plugin install tldraw@lchase

Nuclear option, re-register the whole marketplace:

/plugin marketplace remove lchase
/plugin marketplace add lchase/coding-agent-plugins
/plugin install smart-review@lchase
/plugin install tldraw@lchase

Migrating from the old layout

Before this repo became a multi-plugin marketplace it published one plugin from the repo root under a marketplace named chase. If you installed it back then, clear the old registration first:

/plugin uninstall smart-review
/plugin uninstall tldraw            # only if you installed the short-lived tldraw@chase
/plugin marketplace remove chase
/plugin marketplace add lchase/coding-agent-plugins
/plugin install smart-review@lchase
/plugin install tldraw@lchase

The tldraw skill's command also changed: /tldraw:tldraw → /tldraw:diagram.

PluginWhat it doesSkills / commandsHarnesses
smart-reviewEnsemble code review: six specialized lenses over a diff, merged into one deduplicated, severity-ranked verdict/smart-review:{review,min,max,add-pr-review,review-pr-comments} + auto-triggerClaude Code, Cursor, Codex, Gemini CLI, any AGENTS.md agent
tldrawNatural-language description → editable tldraw document (.tldr) + rendered PNG/SVG/tldraw:diagram + auto-triggerClaude Code only (needs Node + npx)
test-driveBefore/after evidence of a UI or API change: record the app before you edit, replay the same scripted scenario after, with a deterministic verdict/test-drive:{baseline,compare} + auto-triggerClaude Code only (needs Node; UI also needs Playwright and ffmpeg)
cache-clockMod: band line showing whether the prompt cache is warm. TTL, expiry, hit ratio, and re-cache size come from Claude Code when the status-line bridge is installed; otherwise the countdown is a marked estimateCompact button (warm only), /cache-clockClaude Code only
usage-gaugeMod: band line with plan usage windows (5-hour, weekly, spend limit), reset times, pace warning, session cost on API billing, threshold toasts/usage-gauge (detail pane)Claude Code only
auto-handoffMod: band line showing how full the chat is; saves a HANDOFF.md at a threshold (auto or on request), then clear and continue or resume in a new session/auto-handoffClaude Code only
agent-watchMod: band line showing who is doing the work this turn (main chat, helper agents, models, tasks, status, skills), plus a pane with per-agent blocks, per-model totals, timeline/agent-watchClaude Code only
recording-modeMod: screen-record without leaking secrets; tells the model to keep keys, emails, private words off screen and masks them in the transcript display only, red REC chip/recClaude Code only
factorySoftware factory: a feature or bug goes through spec-writer, builder, four parallel reviewers and an approver on its own branch, then merges to main or waits for you; live dashboard/factory <input>, /factory {setup,next,approve,rework,serve}Claude Code only (dashboard needs Bun)

smart-review

An ensemble code review: several specialized lenses, one merged verdict, not another pile of comments.

Most code review, human or AI, is one reviewer making a single pass and leaving a list of comments. This runs six specialized lenses instead (spec-conformance, correctness, security, performance, design, and tests), then merges the results into one verdict: duplicates collapsed, findings that several lenses independently raise weighted up, conflicting advice reconciled, severity rolled up, structural problems first, nits capped. The merge is the point. An ensemble without it is just louder, and a longer checklist handed to one reviewer only dilutes its attention and repeats its own misses.

Two modes: a fast single pass (min) for tight loops, and an orchestrated ensemble (max) for pre-merge review. Auto-routing picks between them by change size and sensitivity.

The skill lives in plugins/smart-review/skills/smart-review/ as harness-neutral markdown. Each harness gets a thin manifest pointing at that same directory, so no skill content is copied or forked.

HarnessInstallminmaxSlash commands / auto-trigger
Claude Code/plugin marketplace add lchase/coding-agent-plugins then /plugin install smart-review@lchase✅✅ isolated parallel subagents✅
Cursorpoint Cursor at plugins/smart-review/.cursor-plugin/✅✅ sequential ensemblevia session-start hook
Codexplugins/smart-review/.codex-plugin/ manifest✅✅ sequential ensembleno
Gemini CLIgemini extensions install https://github.com/lchase/coding-agent-plugins (reads root gemini-extension.json)✅✅ sequential ensemblevia GEMINI.md
Any AGENTS.md agentreads root AGENTS.md✅✅ sequential ensembleno

max's isolated parallel subagents are a Claude Code capability. A model panel (plugins/smart-review/skills/smart-review/references/ensemble.md, off by default) rides on top when the harness can route more than one model. Otherwise max is single-model. Elsewhere max runs the same spec-gate, six lenses, and merge as a disciplined sequential walk. Design and internals: plugins/smart-review/SMART-REVIEW.md.

Claude Code slash commands:

  • /smart-review:review: auto (routes to min or max by size + sensitivity)
  • /smart-review:min: fast single-pass review
  • /smart-review:max: orchestrated ensemble review
  • /smart-review:add-pr-review <PR number or URL>: reviews a GitHub PR and, after you confirm what to publish, posts the findings as PR comments
  • /smart-review:review-pr-comments <PR number or URL>: triages a PR's existing unresolved review comments, fixes or explains each after your approval, replies, and resolves the thread

The skill also triggers automatically when you ask Claude to review a diff, PR, or branch.


tldraw

Turn a described diagram (flowchart, architecture / system diagram, process map, decision tree, state machine) into two artifacts: an editable .tldr document (opens at tldraw.com or in the tldraw editor) and a rendered PNG/SVG for docs and PRs.

Claude writes a {nodes, edges} spec from your description; a bundled Node script does a simple layered auto-layout, emits the .tldr, and renders images by loading it into a headless-Chromium tldraw instance via @kitschpatrol/tldraw-cli (first run downloads Chromium, ~1 min, cached).

/plugin install tldraw@lchase

Claude Code only. Skill: /tldraw:diagram (also auto-triggers on "draw this diagram", "diagram this flow", "make a tldraw of…"). Details: plugins/tldraw/skills/diagram/SKILL.md.


test-drive

A test drive is an e2e test that happens to produce video, and the "before" is part of the process rather than something reconstructed later. Run /test-drive:baseline before you edit: it writes a short browser scenario and records the app as it stands. Make the change, then run /test-drive:compare: it replays the identical scenario with Playwright and composes a labeled side-by-side MP4. The pass/warn/fail verdict comes from the scenario's assertions, not from reading the video.

Backend changes work the same way with "kind": "api": the scenario is a list of HTTP steps (method, path, body, expected status, JSON fields, and server-log lines to expect or avoid). There is nothing to screen-record, so each step captures the request, the response, and the server log lines it produced, and compare writes a before/after report.md instead of a video. Secrets are redacted from the stored transcript (best effort, extendable per scenario with redact), and the finished report is scanned and flagged if anything still looks secret.

/plugin install test-drive@lchase

Claude Code only. UI scenarios need ffmpeg and Playwright in the repo under test; API scenarios need only Node 18+. Only the working tree is ever run, so there is no second checkout to boot. Details: baseline and compare.


Claude Code mods

Five small plugins that change Claude Code's own interface instead of adding a task skill. Each draws a band line above the prompt (some add a side pane or slash command), is independent of the others, and works on Claude Code only.

  • cache-clock: is the prompt cache still warm? After /cache-clock setup, the countdown, TTL, hit ratio, re-cache size, and last miss cause come from Claude Code's own prompt_cache (v2.1.251+). Without that, the band uses your promptCacheTtl or cache environment variables, and only then a fallback (cacheMinutes, default 5) marked with ?. Compact is offered only while the cache is warm. Dollar figures stay hand-kept list-price estimates.
  • usage-gauge: plan usage windows (5-hour, weekly, spend limit) with reset times and a pace warning; session cost on API billing; threshold toasts. /usage-gauge opens a detail pane.
  • auto-handoff: watches context fill and saves a HANDOFF.md at a threshold (automatically or on request), then clears and continues, or resumes in a new session. /auto-handoff.
  • agent-watch: who is doing the work this turn: main chat, helper agents, models, tasks, status, skills. /agent-watch opens a pane with per-agent blocks, per-model totals, and a timeline.
  • recording-mode: for screen recordings. Tells the model to keep keys, emails, and private words off screen and masks them in the transcript display only (the underlying transcript is untouched). Red REC chip, /rec to toggle.
/plugin install cache-clock@lchase    # or usage-gauge, auto-handoff, agent-watch, recording-mode

cache-clock and the status line

Claude Code tells a status-line script whether the prompt cache is warm, when it expires, and the session hit ratio (prompt_cache on the status-line JSON, v2.1.251 or later). A plugin cannot register a status line, and the mods API does not include those fields, so cache-clock reads them through a small bridge.

In Claude Code, run:

/cache-clock setup

That edits your user settings (~/.claude/settings.json, or $CLAUDE_CONFIG_DIR/settings.json when that variable is set). It saves whatever statusLine was there and points statusLine at cache-clock/bridge.mjs, which still runs your previous status line and writes Claude Code's prompt_cache for the band to read. /cache-clock remove puts the previous value back. node must be on PATH. Setup refuses to edit a status line that comes from managed settings, --settings, or a project or local settings file.

The same edit by hand, when you have no status line yet:

{
  "statusLine": {
    "type": "command",
    "command": "node ~/.claude/cache-clock/bridge.mjs"
  }
}

Run /cache-clock setup once so the script is copied into that folder. After the next reply the band's TTL and expiry are Claude Code's figures, not a guess. The band redraws every 30 seconds from the last expires_at. Claude Code also re-runs the status line on its own events, and when a warm cache reaches expires_at.

Until the bridge is installed, the band still works. It follows this order: prompt_cache if the bridge has written it, then FORCE_PROMPT_CACHING_5M, CLAUDE_CODE_PROMPT_CACHE_TTL, the promptCacheTtl setting, ENABLE_PROMPT_CACHING_1H, then the cacheMinutes option (5 or 60, default 5). Only that last step is marked with ?. A subscription within plan usage is often 60 minutes and an API key, cloud provider, or usage-credit session is often

  1. The option cannot see a mid-session change; the bridge can.

/cache-clock status names which of those sources the band is using.


factory

A small, visual software factory. /factory <input> takes a feature or bug as text, a path to a requirements .md, an issue key or URL, or a GitHub issue, and runs it through a fixed loop: spec-writer writes a spec with testable acceptance criteria, builder implements it in its own git worktree (via the Orca CLI when present, so .env and setup hooks come along, else plain git worktree), four reviewers (security, ux, ui, code) run in parallel and each writes a VERDICT: PASS | CHANGES file, the builder is resumed while any review says CHANGES (max two rounds), then an approver writes APPROVE or ESCALATE. APPROVE merges to main locally; ESCALATE parks the job as needs-human.

/plugin install factory@lchase

Then, in a repo:

/factory setup                          # once per repo: profiles it into .factory/repo.md, review that file
/factory <text | path.md | KEY-123 | #123>
/factory next                           # first unchecked item in .factory/backlog.md
/factory approve <job-id>               # merge a needs-human job
/factory rework <job-id> <note>         # send it back to the builder with your note
/factory serve                          # live board at http://localhost:8765 (needs Bun)

Nothing repo-specific is baked in: commands, conventions, commit rules, issue tracker and the approver's never-auto-merge list all come from .factory/repo.md, which /factory setup drafts and you edit. Job state is .factory/jobs/<id>/ (gitignored), one folder of markdown per job, so several sessions can run jobs at once and the dashboard shows them all.

Claude Code only. Dashboard needs Bun. Full guide, including what happens when a job stops for you: plugins/factory/README.md.


Token-savings benchmark

benchmarks/token-savings/ compares stock Claude Code with plugins and settings that claim to cut tokens or cost. It is not a marketplace plugin. Click 8.5.0 is fetched at a pinned commit when you run it. The full matrix calls the Anthropic API and has a hard ceiling of $600 at the default per-session cap. Read the benchmark README before you run it. ./benchmarks/token-savings/check.sh is the offline check and does not spend API money.

Repo layout

.claude-plugin/marketplace.json   # the "lchase" marketplace: 9 plugin entries
AGENTS.md                         # repo-level agent pointer (→ smart-review)
gemini-extension.json + GEMINI.md # Gemini CLI installs the repo as an extension (→ smart-review)

plugins/smart-review/             # plugin 1, multi-harness code review
  .claude-plugin/plugin.json
  skills/smart-review/            # the harness-neutral core (SKILL.md + references/)
  agents/ commands/ hooks/        # Claude Code packaging
  .cursor-plugin/ .codex-plugin/  # thin per-harness manifests
  scripts/                        # validate-adapters.sh, bump-version.sh
  evals/                          # dev-only eval kit (not shipped to installers)
  SMART-REVIEW.md                 # design writeup

plugins/tldraw/                   # plugin 2, Claude Code only
  .claude-plugin/plugin.json
  skills/diagram/                 # SKILL.md + scripts/build-tldr.mjs + references/

plugins/test-drive/               # plugin 3, Claude Code only
  .claude-plugin/plugin.json
  skills/{baseline,compare}/      # SKILL.md each
  scripts/{lib.mjs,record.mjs,record-api.mjs,redact.mjs,verdict.mjs,compose.sh,report.mjs}   # shared by both skills
  references/                     # UI and API scenario schemas + examples

plugins/factory/                  # plugin 4, Claude Code only
  .claude-plugin/plugin.json
  skills/factory/SKILL.md         # the orchestrator loop, commands, setup, job.json and repo.md schemas
  agents/                         # spec-writer, builder, review-{security,ux,ui,code}, approver, repo-profiler
  dashboard/                      # dashboard.html + serve.ts (Bun) + example/ dummy jobs

plugins/{cache-clock,usage-gauge,auto-handoff,agent-watch,recording-mode}/   # plugins 5-9, Claude Code mods
  .claude-plugin/plugin.json      # each with its own version
  hooks/                          # register.tsx (the mod) + hooks.json, tests where present
  types/                          # mod API typings

benchmarks/token-savings/         # paired Claude Code cost benchmark (not a plugin)

Developing

claude plugin validate .                                # marketplace + all plugins
./plugins/smart-review/scripts/validate-adapters.sh      # smart-review's per-harness manifests
./benchmarks/token-savings/check.sh                      # benchmark lint and graders; no API spend
claude plugin test plugins/cache-clock                   # mod tests, including the native prompt_cache path
node --test plugins/cache-clock/statusline/bridge.test.mjs

Releasing: users only get an update when a plugin's version string changes, so bump it on every user-facing change and push to main.

  • smart-review: version is pinned across all its manifests; bump them together with ./plugins/smart-review/scripts/bump-version.sh <version>.
  • tldraw, test-drive, factory, and each mod: version independently; edit that plugin's .claude-plugin/plugin.json.

Once pushed, installed clients pick it up on their next background marketplace refresh, or immediately with /plugin marketplace update lchase.

Source 2 files
hooks/register.tsx 444 lines
1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, Register, RenderElement } from 'claude-code'
3
4import type { Band } from '../types'
5
6type Mode = 'auto' | 'ask'
7type Settings = { on: boolean; mode: Mode; threshold: number; hidden: boolean }
8
9const DEFAULTS: Settings = { on: true, mode: 'ask', threshold: 80, hidden: false }
10const FRESH_MS = 10 * 60 * 1000
11const FILE = 'HANDOFF.md'
12
13const BRANCH_COLOR = '#b794f4'
14const BRANCH_MAX = 24
15const GREEN = '#4ade80'
16const AMBER = '#fbbf24'
17const RED = '#f87171'
18
19const FALLBACK_SAVE =
20  `Write a handoff for this session to ${FILE} in the current folder, so a fresh chat can continue without me. ` +
21  'Use these sections: Objective, Done / In progress / Next, Decisions and why, Open questions, Exact next step. ' +
22  'Be concrete (file paths, commands, names). Write the file now, then reply with one line.'
23const FALLBACK_RESUME =
24  `Read ${FILE} in the current folder and continue the work from its "Exact next step". ` +
25  'Summarise the objective back to me in one line first.'
26
27const IDLE: Band = { percent: null, phase: 'idle', savedAt: null, seen: 0, from: null, model: null, effort: null }
28const band = atom({ plugin: 'auto-handoff', key: 'band' } as const, IDLE)
29
30const clamp = (n: number, lo: number, hi: number) => Math.min(hi, Math.max(lo, n))
31
32export const ago = (ms: number): string => {
33  const mins = Math.floor(Math.max(0, ms) / 60000)
34  if (mins < 1) return 'just now'
35  if (mins < 60) return `${mins}m ago`
36  const hours = Math.floor(mins / 60)
37  if (hours < 24) return `${hours}h ago`
38  return `${Math.floor(hours / 24)}d ago`
39}
40
41const hhmm = (ms: number): string => {
42  const d = new Date(ms)
43  const p = (n: number) => String(n).padStart(2, '0')
44  return `${p(d.getHours())}:${p(d.getMinutes())}`
45}
46
47// claude-sonnet-5-5 -> "sonnet 5.5"; unknown ids pass through
48// control chars stripped so a crafted model id or effort cannot inject terminal escapes
49export const plain = (v: string | number): string => String(v).replace(/[\x00-\x1f\x7f-\x9f]/g, '')
50
51export const modelLabel = (raw: string): string => {
52  const id = plain(raw)
53  const m = id.match(/^claude-([a-z]+)-(\d+)(?:-(\d+))?/)
54  return m ? `${m[1]} ${m[2]}${m[3] ? `.${m[3]}` : ''}` : id
55}
56
57export const meter = (percent: number): string => {
58  const filled = clamp(Math.round((percent / 100) * 6), 0, 6)
59  return '▰'.repeat(filled) + '▱'.repeat(6 - filled)
60}
61
62export const objectiveOf = (text: string): string => {
63  const lines = text.split('\n')
64  const at = lines.findIndex(l => /objective/i.test(l))
65  if (at < 0) return ''
66  const inline = lines[at]!.replace(/^[#*\s>-]*objective[:*\s]*/i, '').trim()
67  const raw = inline || lines.slice(at + 1).find(l => l.trim() !== '' && !/^#/.test(l.trim())) || ''
68  const clean = raw.replace(/^[\s>*-]+/, '').replace(/[*_`]/g, '').trim()
69  return clean.length > 60 ? `${clean.slice(0, 59)}…` : clean
70}
71
72async function load($: EngineInterface): Promise<Settings> {
73  const raw = (await $.store.get('settings')) as Partial<Settings> | undefined
74  const s = { ...DEFAULTS, ...(raw && typeof raw === 'object' ? raw : {}) }
75  s.threshold = clamp(Math.round(Number(s.threshold) || DEFAULTS.threshold), 10, 99)
76  s.mode = s.mode === 'auto' ? 'auto' : 'ask'
77  return s
78}
79
80async function save($: EngineInterface, s: Settings) {
81  await $.store.set('settings', s)
82  $.ui.invalidate('ui.render')
83}
84
85// control chars stripped so a crafted branch name cannot inject terminal escapes
86export const branchFromHead = (head: string): string =>
87  (head.match(/^ref: refs\/heads\/(.+)$/m)?.[1]?.trim() ?? head.trim().slice(0, 7)).replace(/[\x00-\x1f\x7f-\x9f]/g, '')
88
89// a .git pointer file is untrusted: follow it only to a local worktree/submodule gitdir, never a UNC or network path (any two leading slashes, either kind, are UNC on Windows)
90export const isSafeGitdir = (p: string): boolean => !/^[\\/]{2}/.test(p) && /^(\/|[A-Za-z]:[\\/])/.test(p) && /[\\/]\.git[\\/](worktrees|modules)[\\/]/.test(p)
91
92// ponytail: reads .git/HEAD from the cwd up (5 levels), no git subprocess. Worktrees follow the .git pointer file.
93async function readBranch($: EngineInterface): Promise<string> {
94  let dir = '.'
95  for (let i = 0; i < 5; i++, dir += '/..') {
96    const head = await $.fs.read(`${dir}/.git/HEAD`).catch(() => '')
97    if (head) return branchFromHead(head)
98    const ptr = ((await $.fs.read(`${dir}/.git`).catch(() => '')) as string).match(/^gitdir: (.+)$/m)?.[1]
99    if (ptr && isSafeGitdir(ptr.trim())) return branchFromHead(await $.fs.read(`${ptr.trim()}/HEAD`).catch(() => ''))
100  }
101  return ''
102}
103
104async function mtimeOf($: EngineInterface): Promise<number | undefined> {
105  const stat = await $.fs.stat(FILE).catch(() => undefined)
106  return stat ? (stat.mtimeMs as number) : undefined
107}
108
109async function hasCommand($: EngineInterface, name: string): Promise<boolean> {
110  return (await $.command.list()).some((c: { name: string }) => c.name === name)
111}
112
113async function runSave($: EngineInterface) {
114  try {
115    if (await hasCommand($, 'handoff')) await $.command.run({ command: 'handoff' })
116    else await $.prompt.submit({ text: FALLBACK_SAVE })
117  } catch (err) {
118    $.ui.toast(`auto-handoff: could not save (${(err as Error).message})`)
119  }
120}
121
122async function runResume($: EngineInterface) {
123  try {
124    if (await hasCommand($, 'handoff')) await $.command.run({ command: 'handoff', args: 'resume' })
125    else await $.prompt.submit({ text: FALLBACK_RESUME })
126  } catch (err) {
127    $.ui.toast(`auto-handoff: could not resume (${(err as Error).message})`)
128  }
129}
130
131// Slash commands run from a timer, never inside the hook the turn waits on.
132function later($: EngineInterface, fn: () => Promise<void>) {
133  $.clock.after(50, () => void fn())
134}
135
136async function startSave($: EngineInterface, why: 'threshold' | 'manual') {
137  await update($, band, (b): Band => ({ ...b, phase: 'saving', from: null }))
138  if (why === 'manual') $.ui.toast('Saving a handoff')
139  later($, () => runSave($))
140}
141
142async function clearAndContinue($: EngineInterface) {
143  await $.store.set('resumeAfterClear', true)
144  later($, async () => {
145    try {
146      await $.command.run({ command: 'clear' })
147    } catch (err) {
148      await $.store.delete('resumeAfterClear')
149      $.ui.toast(`auto-handoff: /clear failed (${(err as Error).message})`)
150      return
151    }
152    // A real /clear fires session.start, which consumes the flag. If it did not, finish here.
153    await $.clock.sleep(1500)
154    if ((await $.store.get('resumeAfterClear')) === true) {
155      await $.store.delete('resumeAfterClear')
156      await runResume($)
157    }
158  })
159}
160
161async function warnStale($: EngineInterface) {
162  const s = await load($)
163  const mtime = (await mtimeOf($)) ?? ((await $.store.get('lastHandoffAt')) as number | undefined)
164  const now = await $.clock.now()
165  const isFresh = mtime !== undefined && now - mtime < FRESH_MS
166  if (s.on && !isFresh) $.ui.toast('Compacting without a fresh handoff')
167}
168
169async function detectSaved($: EngineInterface) {
170  const mtime = await mtimeOf($)
171  if (mtime === undefined) return
172  const b = await read($, band)
173  if (mtime > b.seen && b.phase !== 'saved') {
174    await $.store.set('lastHandoffAt', mtime)
175    await update($, band, (cur): Band => ({ ...cur, phase: 'saved', savedAt: mtime, seen: mtime }))
176  }
177}
178
179export const register: Register = on => {
180  on('session.start', async ($, e, next) => {
181    await $.command.register({
182      name: 'auto-handoff',
183      description: 'Context watcher: on|off|now|resume|threshold <n>|mode auto|ask|hide|show|status',
184      argumentHint: 'on|off|now|resume|threshold <n>|mode auto|ask|hide|show|status',
185    })
186
187    const mtime = await mtimeOf($)
188    const now = await $.clock.now()
189    const resumeFlag = (await $.store.get('resumeAfterClear')) === true
190
191    // Load-time baseline: a file already there is "seen", not "just saved".
192    const model = await $.session.model().catch(() => null)
193    const percent = (await $.session.usage().catch(() => null))?.context.percent
194    await update($, band, () => ({
195      ...IDLE,
196      percent: typeof percent === 'number' ? percent : null,
197      model,
198      seen: mtime ?? 0,
199      from: mtime !== undefined && !resumeFlag ? { at: mtime, objective: '' } : null,
200    }))
201
202    if (resumeFlag) {
203      await $.store.delete('resumeAfterClear')
204      later($, () => runResume($))
205    } else if (mtime !== undefined) {
206      const text = await $.fs.read(FILE).catch(() => '')
207      const objective = objectiveOf(text)
208      await update($, band, b => ({ ...b, from: { at: mtime, objective } }))
209      const s = await load($)
210      if (s.on) $.ui.toast(`Handoff from ${ago(now - mtime)} available, /handoff resume`)
211    }
212
213    $.clock.every(4000, () => void detectSaved($))
214
215    return next(e)
216  })
217
218  on('turn.step', async function* ($, e, next) {
219    const b = await read($, band)
220    const effort = e.effort ?? null
221    if (b.model !== e.model || b.effort !== effort) await update($, band, cur => ({ ...cur, model: e.model, effort }))
222    return yield* next(e)
223  })
224
225  on('prompt.submit', async ($, e, next) => {
226    await update($, band, cur => (cur.from === null ? cur : { ...cur, from: null })).catch(() => undefined)
227    return next(e)
228  })
229
230  on('turn.complete', async ($, e, next) => {
231    if (e.agentId === undefined) await detectSaved($)
232    return next(e)
233  })
234
235  on('session.measure', async ($, e, next) => {
236    const percent = e.context.percent
237    if (typeof percent === 'number') {
238      const s = await load($)
239      const b = await read($, band)
240      const below = percent < s.threshold
241
242      if (b.percent !== percent) await update($, band, cur => ({ ...cur, percent }))
243
244      if (s.on && !below && b.phase === 'idle') {
245        $.ui.toast(`Chat is ${s.threshold}% full, saving a handoff`)
246        if (s.mode === 'auto') await startSave($, 'threshold')
247        else await update($, band, (cur): Band => ({ ...cur, phase: 'ask' }))
248      } else if (below && (b.phase === 'ask' || b.phase === 'saved')) {
249        // Context shrank (compact or clear): arm again.
250        await update($, band, (cur): Band => ({ ...cur, phase: 'idle' }))
251      }
252    }
253    return next(e)
254  })
255
256  on('session.compact', async ($, e, next) => {
257    if (e.agentId === undefined && e.trigger !== 'precompute') {
258      await warnStale($).catch(() => undefined)
259    }
260    return next(e)
261  })
262
263  on('command.run', { command: 'auto-handoff' }, async ($, e) => {
264    const [verb = 'status', arg] = e.args.trim().split(/\s+/)
265    const s = await load($)
266    const b = await read($, band)
267    const line = `auto-handoff ${s.on ? 'on' : 'off'}, mode ${s.mode}, threshold ${s.threshold}%, band ${s.hidden ? 'hidden' : 'shown'}, context ${b.percent ?? '?'}%`
268
269    switch (verb.toLowerCase()) {
270      case 'on':
271      case 'off':
272        await save($, { ...s, on: verb.toLowerCase() === 'on' })
273        return { text: `auto-handoff ${verb.toLowerCase()}` }
274      case 'hide':
275      case 'show':
276        await save($, { ...s, hidden: verb.toLowerCase() === 'hide' })
277        return { text: `band ${verb.toLowerCase() === 'hide' ? 'hidden' : 'shown'}` }
278      case 'mode':
279        if (arg !== 'auto' && arg !== 'ask') return { text: 'usage: /auto-handoff mode auto|ask' }
280        await save($, { ...s, mode: arg })
281        return { text: `mode ${arg}` }
282      case 'threshold': {
283        const n = Number(arg)
284        if (!Number.isFinite(n) || n < 10 || n > 99) return { text: 'usage: /auto-handoff threshold <10-99>' }
285        await save($, { ...s, threshold: Math.round(n) })
286        return { text: `threshold ${Math.round(n)}%` }
287      }
288      case 'now':
289        await startSave($, 'manual')
290        return { text: 'saving a handoff' }
291      case 'resume':
292        later($, () => runResume($))
293        return { text: 'resuming from HANDOFF.md' }
294      case 'status':
295        return { text: line }
296      default:
297        return { text: `${line}\nusage: /auto-handoff on|off|now|resume|threshold <n>|mode auto|ask|hide|show|status` }
298    }
299  })
300
301  on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
302    const below = await next(e)
303    const s = await load($)
304    const b = await read($, band)
305
306    if (e.props.hasSurvey || !s.on || s.hidden) return below
307
308    const { Box, Text, Button } = $.ui.resolve(e)
309    const now = await $.clock.now()
310    const branch = await readBranch($)
311    const isDefault = branch === 'main' || branch === 'master'
312    const shown = branch.length > BRANCH_MAX ? `${branch.slice(0, BRANCH_MAX - 1)}…` : branch
313    const stack = (line: RenderElement) =>
314      below ? (
315        <Box flexDirection="column">
316          {below}
317          {line}
318        </Box>
319      ) : (
320        line
321      )
322
323    if (e.surface !== 'terminal') {
324      // proportional fonts collapse the padded chip, │ and ▰▱ cells: a gapped row, an Svg meter, native buttons
325      const { Svg } = $.ui.resolve(e)
326      const resume = () => {
327        later($, () => runResume($))
328        return update($, band, cur => ({ ...cur, from: null }))
329      }
330      let parts
331      let action = null
332      if (b.phase === 'saved' && b.savedAt !== null) {
333        parts = [<Text color={GREEN}>✓ saved {hhmm(b.savedAt)}</Text>]
334        action = <Button key="clear" hotkey="c" label="Clear & continue" onPress={() => clearAndContinue($)} />
335      } else if (b.phase === 'idle' && b.from !== null && b.percent !== null && b.percent < s.threshold && b.from.at > 0) {
336        parts = [<Text>from {ago(now - b.from.at)}: {b.from.objective === '' ? 'handoff' : b.from.objective}</Text>]
337        action = <Button key="resume" hotkey="r" label="Resume" onPress={resume} />
338      } else {
339        const percent = b.percent ?? 0
340        const isHot = b.phase === 'ask' || b.phase === 'saving' || percent >= s.threshold
341        const color = isHot ? RED : percent >= 60 ? AMBER : GREEN
342        const fill = Math.round((clamp(percent, 0, 100) / 100) * 56)
343        const mark = Math.round((s.threshold / 100) * 56)
344        parts = [
345          b.model !== null ? <Text dimColor>{modelLabel(b.model)}{b.effort !== null ? ` ${plain(b.effort)}` : ''}</Text> : null,
346          <Text dimColor>ctx</Text>,
347          <Svg
348            source={`<svg xmlns="http://www.w3.org/2000/svg" width="56" height="8" viewBox="0 0 56 8"><rect width="56" height="8" rx="4" fill="#8080804d"/><rect width="${fill}" height="8" rx="4" fill="${color}"/><rect x="${mark - 1}" width="2" height="8" fill="${AMBER}"/></svg>`}
349            alt={`context ${Math.round(percent)}%, saves at ${s.threshold}%`}
350            width={56}
351            height={8}
352          />,
353          <Text color={color}>{Math.round(percent)}%</Text>,
354          b.phase === 'saving' ? (
355            <Text dimColor>saving handoff…</Text>
356          ) : (
357            <Text dimColor>
358              {s.mode === 'auto' ? 'auto-saves' : 'saves'} at <Text bold color={AMBER}>{s.threshold}%</Text>
359            </Text>
360          ),
361        ]
362        if (b.phase !== 'saving') action = <Button key="save" hotkey="h" label="Save now" onPress={() => startSave($, 'manual')} />
363      }
364
365      return stack(
366        <Box flexDirection="row" alignItems="center">
367          <Box width={9} flexShrink={0}><Text dimColor bold>handoff</Text></Box>
368          <Box flexDirection="row" alignItems="center" flexWrap="wrap" flexGrow={1} gap={1}>
369            {parts}
370            {branch !== '' && <Text color={isDefault ? undefined : BRANCH_COLOR} dimColor={isDefault}>⎇ {shown}</Text>}
371            {/* native buttons stand taller than a text row: keep them at the trailing edge */}
372            <Box flexGrow={1} />
373            {action}
374          </Box>
375        </Box>,
376      )
377    }
378
379    const chip = (
380      <Text dimColor>{'handoff │ '}</Text>
381    )
382
383    let body
384    if (b.phase === 'saved' && b.savedAt !== null) {
385      body = (
386        <Box>
387          <Text color={GREEN}>{`✓ saved ${hhmm(b.savedAt)} `}</Text>
388          <Button key="clear" plain hotkey="c" label="clear & continue" onPress={() => clearAndContinue($)} />
389        </Box>
390      )
391    } else if (b.phase === 'idle' && b.from !== null && b.percent !== null && b.percent < s.threshold && b.from.at > 0) {
392      const what = b.from.objective === '' ? 'handoff' : b.from.objective
393      body = (
394        <Box>
395          <Text>{`from ${ago(now - b.from.at)}: ${what} `}</Text>
396          <Button
397            key="resume"
398            plain
399            hotkey="r"
400            label="resume"
401            onPress={() => {
402              later($, () => runResume($))
403              return update($, band, cur => ({ ...cur, from: null }))
404            }}
405          />
406        </Box>
407      )
408    } else {
409      const percent = b.percent ?? 0
410      const isHot = b.phase === 'ask' || b.phase === 'saving' || percent >= s.threshold
411      const color = isHot ? RED : percent >= 60 ? AMBER : GREEN
412      // filled cells in the level color, empty cells dim
413      const cells = meter(percent)
414      body = (
415        <Box>
416          {b.model !== null && <Text dimColor>{`default: ${modelLabel(b.model)}${b.effort !== null ? ` ${plain(b.effort)}` : ''} · `}</Text>}
417          <Text dimColor>ctx </Text>
418          <Text color={color}>{cells.replace(/▱/g, '')}</Text>
419          <Text dimColor>{cells.replace(/▰/g, '')}</Text>
420          <Text color={color}>{` ${Math.round(percent)}% `}</Text>
421          {b.phase === 'saving' ? (
422            <Text dimColor>· saving handoff… </Text>
423          ) : (
424            <Box>
425              <Text dimColor>{`· ${s.mode === 'auto' ? 'auto-saves' : 'saves'} at `}</Text>
426              <Text bold color={AMBER}>{`${s.threshold}% `}</Text>
427              <Button key="save" plain hotkey="h" label="h: save now" onPress={() => startSave($, 'manual')} />
428            </Box>
429          )}
430        </Box>
431      )
432    }
433
434    return stack(
435      <Box>
436        {chip}
437        <Text> </Text>
438        {body}
439        {branch !== '' && (isDefault ? <Text dimColor>{` ⎇ ${shown}`}</Text> : <Text color={BRANCH_COLOR}>{` ⎇ ${shown}`}</Text>)}
440      </Box>,
441    )
442  })
443}
444
types/index.d.ts 18 lines
1export type Phase = 'idle' | 'ask' | 'saving' | 'saved'
2
3export type Band = {
4  percent: number | null
5  phase: Phase
6  savedAt: number | null
7  seen: number
8  from: { at: number; objective: string } | null
9  model: string | null
10  effort: string | number | null
11}
12
13declare module 'claude-code' {
14  interface PluginState {
15    'auto-handoff': { band: Band }
16  }
17}
18