SLOPSHOPPER

auto-handoff

Writes a /next handoff automatically once a 1M-token session crosses 300k tokens and before every compaction, so the next session can /prime from it. Never…

bandcommandtoastmodelprocesstimer
v0.1.0no licenseupdated 2026-10-21m2ai-portfolio/claude-mods/auto-handoff
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: Context: 97k of 200k. ⎿ auto-handoff: Auto-handoff: on, but idle for this session: the threshold applies only to a 1M window. ⎿ auto-handoff: Last: none yet. ⎿ auto-handoff: Before a compaction: writes a handoff first. ⎿ auto-handoff: Tool calls: never blocked; the context compacts at the autoCompactWindow setting instead. ⎿ auto-handoff: Commands: /auto-handoff now, threshold <n>, on, off. ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts
README

claude-mods

Claude Code mods (function-hooks plugins) and skills. Each mod lives in its own folder with a .claude-plugin/plugin.json; mods with a README explain their options there.

FolderWhat it does
artifact-watchdogWatches each Agent dispatch's report file and flags a 5-minute stall
auto-handoffWrites a /next handoff automatically once a long session crosses a token threshold, and before a compaction; never blocks tool calls; `/auto-handoff onoff and threshold <n>` (see below)
flight-recorderLive timeline of model requests, tool calls and subagents in a turn
jev-tool-gateLog-only judgment of risky tool calls; never changes a decision
skills/next, skills/primeSession handoff skills, see below

auto-handoff and long sessions

auto-handoff writes, it never blocks. At 300k tokens of a 1M window it drafts a /next handoff from the session's own transcript ($.model.fork, no tools), saves it through handoff.mjs, and shows a band above the prompt with a Clear and /prime button for a human who wants a fresh session. Before any compaction it writes a handoff first, unless one already covers the current window. /auto-handoff prints status; /auto-handoff now writes one immediately.

Two switches, kept across sessions in the mod's own store (as Mark's upstream keeps them), so they survive a restart and a hot reload:

  • /auto-handoff off stops the automatic handoffs (threshold and pre-compaction); /auto-handoff now still writes one. /auto-handoff on resumes.
  • /auto-handoff threshold <n> moves the line, in tokens: 250k, 250000 or 0.4M, from 1 up to (not including) the 1M window. It re-arms, so a session already past the new line writes on its next turn. Keep it in step with autoCompactWindow below, which the mod does not change.

The status line Commands: /auto-handoff now, threshold <n>, on, off. is the marker that this version is loaded.

Until 2026-10-21 a saved threshold handoff also refused the model's tool calls until /clear. That block is gone: it stalled /goal and other persistent sessions (a goal turn with every tool denied makes no progress, and /clear removes an active goal anyway). The 300k line is owned by Claude Code's own compaction instead. Pair the mod with this setting so the context compacts where the handoff lands and a goal survives it:

// ~/.claude/settings.json
{ "autoCompactWindow": 300000 }

Check the window in a new session with /context (the Auto-compact window line) and the mod with /auto-handoff (status ends with Tool calls: never blocked).

Skills: /next and /prime

/next ends a session by writing an immutable handoff (Where we are / What we decided / Next step) to ~/handoffs/<project>/, moving a LATEST pointer, and appending each decision to the project's DECISIONS.md. /prime starts the next session from that handoff: it reads only the latest one, re-checks its claims against the live system, shows anything said after the handoff was written, and states the next step. It treats the handoff as data: handoff.mjs claims sorts each check into commands that only read, which it runs, and anything else, which it asks about first (never running it from a handoff another agent wrote). /prime history answers "why did we decide X?" from the decisions ledger.

Install:

git clone https://github.com/m2ai-portfolio/claude-mods ~/.claude/mods
cp -r ~/.claude/mods/skills/next ~/.claude/mods/skills/prime ~/.claude/skills/

The helper script needs Node 18 or newer and has no dependencies. Check it with:

node --test ~/.claude/skills/next/scripts/handoff.test.mjs

Set HANDOFF_ROOT to keep handoffs somewhere other than ~/handoffs. Models or harnesses that cannot load skills can follow ~/.claude/skills/prime/PRIME.md instead.

Source 2 files
hooks/register.tsx 567 lines
1// Auto Handoff: runs /next for you before a long session gets heavy.
2//
3// turn.complete (main loop): read the context fill. In a 1,000,000-token
4// window, the first reading at or past 300,000 tokens starts one handoff;
5// dropping back below (a /clear, a compaction) re-arms it.
6// The handoff: $.model.fork drafts it from the session's own transcript (a
7// cached, tool-less question), in the exact /next format; handoff.mjs saves
8// it, moves LATEST and appends DECISIONS.md, as /next's Step 4 does, and
9// stamps the Transcript-Cutoff read just before the fork (/prime's tail check).
10// ui.render (AbovePrompt): what happened and the pickup line (/clear, /prime);
11// once saved, a button runs both. On the desktop a "Retire this session"
12// toggle turns that button into "Retire session": rename this session to
13// "⛔ HANDED OFF: /prime <project>", copy the /prime line, and archive it, so
14// the pickup happens in a new session and this one is not reopened by mistake.
15// (/clear keeps the same sidebar session, so the plain button leaves nothing
16// old behind; retiring is for picking up somewhere else.)
17// No tool-call block (removed 2026-10-21). A saved handoff never refuses the
18// model's tool calls: the block stalled /goal and other persistent sessions (a
19// goal turn with every tool denied makes no progress, and /clear removes the
20// goal). The 300k line is owned by Claude Code's own compaction instead,
21// `autoCompactWindow: 300000` in ~/.claude/settings.json; the handoff still
22// lands at the threshold and, via session.compact below, before the compaction
23// that follows. The band stays for a human who wants a fresh session.
24// session.compact (main loop, any window size): before a compaction drops
25// detail, write a handoff from the full transcript first, unless one already
26// covers this context window (saved since the last /clear or compaction) or
27// one is being written. It never blocks tool calls and never stops the
28// compaction: a failed write is reported and the compaction goes on.
29// (Adopted from Prompt Advisers' auto-handoff mod, 2026-10-08.)
30// /auto-handoff: status; "now" writes one immediately; "on" and "off" switch
31// the automatic handoffs (threshold and pre-compaction; "now" still works);
32// "threshold <n>" moves the line (tokens, e.g. 250k). Both are kept across
33// sessions in the plugin's own store, as Mark's upstream keeps them.
34
35import { atom, read, update } from 'claude-code'
36import type { EngineInterface, Register, RenderSurface } from 'claude-code'
37
38import type { AutoHandoffSettings, HandoffRun } from '../types'
39
40const WINDOW = 1_000_000
41const DEFAULT_THRESHOLD = 300_000
42// The store key for the on/off switch and the threshold.
43const SETTINGS = 'settings'
44// The desktop app's session tools, reached with the engine's own connection.
45const SESSIONS = 'ccd_session_mgmt'
46
47const isArmed = atom({ plugin: 'auto-handoff', key: 'isArmed' } as const, true)
48const crossings = atom({ plugin: 'auto-handoff', key: 'crossings' } as const, 0)
49const last = atom({ plugin: 'auto-handoff', key: 'last' } as const, null)
50const isDismissed = atom({ plugin: 'auto-handoff', key: 'isDismissed' } as const, false)
51const isRetiring = atom({ plugin: 'auto-handoff', key: 'isRetiring' } as const, false)
52const isCovered = atom({ plugin: 'auto-handoff', key: 'isCovered' } as const, false)
53
54let isWriting = false
55// A retire in flight: a second press must not rename or archive twice.
56let isRetiringNow = false
57
58export const register: Register = on => {
59  on('session.start', async ($, e, next) => {
60    const result = await next(e)
61    await $.command.register({
62      name: 'auto-handoff',
63      description: 'Auto-handoff status, or now | threshold <n> | on | off',
64      argumentHint: '[now|threshold <n>|on|off]',
65    })
66    return result
67  })
68
69  on('turn.complete', async ($, e, next) => {
70    const result = await next(e)
71    if (e.agentId) {
72      return result
73    }
74    const { context } = await $.session.usage()
75    const tokens = context.tokens ?? 0
76    if (context.window !== WINDOW) {
77      return result
78    }
79    const { threshold, isEnabled } = await settings($)
80    if (tokens < threshold) {
81      await rearm($)
82      return result
83    }
84    if (!isEnabled) {
85      return result
86    }
87    const { value: armed = true } = await $.state.get({ plugin: 'auto-handoff', key: 'isArmed' } as const)
88    if (armed && !isWriting) {
89      await update($, isArmed, () => false)
90      // Outside this dispatch: the fork must not die with the turn's hook.
91      $.clock.after(1, () => {
92        void writeHandoff($, tokens)
93      })
94    }
95    return result
96  })
97
98  on('session.compact', async ($, e, next) => {
99    if (e.trigger === 'precompute' || e.agentId !== undefined) {
100      return next(e)
101    }
102    const { context } = await $.session.usage()
103    const { isEnabled } = await settings($)
104    if (isEnabled && !isWriting && context.tokens !== undefined && !(await read($, isCovered))) {
105      await writeHandoff($, context.tokens, `the conversation is about to be compacted (${e.trigger})`)
106    }
107    const result = await next(e)
108    if (!('skip' in result && result.skip)) {
109      await update($, isCovered, () => false)
110    }
111    return result
112  })
113
114  // A /clear ends this conversation (the process goes on): what was saved
115  // covers the old window, not the new one.
116  on('session.end', async ($, e, next) => {
117    if (e.reason === 'clear') {
118      await update($, isCovered, () => false)
119    }
120    return next(e)
121  })
122
123  on('command.run', { command: 'auto-handoff' }, async ($, e) => {
124    const [verb = '', value = ''] = e.args.trim().split(/\s+/)
125    if (verb === 'now') {
126      if (isWriting) {
127        return { text: 'An auto-handoff is already being written.' }
128      }
129      const { context } = await $.session.usage()
130      // No tokens means no response yet in this window (a fresh chat, or
131      // right after /clear or a compaction); the fork would only answer
132      // nothing-to-fork, so refuse instead of starting a write that fails.
133      if (context.tokens === undefined) {
134        return { text: 'Nothing to hand off yet: send a message first, then run /auto-handoff now.' }
135      }
136      const { tokens } = context
137      $.clock.after(1, () => {
138        void writeHandoff($, tokens)
139      })
140      return { text: 'Writing a handoff now. The band above the prompt shows when it is saved.' }
141    }
142    if (verb === 'on' || verb === 'off') {
143      const stored = asObject(await $.store.get(SETTINGS))
144      await $.store.set(SETTINGS, { ...stored, isEnabled: verb === 'on' })
145      return {
146        text:
147          verb === 'on'
148            ? `Auto-handoff is on: fires at ${short((await settings($)).threshold)} and before a compaction.`
149            : 'Auto-handoff is off: no handoff at the threshold or before a compaction. /auto-handoff now still writes one.',
150      }
151    }
152    if (verb === 'threshold') {
153      const n = toThreshold(value)
154      if (n === undefined) {
155        return { text: `Usage: /auto-handoff threshold <tokens>, from 1 up to but not including ${short(WINDOW)} (e.g. 250k or 250000).` }
156      }
157      const stored = asObject(await $.store.get(SETTINGS))
158      await $.store.set(SETTINGS, { ...stored, threshold: n })
159      // Armed again: the next turn at or past the new line writes, as on a
160      // fresh crossing.
161      await rearm($)
162      return { text: `Auto-handoff threshold set to ${short(n)} tokens.` }
163    }
164    if (verb !== '' && verb !== 'status') {
165      return { text: 'Usage: /auto-handoff [now|threshold <n>|on|off]' }
166    }
167    const { context } = await $.session.usage()
168    const { value: run } = await $.state.get({ plugin: 'auto-handoff', key: 'last' } as const)
169    const { threshold, isEnabled } = await settings($)
170    const tokens = context.tokens ?? 0
171    const lines = [
172      `Context: ${short(tokens)} of ${short(context.window)}.`,
173      !isEnabled
174        ? `Auto-handoff: off (threshold ${short(threshold)}); /auto-handoff on to resume.`
175        : context.window === WINDOW
176          ? `Auto-handoff: on, fires at ${short(threshold)}.`
177          : `Auto-handoff: on, but idle for this session: the threshold applies only to a ${short(WINDOW)} window.`,
178      run ? `Last: ${run.status}${run.path ? ` ${run.path}` : ''}${run.detail ? ` (${run.detail})` : ''}` : 'Last: none yet.',
179      !isEnabled
180        ? 'Before a compaction: nothing, auto-handoff is off.'
181        : (await read($, isCovered))
182          ? 'Before a compaction: no new handoff, the last one covers this window.'
183          : 'Before a compaction: writes a handoff first.',
184      'Tool calls: never blocked; the context compacts at the autoCompactWindow setting instead.',
185      'Commands: /auto-handoff now, threshold <n>, on, off.',
186    ]
187    return { text: lines.join('\n') }
188  })
189
190  on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
191    const run = await read($, last)
192    if (e.props.hasSurvey || run === null || (await read($, isDismissed))) {
193      return next(e)
194    }
195    const { Box, Text, Button } = $.ui.resolve(e)
196    const dismiss = (
197      <Button key="dismiss" label="Dismiss" plain onPress={() => update($, isDismissed, () => true)} />
198    )
199    if (run.status === 'writing') {
200      return (
201        <Box flexDirection="row" paddingX={1}>
202          <Text color="yellow">… Writing auto-handoff at {short(run.tokens)} tokens</Text>
203        </Box>
204      )
205    }
206    if (run.status === 'failed') {
207      return (
208        <Box flexDirection="row" paddingX={1}>
209          <Text color="red">✗ Auto-handoff failed: {run.detail}. Run /next yourself. </Text>
210          {dismiss}
211        </Box>
212      )
213    }
214    // Only the desktop app has a sidebar session to rename and archive.
215    const canRetire = e.surface === 'desktop'
216    const retiring = canRetire && (await read($, isRetiring))
217    return (
218      <Box flexDirection="column" paddingX={1}>
219        <Box flexDirection="row">
220          <Text color="green" bold>
221            ✓ Handoff saved at {short(run.tokens)} tokens{' '}
222          </Text>
223          <Text dimColor>{run.path} </Text>
224          {dismiss}
225        </Box>
226        <Box flexDirection="row">
227          {retiring ? (
228            <Text>To continue in a new session: retire this one, then /prime {run.project} there </Text>
229          ) : (
230            <Text>To continue fresh: /clear, then /prime {run.project} </Text>
231          )}
232          <Button
233            key="pickup"
234            label={retiring ? 'Retire session' : `Clear and /prime ${run.project}`}
235            variant="primary"
236            onPress={press => (retiring ? retire($, run.project, press.surface) : clearAndPrime($, run.project))}
237          />
238          {canRetire && (
239            <Button
240              key="retire"
241              label={`${retiring ? '[x]' : '[ ]'} Retire this session`}
242              plain
243              onPress={() => update($, isRetiring, v => !v)}
244            />
245          )}
246        </Box>
247      </Box>
248    )
249  })
250}
251
252// The fork's instructions: /next Steps 2-3, with the facts a tool-less
253// completion cannot look up handed to it.
254function forkPrompt(facts: {
255  why: string
256  now: string
257  cwd: string
258  project: string | null
259  projects: string
260  sessionId: string
261  model: string
262  tokens: number
263  key: string
264  git: string
265  previous: string
266}): string {
267  return [
268    `[auto-handoff] ${facts.why} (${facts.tokens} tokens).`,
269    'Write the /next handoff for this session now. You have no tools: do not try to run anything,',
270    'and do not do any of the remaining work. Use only this conversation and the facts below.',
271    '',
272    'FACTS',
273    `Date: ${facts.now}`,
274    `Working directory: ${facts.cwd}`,
275    facts.project
276      ? `Project: ${facts.project}`
277      : `Project: undetermined. Pick the existing project this session was about from this list (name, latest handoff), or coin a short kebab-case name:\n${facts.projects}`,
278    `Harness: Claude Code, model ${facts.model}. Session: ${facts.sessionId}`,
279    `git status --short / git diff --stat:\n${facts.git || '(not a git repository, or clean)'}`,
280    facts.previous
281      ? `Previous handoff for this project (do not repeat its settled decisions):\n${facts.previous}`
282      : 'Previous handoff: none.',
283    '',
284    'OUTPUT: exactly these two lines, then the handoff markdown, nothing else:',
285    'PROJECT: <project, kebab-case>',
286    'SLUG: <2-4 word kebab-case slug>',
287    '',
288    '# Handoff: <one-line outcome or active objective>',
289    'Date: <the date above>',
290    'Project: <project>',
291    'Working directory: <absolute path>',
292    'Harness: <harness and model>. Session: <id>',
293    `Attempt-Key: ${facts.key}`,
294    '',
295    '## Where we are',
296    '<What is done and verified, and the current state: uncommitted changes, running processes, partial work.',
297    'Name the checks that ran (command and result) and the checks that did NOT run; never call an unrun test passed.>',
298    '',
299    '## What we decided',
300    '- <Decision. Why: reason.> (one standalone bullet per decision made THIS session, or exactly "- None" with',
301    '  nothing after it; an offer still waiting for approval goes under Needs you, not here)',
302    '- Rejected: <a direction turned down that a later session might retry>. Why: <reason>.',
303    '',
304    '## Next step',
305    '<The single first concrete action for the next session, and why it is next.>',
306    '',
307    '## Remaining',
308    '### Ready',
309    '### Needs you',
310    '### Later',
311    '',
312    '## Claims to verify',
313    '- <A fact the next session depends on> : `<read-only command that checks it>` (3 to 6 items;',
314    '  plain read-only programs such as git, grep, jq, ls: /prime runs those, and asks before anything else)',
315    '',
316    '## References',
317    '<Absolute paths, commits, issue IDs, plans. Point to detail; do not copy it.>',
318    '',
319    'RULES: under 500 words. Mark anything unverified as unverified; distinguish what was checked,',
320    'what Matthew said, and what is assumed. Approvals do not carry over: list what was granted this',
321    'session and what still needs approval. No secrets or tokens (write [REDACTED]). No em dashes.',
322  ].join('\n')
323}
324
325async function exec($: EngineInterface, argv: string[], cwd?: string): Promise<{ ok: boolean; out: string }> {
326  try {
327    const r = await $.process.run(argv, cwd ? { cwd } : undefined)
328    return { ok: r.exitCode === 0, out: (r.exitCode === 0 ? r.stdout : r.stderr || r.stdout).trim() }
329  } catch (err) {
330    return { ok: false, out: String(err) }
331  }
332}
333
334async function setRun($: EngineInterface, value: HandoffRun): Promise<void> {
335  await update($, last, () => value)
336  await update($, isDismissed, () => false)
337}
338
339// Below the threshold again (a /clear, a compaction), or the threshold moved:
340// the next crossing may write again.
341async function rearm($: EngineInterface): Promise<void> {
342  await update($, isArmed, () => true)
343}
344
345// The on/off switch and the threshold, from the plugin's store; a missing or
346// malformed entry falls back to the defaults (on, 300k).
347async function settings($: EngineInterface): Promise<AutoHandoffSettings> {
348  const s = asObject(await $.store.get(SETTINGS))
349  return {
350    threshold: toThreshold(s.threshold) ?? DEFAULT_THRESHOLD,
351    isEnabled: typeof s.isEnabled === 'boolean' ? s.isEnabled : true,
352  }
353}
354
355// A token count, as typed (`250000`, `250k`, `0.5M`) or as stored; whole
356// tokens from 1 up to but not including the window. Anything else: undefined.
357function toThreshold(v: unknown): number | undefined {
358  let n: number
359  if (typeof v === 'number') {
360    n = v
361  } else {
362    const m = /^(\d+(?:\.\d+)?)([kKmM])?$/.exec(String(v ?? '').trim())
363    if (!m) return undefined
364    n = Number(m[1]) * (m[2] === undefined ? 1 : m[2].toLowerCase() === 'k' ? 1_000 : 1_000_000)
365  }
366  if (!Number.isFinite(n)) return undefined
367  n = Math.round(n)
368  return n >= 1 && n < WINDOW ? n : undefined
369}
370
371function asObject(v: unknown): Record<string, unknown> {
372  return v !== null && typeof v === 'object' && !Array.isArray(v) ? (v as Record<string, unknown>) : {}
373}
374
375// why: the fork's first line, what prompted this handoff.
376async function writeHandoff(
377  $: EngineInterface,
378  tokens: number,
379  why = 'This session has reached its handoff point in a 1,000,000-token window',
380): Promise<void> {
381  if (isWriting) {
382    return
383  }
384  isWriting = true
385  const fail = async (detail: string, project = '') => {
386    await setRun($, { status: 'failed', tokens, project, path: '', detail })
387    $.ui.toast(`Auto-handoff failed: ${detail}`, { timeoutMs: 10_000 })
388  }
389  try {
390    await setRun($, { status: 'writing', tokens, project: '', path: '', detail: '' })
391    const home = (await $.env.get('HOME')) ?? '/home/apexaipc'
392    const script = `${home}/.claude/skills/next/scripts/handoff.mjs`
393    const cwd = await $.session.cwd()
394    const sessionId = await $.session.id()
395    const crossing = await update($, crossings, n => n + 1)
396    const key = `auto-${sessionId.slice(0, 8)}-${crossing}`
397
398    // /next Step 1: the git root's name, or refused in the home folder.
399    const resolved = await exec($, ['node', script, 'project'], cwd)
400    const projects = resolved.ok ? '' : (await exec($, ['node', script, 'list'], cwd)).out
401
402    // /next Step 2: git state and the previous handoff.
403    const status = await exec($, ['git', '-C', cwd, 'status', '--short'])
404    const stat = await exec($, ['git', '-C', cwd, 'diff', '--stat'])
405    const git = status.ok ? `${status.out}\n${stat.out}`.trim() : ''
406    let previous = ''
407    if (resolved.ok) {
408      const latest = await exec($, ['node', script, 'latest', '--project', resolved.out], cwd)
409      if (latest.ok && latest.out) {
410        previous = ((await $.fs.read(latest.out).catch(() => '')) as string).slice(0, 4000)
411      }
412    }
413
414    // /next Step 3: the draft, from the session's own context.
415    const prompt = forkPrompt({
416      why,
417      now: (await exec($, ['date', '+%Y-%m-%d %H:%M %Z'])).out,
418      cwd,
419      project: resolved.ok ? resolved.out : null,
420      projects,
421      sessionId,
422      model: await $.session.model(),
423      tokens,
424      key,
425      git,
426      previous,
427    })
428    // The Transcript-Cutoff: the last transcript entry the fork replays, read just
429    // before it starts. The session keeps talking while the fork drafts (2026-10-07:
430    // a decision 16 s later never reached the handoff); /prime's tail check reads
431    // everything after this entry. Unreadable: "none", and /prime falls back to Date.
432    const cut = await exec($, ['node', script, 'cutoff', '--session', sessionId, '--cwd', cwd, '--fork'], cwd)
433    const cutoff = cut.ok && cut.out ? cut.out : 'none'
434    const reply = await $.model.fork({ prompt })
435    if (!reply.isAnswered) {
436      await fail(`the fork returned no draft (${reply.reason})`)
437      return
438    }
439    const parsed = parseReply(reply.text, key)
440    if ('error' in parsed) {
441      await fail(parsed.error)
442      return
443    }
444    const project = resolved.ok ? resolved.out : parsed.project
445
446    // /next Step 4: handoff.mjs owns LATEST, Supersedes and DECISIONS.md.
447    const draft = `${home}/.claude/auto-handoff/drafts/${key}.md`
448    await $.fs.write(draft, parsed.markdown)
449    const saved = await exec($, [
450      'node', script, 'save', '--slug', parsed.slug, '--file', draft, '--project', project, '--key', key,
451      '--cutoff', cutoff,
452    ], cwd)
453    if (!saved.ok) {
454      await fail(`handoff.mjs refused the draft: ${saved.out.slice(0, 160)}`, project)
455      return
456    }
457    await setRun($, { status: 'saved', tokens, project, path: saved.out, detail: '' })
458    await update($, isCovered, () => true)
459    $.ui.toast(`Handoff saved: ${saved.out}. Next: /clear, then /prime ${project}`, { timeoutMs: 15_000 })
460  } catch (err) {
461    await fail(String(err).slice(0, 160))
462  } finally {
463    isWriting = false
464  }
465}
466
467// The pickup line in one press. /clear ends the conversation but not this
468// module (no session.start follows it), so /prime still runs from here.
469// Dismissed first, so a second press cannot clear twice.
470async function clearAndPrime($: EngineInterface, project: string): Promise<void> {
471  await update($, isDismissed, () => true)
472  try {
473    await $.command.run({ command: 'clear' })
474  } catch (err) {
475    await update($, isDismissed, () => false)
476    $.ui.toast(`/clear did not run (${String(err).slice(0, 120)}). Run /clear, then /prime ${project}`, {
477      timeoutMs: 15_000,
478    })
479    return
480  }
481  try {
482    await $.command.run({ command: 'prime', args: project })
483  } catch (err) {
484    $.ui.toast(`Cleared, but /prime did not run (${String(err).slice(0, 120)}). Run /prime ${project}`, {
485      timeoutMs: 15_000,
486    })
487  }
488}
489
490// Retire: mark this session so it is not reopened, then archive it; the pickup
491// happens in a new session. Rename first, so a declined or failed archive
492// still leaves the session labelled. The archive ends the conversation, so
493// nothing after a successful one runs here.
494async function retire($: EngineInterface, project: string, surface: RenderSurface): Promise<void> {
495  if (isRetiringNow) {
496    return
497  }
498  isRetiringNow = true
499  try {
500    const pickup = `/prime ${project}`
501    const renamed = await sessions($, 'set_session_title', { session_id: 'self', title: `⛔ HANDED OFF: ${pickup}` })
502    const copied = await $.ui.copy({ text: pickup, surface }).catch(() => ({ isCopied: false }))
503    const archived = await sessions($, 'archive_session', {
504      session_id: 'self',
505      reason: `Auto-handoff saved; continue with ${pickup} in a new session`,
506    })
507    if (archived.ok) {
508      $.ui.toast(`Session retired. In a new session run ${pickup}${copied.isCopied ? ' (copied)' : ''}`, { timeoutMs: 15_000 })
509      return
510    }
511    $.ui.toast(
512      `${renamed.ok ? 'Renamed' : `Rename failed (${renamed.detail.slice(0, 80)})`}; archive did not happen ` +
513        `(${archived.detail.slice(0, 120)}). Archive it from the sidebar, then ${pickup} in a new session.`,
514      { timeoutMs: 20_000 },
515    )
516  } finally {
517    isRetiringNow = false
518  }
519}
520
521async function sessions(
522  $: EngineInterface,
523  tool: string,
524  args: Record<string, unknown>,
525): Promise<{ ok: boolean; detail: string }> {
526  try {
527    const r = await $.mcp.call(SESSIONS, tool, args)
528    const detail = r.content.map(b => b.text ?? '').join(' ').trim()
529    return { ok: !r.isError, detail: detail || (r.isError ? 'no reason given' : '') }
530  } catch (err) {
531    return { ok: false, detail: String(err) }
532  }
533}
534
535function parseReply(
536  text: string,
537  key: string,
538): { project: string; slug: string; markdown: string } | { error: string } {
539  const project = /^PROJECT:\s*([a-z0-9][a-z0-9-]*)\s*$/m.exec(text)?.[1]
540  const slug = /^SLUG:\s*([a-z0-9][a-z0-9-]*)\s*$/m.exec(text)?.[1]
541  const start = text.search(/^# Handoff:/m)
542  if (!project || !slug || start < 0) {
543    return { error: 'the draft is missing its PROJECT, SLUG or "# Handoff:" line' }
544  }
545  let markdown = text
546    .slice(start)
547    .replace(/\s*—\s*/g, ', ')
548    .replace(/–/g, '-')
549    .replace(/^```\w*\s*$/gm, '')
550    .trim()
551  if (!markdown.includes(`Attempt-Key: ${key}`)) {
552    markdown = markdown.replace(/^(# Handoff:.*)$/m, `$1\nAttempt-Key: ${key}`)
553  }
554  for (const heading of ['## Where we are', '## What we decided', '## Next step']) {
555    if (!markdown.includes(heading)) {
556      return { error: `the draft is missing "${heading}"` }
557    }
558  }
559  return { project, slug, markdown: `${markdown}\n` }
560}
561
562function short(n: number): string {
563  if (n >= 1_000_000) return `${(n / 1_000_000).toFixed(n % 1_000_000 === 0 ? 0 : 1)}M`
564  if (n >= 1_000) return `${Math.round(n / 1_000)}k`
565  return String(n)
566}
567
types/index.d.ts 40 lines
1// writing: the fork is drafting. saved: handoff.mjs stored it. failed: see detail.
2export type HandoffStatus = 'writing' | 'saved' | 'failed'
3
4export type HandoffRun = {
5  status: HandoffStatus
6  tokens: number
7  project: string
8  path: string
9  detail: string
10}
11
12// Kept across sessions under the plugin's store key "settings", written by
13// /auto-handoff on|off and threshold <n>; absent fields fall back to the
14// defaults (on, 300k tokens).
15export type AutoHandoffSettings = {
16  // Tokens, 1 up to but not including the 1M window.
17  threshold: number
18  isEnabled: boolean
19}
20
21declare module 'claude-code' {
22  interface PluginState {
23    'auto-handoff': {
24      // True until the context crosses the threshold; re-armed when it drops
25      // back below (after /clear or a compaction).
26      isArmed: boolean
27      // How many times this session has crossed; part of the idempotency key.
28      crossings: number
29      last: HandoffRun | null
30      isDismissed: boolean
31      // The band's "Retire this session" toggle: the pickup button renames and
32      // archives this session instead of clearing it (desktop only).
33      isRetiring: boolean
34      // A handoff saved since the last /clear or compaction: a compaction
35      // then goes ahead without writing another.
36      isCovered: boolean
37    }
38  }
39}
40