EXPERIMENTAL: run /handoff or /handoffplan, then replace the conversation with the handoff and continue in the same terminal. Needs compact-handoff-answer…

<img src="https://github.com/REMvisual/claude-handoff/releases/download/v1.6.0/banner.png" alt="claude-handoff" width="900"/>
Never lose context between AI coding sessions.
Two skills for Claude Code that capture decisions, failed approaches, measurements, and next steps — so your next session picks up exactly where you left off. Stop wasting 20-40% of each session rediscovering what was already tried.
Now a Claude Code mod: /compact-handoff writes the handoff, swaps the conversation for it, and keeps working in the same terminal. No new window, no paste. Jump to the mod ↓
git clone https://github.com/REMvisual/claude-handoff.git
cp -r claude-handoff/skills/handoff ~/.claude/skills/
cp -r claude-handoff/skills/handoffplan ~/.claude/skills/
Verify: type /handoff in Claude Code — it should appear in autocomplete.
/handoff # Capture session context — next session explores
/handoffplan # Capture context + write a plan — next session executes
No arguments needed. The skill mines your full conversation, gathers git state, validates the output, and gives you a ready-to-paste resume prompt:
Read `plans/handoffs/HANDOFF_fix-auth-bug_2026-03-19.md` (seq 2, PROJ-abc1)
and continue from "Where We're Going".
Paste that into a fresh Claude Code session. It picks up the chain and starts working.
Every handoff captures a structured snapshot of your session:
┌─────────────────────────────────────────────────────┐
│ HANDOFF_fix-auth-bug_2026-03-19.md │
├─────────────────────────────────────────────────────┤
│ The Goal — what we're solving and why │
│ Where We Are — 15-25 bullets of current state│
│ What We Tried — every approach, chronological │
│ Key Decisions — what was chosen AND rejected │
│ Evidence & Data — real numbers, not summaries │
│ User Feedback — preferences, corrections, tone│
│ Where We're Going — ordered next steps │
│ Quick Start — exact commands for next session│
└─────────────────────────────────────────────────────┘
"What We Tried" is the most valuable section. Failed approaches are the most expensive thing to rediscover. This section captures every attempt — what was tried, what happened, why it was kept or abandoned — so the next session never repeats work.
/handoff vs /handoffplanBoth capture your session. The difference is what the next session does:
/handoff | /handoffplan | |
|---|---|---|
| When to use | Pausing mid-work | Done with research, ready to build |
| What it writes | Handoff file | Handoff + phased plan + tracked tasks |
| Next session | Reads handoff, onboards, explores | Reads plan, claims Phase 1, starts coding |
| Paste prompt | "Continue from Where We're Going" | "Execute the plan starting at Phase 1" |
/handoffplan creates beads (or tasks in your tracker) with dependency chains between phases, anti-goals from failed approaches, rollback strategies, and success criteria tied to real numbers from the session.
Handoffs link across sessions automatically:
HANDOFF_fix-auth_2026-03-17.md (seq 1)
└─ HANDOFF_fix-auth_2026-03-18.md (seq 2)
└─ HANDOFF_fix-auth_2026-03-19.md (seq 3)
Your third session on a feature knows about the first two.
Claude already generates session summaries when context compresses. They look like handoffs — but they lack chain tracking, self-validation, evidence mining, and comprehension gates. In controlled A/B testing (same bug, same codebase, fresh sessions), the skill-based session:
Without this, Claude may generate freeform "handoffs" when sessions end — documents that look right but skip the process. Add to your CLAUDE.md:
When ending a session or saving progress:
- ALWAYS use the /handoff skill. NEVER generate handoff summaries without it.
The skills work standalone. They unlock more when paired with:
bd (beads) as default — swap in Linear, Jira CLI, or GitHub Issues.Runs the handoff, then replaces the conversation with it and keeps going in the same terminal, with no new session and no paste. It works like /compact, but the summary is your validated handoff.
claude plugin marketplace add REMvisual/claude-handoff
claude plugin install compact-handoff@claude-handoff
This also installs its small companion, compact-handoff-answer (see below). The skills above must be installed too, from v2.1.0 or later.
/compact-handoff [note] # /handoff, then continue from "Where We're Going"
/compact-handoffplan [note] # /handoffplan, then start executing Phase 1
/compact-handoff cancel # drop a run that's stuck
What happens:
compact-mode: it asks nothing, commits the session's work, and writes the handoff (and plan).While it runs, a bar above the prompt and the spinner line show how far along it is, for example Handoff 48% · Writing the handoff · 250 of 500 lines.
The mod also shows a one-time toast when context passes 70%, suggesting /compact-handoff.
The model can't start a handoff on its own while the mod is installed: its own call to /handoff or /handoffplan is refused, and it tells you to run /compact-handoff or /handoff instead. A handoff you ask for (typing /handoff, or "do a handoff" in your own words) runs as usual.
Why two plugins: Claude Code doesn't let a plugin answer a compaction it started itself. compact-handoff-answer is about 20 lines. It answers only compactions marked compact-handoff:v1 and leaves every other compaction alone.
Caveats:
PreCompact hooks (including the one below) don't run on these compactions. SessionStart hooks with the compact matcher still do.Safety net that runs before context compaction, capturing ~50 lines of git state and active tasks.
cp claude-handoff/hooks/precompact-handoff.sh ~/.claude/hooks/
chmod +x ~/.claude/hooks/precompact-handoff.sh
rm -rf ~/.claude/skills/handoff ~/.claude/skills/handoffplan
claude plugin uninstall compact-handoff@claude-handoff
claude plugin prune # removes compact-handoff-answer, installed as its dependency
MIT — If this saved you time, give it a star.
hooks/register.tsx 321 lines1// compact-handoff: /compact-handoff and /compact-handoffplan run the handoff skills in compact mode,
2// then replace the conversation with the handoff and continue in the same session.
3//
4// Order of events (each step is the one the engine allows; see the README):
5// command -> timer -> $.command.run(handoff|handoffplan, "compact-mode context=Nk ...") (no prompt from inside a command hook)
6// tool.call Write/Edit records the handoff/plan files the skill writes; Read/Write/Edit move the progress
7// turn.complete -> verify the files on disk and the handoff's line floor (under it: ask once for the rest)
8// -> queue /compact-handoff-go (no compaction while a turn runs)
9// compact-handoff-go -> timer -> $.session.compact(marker + stub) (answered by compact-handoff-answer;
10// a plugin cannot answer its own compaction)
11// -> $.prompt.submit(the skill's own paste prompt)
12import { atom, read, update } from 'claude-code'
13import type { EngineInterface, Register } from 'claude-code'
14
15import type { Mode, Progress, Run } from '../types'
16import {
17 advance,
18 buildInstructions,
19 classifyPath,
20 contextArg,
21 countLines,
22 extractPastePrompt,
23 fallbackPrompt,
24 isHandoffSkill,
25 lineFloor,
26 parseChain,
27 parseSentinel,
28 progressBar,
29 readingProgress,
30 resolvePath,
31 samePath,
32 shortPrompt,
33 SKILL_DENIED,
34 stubText,
35 writingProgress,
36} from './logic'
37
38const runAtom = atom({ plugin: 'compact-handoff', key: 'run' } as const, null as Run | null)
39const nudgedAtom = atom({ plugin: 'compact-handoff', key: 'nudged' } as const, false)
40// True for the rest of a turn in which the user asked for a handoff (in words or with /handoff, /handoffplan).
41const askedAtom = atom({ plugin: 'compact-handoff', key: 'askedForHandoff' } as const, false)
42const progressAtom = atom({ plugin: 'compact-handoff', key: 'progress' } as const, null as Progress | null)
43
44const GO = 'compact-handoff-go'
45const NUDGE_PERCENT = 70
46const MAX_COMPACT_TRIES = 40
47const DONE_SHOWN_MS = 8000
48
49function say($: EngineInterface, text: string) {
50 $.ui.toast(`Handoff: ${text}`)
51}
52
53async function setProgress($: EngineInterface, next: Progress) {
54 await update($, progressAtom, prev => advance(prev, next))
55}
56
57async function abort($: EngineInterface, why: string) {
58 await update($, runAtom, () => null)
59 await update($, progressAtom, () => null)
60 say($, `${why}. The conversation was not changed.`)
61}
62
63async function start($: EngineInterface, mode: Mode, args: string) {
64 args = (args ?? '').trim()
65 if (args === 'cancel') {
66 await update($, runAtom, () => null)
67 await update($, progressAtom, () => null)
68 return { text: 'Cancelled. The conversation was not changed.' }
69 }
70 const running = await read($, runAtom)
71 if (running) {
72 return { text: 'A handoff is already running. `/compact-handoff cancel` drops it.' }
73 }
74 const usage = await $.session.usage().catch(() => null)
75 const tokens = usage?.context.tokens
76 await update($, runAtom, () => ({
77 mode,
78 stage: 'handoff' as const,
79 startedAt: Date.now(),
80 files: [],
81 contextTokens: tokens,
82 window: usage?.context.window,
83 }))
84 await update($, progressAtom, () => ({ percent: 5, step: 'Starting' }))
85 const skill = mode === 'plan' ? 'handoffplan' : 'handoff'
86 // The measured size, so the skill picks its mining pass from a number rather than a guess.
87 const skillArgs = ['compact-mode', contextArg(tokens), args].filter(Boolean).join(' ')
88 // A prompt or command raised from inside this hook would wait on the turn the hook holds.
89 $.clock.after(100, () => runSkill($, skill, skillArgs))
90 const what = mode === 'plan' ? 'the handoff and the plan' : 'the handoff'
91 return { text: `Writing ${what}. When it is done, it replaces this conversation and work carries on from it.` }
92}
93
94async function runSkill($: EngineInterface, skill: string, args: string) {
95 try {
96 await $.command.run({ command: skill, args })
97 } catch (err) {
98 try {
99 await $.prompt.submit({ text: `Run the ${skill} skill with these arguments: ${args}` })
100 } catch (err2) {
101 await abort($, `/${skill} could not start (${String(err2 ?? err)})`)
102 }
103 }
104}
105
106/** After a Write/Edit of a handoff file in a run: record it and move the progress by its length. */
107async function trackFile($: EngineInterface, path: string) {
108 const kind = classifyPath(path)
109 const run = await read($, runAtom)
110 if (!kind || !run || run.stage !== 'handoff') return
111 if (!run.files.includes(path)) await update($, runAtom, r => (r ? { ...r, files: [...r.files, path] } : r))
112 if (kind === 'PLAN') return setProgress($, { percent: 72, step: 'Writing the plan' })
113 let content = ''
114 try {
115 content = await $.fs.read(resolvePath(await $.session.cwd(), path))
116 } catch {
117 return
118 }
119 const floor = lineFloor(run.contextTokens ?? 0, run.window ?? 0)
120 await setProgress($, writingProgress(countLines(content), floor, !!run.retried))
121}
122
123async function finishHandoff($: EngineInterface, reason: string, text: string) {
124 const run = await read($, runAtom)
125 if (!run || run.stage !== 'handoff') return
126 if (reason !== 'answer') return abort($, `the handoff stopped early (${reason})`)
127
128 const sentinel = parseSentinel(text)
129 if (sentinel && !sentinel.ok) return abort($, `the skill could not finish: ${sentinel.reason}`)
130
131 const reported = sentinel?.ok ? sentinel.files : []
132 const pick = (kind: 'HANDOFF' | 'PLAN') =>
133 reported.find(f => classifyPath(f) === kind) ?? [...run.files].reverse().find(f => classifyPath(f) === kind)
134 const handoff = pick('HANDOFF')
135 const plan = run.mode === 'plan' ? pick('PLAN') : undefined
136 if (!handoff) return abort($, 'no handoff file was written')
137 if (run.mode === 'plan' && !plan) return abort($, 'no plan file was written')
138 if (sentinel?.ok && run.files.length && !run.files.some(f => samePath(f, handoff))) {
139 say($, `the skill named ${handoff}, which this run did not write; checking it on disk anyway`)
140 }
141
142 const cwd = await $.session.cwd()
143 let chain: string | null = null
144 let lines = 0
145 for (const file of [handoff, plan].filter((f): f is string => !!f)) {
146 let content = ''
147 try {
148 content = await $.fs.read(resolvePath(cwd, file))
149 } catch {
150 return abort($, `${file} could not be read`)
151 }
152 if (content.trim().length < 200) return abort($, `${file} is empty`)
153 if (file === handoff) {
154 chain = parseChain(content)
155 lines = countLines(content)
156 }
157 }
158
159 // The conversation is deleted next, so a thin handoff is refused rather than compacted.
160 const tokens = run.contextTokens ?? 0
161 const floor = lineFloor(tokens, run.window ?? 0)
162 if (lines < floor.min) {
163 if (run.retried) {
164 return abort($, `the handoff is still too short (${lines} of ${floor.min} lines). Run /handoff to finish it by hand`)
165 }
166 const firstPrompt = extractPastePrompt(text)
167 await update($, runAtom, r => (r ? { ...r, retried: true, pastePrompt: firstPrompt ?? r.pastePrompt } : r))
168 await setProgress($, writingProgress(lines, floor, true))
169 say($, `the handoff has ${lines} of ${floor.min} lines, so it is not finished. Asking for the missing detail.`)
170 $.clock.after(100, () => {
171 $.prompt
172 .submit({ text: shortPrompt(handoff, lines, floor, tokens) })
173 .catch(err => abort($, `could not ask for the missing detail (${String(err)})`))
174 })
175 return
176 }
177
178 const pastePrompt = extractPastePrompt(text) ?? run.pastePrompt ?? fallbackPrompt(run.mode, handoff, plan, chain)
179 await update($, runAtom, r => (r ? { ...r, stage: 'compacting' as const, handoff, plan, pastePrompt } : r))
180 await setProgress($, { percent: 90, step: 'Replacing the conversation', detail: `${lines} lines` })
181 // Compaction is refused while a turn runs; a queued command runs once the session is idle.
182 $.command.run({ command: GO }).catch(err => abort($, `could not start the replacement (${String(err)})`))
183}
184
185function compactLoop($: EngineInterface, attempt: number) {
186 void (async () => {
187 const run = await read($, runAtom)
188 if (!run || run.stage !== 'compacting' || !run.handoff) return
189 const instructions = buildInstructions(stubText(run.mode, run.handoff, run.plan))
190 let result
191 try {
192 result = await $.session.compact({ instructions })
193 } catch (err) {
194 if (attempt >= MAX_COMPACT_TRIES) return abort($, `Claude Code kept refusing the replacement (${String(err)})`)
195 $.clock.after(500, () => compactLoop($, attempt + 1))
196 return
197 }
198 if (result.skip !== undefined) return abort($, `the replacement was skipped: ${result.skip}`)
199 if (result.usage) say($, 'compact-handoff-answer is not installed, so Claude Code summarized the conversation instead')
200 await update($, runAtom, () => null)
201 await update($, nudgedAtom, () => false)
202 await update($, progressAtom, () => ({ percent: 100, step: 'Done', detail: 'continuing from the handoff' }))
203 $.clock.after(DONE_SHOWN_MS, () => void update($, progressAtom, p => (p?.percent === 100 ? null : p)))
204 try {
205 await $.prompt.submit({ text: run.pastePrompt ?? fallbackPrompt(run.mode, run.handoff, run.plan), asUser: true })
206 } catch (err) {
207 say($, `the conversation was replaced, but the next prompt could not be sent (${String(err)}). Paste it from the handoff.`)
208 }
209 })()
210}
211
212async function nudge($: EngineInterface) {
213 if (await read($, nudgedAtom)) return
214 const usage = await $.session.usage()
215 if ((usage.context.percent ?? 0) < NUDGE_PERCENT) return
216 await update($, nudgedAtom, () => true)
217 say($, `context is at ${Math.round(usage.context.percent ?? 0)}%. A good point for /compact-handoff.`)
218}
219
220export const register: Register = on => {
221 on('session.start', async ($, e, next) => {
222 await $.command.register({
223 name: 'compact-handoff',
224 description: 'Write a handoff, then replace the conversation with it and carry on (experimental)',
225 })
226 await $.command.register({
227 name: 'compact-handoffplan',
228 description: 'Write a handoff and a plan, then replace the conversation and start Phase 1 (experimental)',
229 })
230 await $.command.register({ name: GO, description: 'Internal step of /compact-handoff' })
231 return next(e)
232 })
233
234 // The internal step stays runnable but out of the typeahead and /help.
235 on('command.describe', { command: GO }, async ($, e, next) => ({ ...(await next(e)), isHidden: true }))
236
237 on('command.run', { command: 'compact-handoff' }, async ($, e) => start($, 'resume', e.args))
238 on('command.run', { command: 'compact-handoffplan' }, async ($, e) => start($, 'plan', e.args))
239 on('command.run', { command: GO }, async $ => {
240 const run = await read($, runAtom)
241 if (!run || run.stage !== 'compacting') return { text: 'Nothing to replace.' }
242 // Compacting from inside this hook is refused too; a timer runs after it returns.
243 $.clock.after(300, () => compactLoop($, 0))
244 return { text: 'Replacing the conversation with the handoff…' }
245 }).catch(() => ({ text: 'The replacement step failed. The conversation was not changed.' }))
246
247 on('tool.call', { tool: 'Write' }, async ($, e, next) => {
248 const res = await next(e)
249 if (!e.agentId && !res.deny && !res.isError) await trackFile($, e.file_path)
250 return res
251 }).catch(($, e, next) => next(e))
252
253 on('tool.call', { tool: 'Edit' }, async ($, e, next) => {
254 const res = await next(e)
255 if (!e.agentId && !res.deny && !res.isError) await trackFile($, e.file_path)
256 return res
257 }).catch(($, e, next) => next(e))
258
259 // The skill's references mark its steps: mining, checking, closing.
260 on('tool.call', { tool: 'Read' }, async ($, e, next) => {
261 const res = await next(e)
262 const run = await read($, runAtom)
263 if (!e.agentId && run?.stage === 'handoff') {
264 const written = run.files.some(f => classifyPath(f) === 'HANDOFF')
265 const step = readingProgress(e.file_path, written)
266 await setProgress($, step ?? { percent: 10, step: 'Reading the session' })
267 }
268 return res
269 }).catch(($, e, next) => next(e))
270
271 // The model may not start a handoff on its own: the user picks /compact-handoff or /handoff.
272 on('tool.call', { tool: 'Skill' }, async ($, e, next) => {
273 if (!isHandoffSkill(e.skill) || (await read($, runAtom)) || (await read($, askedAtom))) return next(e)
274 return { deny: SKILL_DENIED }
275 }).catch(($, e, next) => next(e))
276
277 on('prompt.submit', async ($, e, next) => {
278 if (/hand-?off/i.test(e.text ?? '')) await update($, askedAtom, () => true)
279 return next(e)
280 }).catch(($, e, next) => next(e))
281
282 // /handoff, /handoffplan typed by the user; /handoffplan then runs /handoff through the Skill tool.
283 on('skill.prompt', async ($, e, next) => {
284 if (isHandoffSkill(e.skill)) await update($, askedAtom, () => true)
285 return next(e)
286 }).catch(($, e, next) => next(e))
287
288 // The spinner line names the step while the handoff turn runs.
289 on('ui.render', { component: 'Spinner' }, async ($, e, next) => {
290 const p = await read($, progressAtom)
291 if (!p || p.percent >= 100) return next(e)
292 return next({ ...e, props: { ...e.props, message: `Handoff ${p.percent}% · ${p.step}` } })
293 }).catch(($, e, next) => next(e))
294
295 // A bar above the prompt for the whole run, until a few seconds after it is done.
296 on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
297 const p = await read($, progressAtom)
298 if (!p || e.props.hasSurvey) return next(e)
299 const { Box, Text } = $.ui.resolve(e)
300 return (
301 <Box>
302 <Text bold>Handoff </Text>
303 <Text color={p.percent >= 100 ? 'green' : undefined}>{progressBar(p.percent)}</Text>
304 <Text bold> {p.percent}% </Text>
305 <Text>{p.step}</Text>
306 {p.detail ? <Text dimColor> · {p.detail}</Text> : null}
307 </Box>
308 )
309 }).catch(($, e, next) => next(e))
310
311 on('turn.complete', async ($, e, next) => {
312 const res = await next(e)
313 if (e.agentId) return res
314 await update($, askedAtom, () => false)
315 const run = await read($, runAtom)
316 if (run) await finishHandoff($, e.reason, res.text)
317 else await nudge($)
318 return res
319 }).catch(($, e, next) => next(e))
320}
321hooks/logic.ts 184 lines1// Pure helpers for the compact-handoff mod: no `$`, so the tests can call them directly.
2import type { Mode, Progress } from '../types'
3
4/**
5 * First line of the compaction instructions. compact-handoff-answer answers only a
6 * compaction whose instructions start with it, and returns the text after it.
7 */
8export const MARKER = 'compact-handoff:v1'
9
10const HANDOFF_FILE = /(?:^|[\\/])(?:plans|\.claude)[\\/]handoffs[\\/](HANDOFF|PLAN)_[^\\/]*\.md$/
11
12/** `HANDOFF` or `PLAN` for a file the handoff skills write, else null. */
13export function classifyPath(path: string): 'HANDOFF' | 'PLAN' | null {
14 const m = HANDOFF_FILE.exec(path)
15 if (!m) return null
16 return m[1] === 'PLAN' ? 'PLAN' : 'HANDOFF'
17}
18
19export type Sentinel = { ok: true; files: string[] } | { ok: false; reason: string }
20
21/** Reads the skill's last `COMPACT-HANDOFF-READY:` / `COMPACT-HANDOFF-FAILED:` line; null when there is none. */
22export function parseSentinel(text: string): Sentinel | null {
23 const lines = text.split(/\r?\n/).map(l => l.trim().replace(/^`+|`+$/g, '').trim())
24 for (let i = lines.length - 1; i >= 0; i--) {
25 const line = lines[i] ?? ''
26 const ready = /^COMPACT-HANDOFF-READY:\s*(.+)$/.exec(line)
27 if (ready) {
28 const files = (ready[1] ?? '')
29 .split('|')
30 .map(f => f.trim().replace(/^`+|`+$/g, ''))
31 .filter(Boolean)
32 return { ok: true, files }
33 }
34 const failed = /^COMPACT-HANDOFF-FAILED:\s*(.*)$/.exec(line)
35 if (failed) return { ok: false, reason: failed[1] || 'no reason given' }
36 }
37 return null
38}
39
40/** The prompt between the dashes after `PASTE THIS INTO YOUR NEXT SESSION:`, or null. */
41export function extractPastePrompt(text: string): string | null {
42 const lines = text.split(/\r?\n/)
43 const head = lines.findIndex(l => l.includes('PASTE THIS INTO YOUR NEXT SESSION:'))
44 if (head < 0) return null
45 const isRule = (l: string) => /^\s*-{10,}\s*$/.test(l)
46 let start = head + 1
47 if (isRule(lines[start] ?? '')) start++
48 const end = lines.findIndex((l, i) => i >= start && isRule(l))
49 if (end < 0) return null
50 const body = lines
51 .slice(start, end)
52 .map(l => l.replace(/^ {3}/, ''))
53 .join('\n')
54 .trim()
55 return body || null
56}
57
58/** The handoff's chain as "seq N, tag", from its `**Chain:** \`tag\` seq \`N\`` header line. */
59export function parseChain(content: string): string | null {
60 const m = /^\*\*Chain:\*\*\s*`([^`]+)`\s*seq\s*`?(\d+)`?/m.exec(content)
61 return m ? `seq ${m[2]}, ${m[1]}` : null
62}
63
64export type Floor = { pass: 'Quick' | 'Deep' | 'Chunked'; min: number }
65
66/**
67 * The handoff skill's line minimum for the mining pass the context size calls for.
68 * Quick gets the light-session floor, so a short session is never refused.
69 */
70export function lineFloor(tokens: number, window: number): Floor {
71 if (tokens >= 500_000) return { pass: 'Chunked', min: 500 }
72 if (tokens >= 100_000) return { pass: 'Deep', min: 300 }
73 return { pass: 'Quick', min: window >= 1_000_000 ? 120 : 80 }
74}
75
76export function countLines(content: string): number {
77 const body = content.replace(/\s+$/, '')
78 return body ? body.split(/\r?\n/).length : 0
79}
80
81/** Sent once when the handoff is under its floor: finish mining, then report again. */
82export function shortPrompt(handoff: string, lines: number, floor: Floor, tokens: number): string {
83 return (
84 `The handoff is too short to replace this conversation: ${lines} lines, and a ${kTokens(tokens)} session ` +
85 `needs at least ${floor.min} (${floor.pass} pass).\n\n` +
86 `Go back through the early, middle and late parts of the session and add what \`${handoff}\` is missing: ` +
87 'decisions, numbers, failed approaches, file paths, user feedback. Read `references/mining-deep-chunked.md` first ' +
88 'if you have not. Add real detail, not padding. Then print the Length check again and end with the ' +
89 'COMPACT-HANDOFF-READY line.'
90 )
91}
92
93export function kTokens(tokens: number): string {
94 return `${Math.round(tokens / 1000)}k-token`
95}
96
97/** The context size the skill picks its mining pass from, as a `compact-mode` argument. */
98export function contextArg(tokens: number | undefined): string {
99 return tokens ? `context=${Math.round(tokens / 1000)}k` : ''
100}
101
102export function progressBar(percent: number, width = 20): string {
103 const filled = Math.round((Math.max(0, Math.min(100, percent)) / 100) * width)
104 return '█'.repeat(filled) + '░'.repeat(width - filled)
105}
106
107/** 25-70% while the first pass grows toward its floor; 80-88% while missing detail is added. */
108export function writingProgress(lines: number, floor: Floor, addingDetail: boolean): Progress {
109 const share = Math.min(lines / floor.min, 1)
110 const detail = `${lines} of ${floor.min} lines`
111 return addingDetail
112 ? { percent: 80 + Math.round(8 * share), step: 'Adding missing detail', detail }
113 : { percent: 25 + Math.round(45 * share), step: 'Writing the handoff', detail }
114}
115
116/** The step a skill reference marks. Checking and closing count only once the handoff exists. */
117export function readingProgress(path: string, written: boolean): Progress | null {
118 const name = (path.replace(/\\/g, '/').split('/').pop() ?? '').toLowerCase()
119 if (name === 'mining-deep-chunked.md' || name === 'output-template.md') return { percent: 20, step: 'Mining the session' }
120 if (!written) return null
121 if (name === 'validation.md') return { percent: 75, step: 'Checking the handoff' }
122 if (name === 'close-session.md') return { percent: 80, step: 'Closing the session' }
123 return null
124}
125
126/** Progress only moves forward; a lower reading keeps the step and takes the new detail. */
127export function advance(prev: Progress | null, next: Progress): Progress {
128 if (!prev || next.percent >= prev.percent) return next
129 return next.detail ? { ...prev, detail: next.detail } : prev
130}
131
132/** The model's own call to a handoff skill, by the Skill tool's `skill` value. */
133export function isHandoffSkill(skill: string): boolean {
134 return /^\/?(?:[\w-]+:)?(handoff|handoffplan)$/.test(skill.trim())
135}
136
137export const SKILL_DENIED =
138 'A handoff starts when the user asks for one, so this call was refused. Do not write a handoff file yourself. ' +
139 'Tell the user the work is at a good point for a handoff, and that they can type /compact-handoff ' +
140 '(writes the handoff, then replaces the conversation with it) or /handoff (writes it and keeps the conversation).'
141
142/** Used only when the skill's own paste prompt could not be extracted. */
143export function fallbackPrompt(mode: Mode, handoff: string, plan?: string, chain?: string | null): string {
144 const tag = chain ? ` (${chain})` : ''
145 if (mode === 'plan' && plan) {
146 return `Read \`${plan}\` and \`${handoff}\`${tag}. Execute the plan starting at Phase 1: claim its bead, read the Quick Start files, then start coding Phase 1's first concrete action.`
147 }
148 return (
149 `Read \`${handoff}\`${tag} and continue from "Where We're Going". Check \`bd list --status=in_progress\` for active work.\n\n` +
150 'Before starting work, summarize the goal, current state and what was tried; name the bead(s) you will claim; ' +
151 'say what you will verify first; then wait for my go-ahead before executing.'
152 )
153}
154
155/** The one message the conversation is replaced with. */
156export function stubText(mode: Mode, handoff: string, plan?: string): string {
157 const files = plan ? `Handoff: \`${handoff}\`. Plan: \`${plan}\`.` : `Handoff: \`${handoff}\`.`
158 return (
159 `The conversation was replaced by compact-handoff (${mode} mode) after a full handoff. ${files} ` +
160 'Everything earlier in this session is in those files; the next message says what to do.'
161 )
162}
163
164/**
165 * The compaction's instructions: the marker line, then the stub. Without the answering
166 * plugin the engine's summarizer reads them instead, so they must make sense to it too.
167 */
168export function buildInstructions(stub: string): string {
169 return `${MARKER}\n${stub}`
170}
171
172/** Makes a skill-reported relative path absolute against the session's directory. */
173export function resolvePath(cwd: string, path: string): string {
174 if (/^([a-zA-Z]:[\\/]|[\\/])/.test(path)) return path
175 const sep = cwd.includes('\\') ? '\\' : '/'
176 return `${cwd.replace(/[\\/]+$/, '')}${sep}${path.replace(/^\.[\\/]/, '')}`
177}
178
179/** Same file, whatever the separators or case of a Windows path. */
180export function samePath(a: string, b: string): boolean {
181 const norm = (p: string) => p.replace(/\\/g, '/').toLowerCase()
182 return norm(a) === norm(b) || norm(a).endsWith('/' + norm(b)) || norm(b).endsWith('/' + norm(a))
183}
184types/index.d.ts 30 lines1export type Mode = 'resume' | 'plan'
2
3/** Where a run is, for the spinner line and the band above the prompt. */
4export type Progress = { percent: number; step: string; detail?: string }
5
6/** One /compact-handoff run, from the command until the continue-prompt is sent. */
7export type Run = {
8 mode: Mode
9 /** `handoff`: the skill's turn is running. `compacting`: waiting for the compaction. */
10 stage: 'handoff' | 'compacting'
11 startedAt: number
12 /** The context size when the run started: picks the handoff's line floor. */
13 contextTokens?: number
14 window?: number
15 /** Set once the mod has asked for the rest of a handoff that came in under its floor. */
16 retried?: boolean
17 /** Handoff/plan files written during the run, as the tools reported them. */
18 files: string[]
19 /** Set once the turn ended with verified files. */
20 handoff?: string
21 plan?: string
22 pastePrompt?: string
23}
24
25declare module 'claude-code' {
26 interface PluginState {
27 'compact-handoff': { run: Run | null; nudged: boolean; askedForHandoff: boolean; progress: Progress | null }
28 }
29}
30