When Claude ends a reply with a question, explains the choice in a side pane and lets you explore any option, or your own, in a real forked session

A Claude Code mod that turns the question at the end of Claude's reply into a side pane you can explore: every option with what it leads to, and a real forked session for any answer you want to try before you commit.

After every turn:
YES if you have to decide something before work can go on, NO for "anything else?" and other pleasantries.$.model.fork replays the session's own transcript (served from the prompt cache), so it knows everything Claude knew. It has no tools and replies with JSON: the question, the context you need, each option with what it leads to and its pros and cons, and a recommendation.You answer Claude in the prompt as usual. Nothing in the pane goes back to Claude.
Does nothing in -p / SDK sessions, unless DECISION_TREE_WAIT=1 is set (see below).

Explore forks the real session at the message that asked the question:
claude -p --resume <session> --resume-session-at <that message> --fork-session
The fork is told you picked that option and carries on with read-only tools (Read, Grep, Glob). In 12 to 20 seconds the pane shows what it would do, its steps, and the next question it would ask you. Explore again from there to go deeper: each level forks the branch above it.
/explain other <answer>, adds it as an option and explores it like the rest.claude --resume <branch> --fork-session, in a new Herdr pane when you're inside Herdr, or copied to your clipboard otherwise.Every branch is its own session file, so the main conversation never sees any of it.
| Command | What it does |
|---|---|
/explain | Open the pane for the latest question |
/explain b | Explore option B (A to H) |
/explain other <answer> | Explore your own answer |
/explain map | Show the map |
/explain back, /explain top | Move up the tree |
/explain continue | Open the current branch as a live session |
/plugin install decision-tree --marketplace ray-amjad/claude-code-mods
Answer y to add the marketplace, then pick a scope.
| Option | Default | What it does |
|---|---|---|
gateModel | haiku | The model that answers YES or NO |
/explain and the pane opens above the prompt.--resume-session-at is an undocumented Claude Code flag (tested on 2.1.296). If the mod can't find the message to cut at, it forks from the latest point and says so.claude -p run with a turn's cost, and its session file stays in the project's history.claude --plugin-dir ./decision-tree
claude plugin validate .
In claude -p, set DECISION_TREE_WAIT=1 so the run waits for the fork before it exits.
hooks/register.jsx 434 lines1// decision-tree: when Claude's reply ends by asking you something, a fork of the
2// conversation explains the choice in a side pane. Then you can explore
3// any option: the mod forks the real session at that question, plays the answer out in
4// the fork, and shows the next question. Each branch is its own session, so nothing you
5// explore reaches the main conversation.
6
7const PANE = 'question'
8
9// The answer every explanation is asked for, so the pane can draw it
10const SHAPE = '{"question": "the question in one plain line", ' +
11 '"context": "one or two sentences: what I need to know to decide", ' +
12 '"options": [{"label": "2 to 5 words", "detail": "what it means", ' +
13 '"leadsTo": "what happens next if I pick it", "pros": ["short"], "cons": ["short"]}], ' +
14 '"recommendation": {"label": "the label of one option", "why": "one sentence"}}'
15
16// The tree for the latest question. A node is { sid, msgId, answer, status, data, children }:
17// sid and msgId say which session, cut at which message, a branch below it forks from
18let root = null
19// Option indexes from the root to the node the pane shows
20let path = []
21// What the pane shows: 'node' (one question) or 'map' (the whole tree)
22let view = 'node'
23// Where the session transcripts live, from the Stop hook
24let transcriptPath = ''
25// Set at each session.start; true for -p / SDK sessions, where the pane is never drawn
26let headless = false
27
28// Cheap check, no model: does the end of the reply ask something?
29// A question mark in the last paragraph, or a numbered / lettered / bulleted list of options.
30function looksLikeQuestion(answer) {
31 const tail = answer.trim().slice(-1500)
32 const paragraphs = tail.split(/\n\s*\n/)
33 const last = paragraphs[paragraphs.length - 1] || ''
34 if (/\?\s*(\*\*|_|`)?\s*$/.test(last) || /\?\s*$/m.test(last)) return true
35 const options = tail.match(/^\s*(\d+[.)]|[A-D][.):]|[-*]\s+\*\*Option|Option [A-D1-9])/gm) || []
36 return options.length >= 2 && /\b(which|prefer|choose|pick|want|should I|let me know)\b/i.test(tail)
37}
38
39// The gate: a small model confirms the question needs a real decision from the user
40async function needsDecision($, answer, model) {
41 const r = await $.model.complete({
42 model,
43 system: 'You read the end of an AI coding assistant reply. Answer YES if it ends by asking ' +
44 'the user to decide, choose, or supply something before work can go on. Answer NO for ' +
45 'rhetorical questions, pleasantries such as "anything else?", or a reply that just reports. ' +
46 'Reply with YES or NO only.',
47 prompt: answer.trim().slice(-2000),
48 maxTokens: 5,
49 timeoutMs: 20000,
50 })
51 return r.isAnswered && /^\s*yes/i.test(r.text)
52}
53
54// The first explanation: a model fork replays the conversation and returns the choice as JSON
55async function explainRoot($, answer) {
56 const node = { sid: await $.session.id(), answer, status: 'thinking', children: [] }
57 root = node
58 path = []
59 view = 'node'
60 await openPane($, false)
61 $.ui.invalidate('ui.render')
62
63 const r = await $.model.fork({
64 prompt: 'Your last reply ended by asking me a question. Do not answer it and do not use tools. ' +
65 'Help me answer it. Reply with JSON only, no code fence, in this shape: ' + SHAPE + '. ' +
66 'Use the options you offered; if you offered none, give the 2 to 4 answers I would most ' +
67 'likely pick. At most 2 pros and 2 cons each. No em or en dashes.',
68 })
69 settle(node, r.isAnswered ? r.text : '', r.isAnswered ? 'the fork did not return JSON' : r.reason)
70 if (root !== node) return
71 $.ui.invalidate('ui.render')
72}
73
74// Explore option i of the node the pane shows: fork the real session at that node's
75// question, tell the fork we picked i, and let it play that out with read-only tools.
76// With own, the answer is yours: it joins the question's options first, then is explored
77async function explore($, i, own) {
78 const tree = root
79 const node = nodeAt(path)
80 if (own && node && node.data && node.data.options) {
81 const options = node.data.options
82 i = options.findIndex(o => o.label.toLowerCase() === own.toLowerCase())
83 if (i < 0) i = options.push({ label: own, mine: true }) - 1
84 }
85 const option = node && node.data && node.data.options && node.data.options[i]
86 if (!option) return $.ui.toast('decision-tree: no option ' + String.fromCharCode(65 + i) + ' here')
87 path = [...path, i]
88 view = 'node'
89 $.ui.invalidate('ui.render')
90 if (node.children[i]) return
91
92 const child = { label: option.label, status: 'exploring', children: [], startedAt: Date.now() }
93 node.children[i] = child
94
95 // The message to cut the parent session at: the reply that asked this question
96 if (!node.msgId) node.msgId = await lastAssistantId($, node.sid, node.answer)
97 if (!node.msgId) $.ui.log('decision-tree: message id not found, forking from the latest point')
98 const args = ['claude', '-p', whatIf(option),
99 '--resume', node.sid, '--fork-session', '--output-format', 'json',
100 '--permission-mode', 'default', '--allowedTools=Read,Grep,Glob',
101 '--disallowedTools=Bash,Edit,Write,NotebookEdit']
102 if (node.msgId) args.push('--resume-session-at', node.msgId)
103
104 let out = null
105 try {
106 const run = await $.process.run(args, {
107 cwd: await $.session.cwd(),
108 env: { DECISION_TREE_CHILD: '1' },
109 timeoutMs: 300000,
110 })
111 out = resultOf(run.stdout)
112 if (!out) child.reason = (run.stderr || run.stdout || 'no output').slice(0, 300)
113 } catch (err) {
114 child.reason = String(err)
115 }
116 if (root !== tree) return
117 if (out) {
118 child.sid = out.session_id
119 child.answer = out.result
120 settle(child, out.result || '', 'the branch did not return JSON')
121 } else {
122 child.status = 'failed'
123 }
124 child.ms = Date.now() - child.startedAt
125 $.ui.invalidate('ui.render')
126}
127
128// The prompt a branch gets: our answer, then the same JSON as the root plus what happened
129function whatIf(option) {
130 return 'WHAT-IF BRANCH: this is a forked copy of the session for exploring one answer. ' +
131 'The real session is not affected. My answer to your question: "' + option.label + '"' +
132 (option.detail ? ' (' + option.detail + ')' : '') + '. Carry on as if I picked it, but change no files and run no ' +
133 'commands; you may Read, Grep and Glob to make the plan concrete. Then reply with JSON only, ' +
134 'no code fence, in this shape, plus two more fields: "outcome" (two to four sentences: what ' +
135 'you would do and how things stand after) and "steps" (up to 4 short concrete steps). ' +
136 'The question and options are the NEXT decision you would need from me after this; if there ' +
137 'is none, give an empty question and options []. Shape: ' + SHAPE + '. No em or en dashes.'
138}
139
140// Turn a reply into the node's data, or mark the node failed
141function settle(node, text, reason) {
142 const data = parseJson(text)
143 if (data && Array.isArray(data.options)) {
144 node.data = data
145 node.status = 'ready'
146 } else {
147 node.status = 'failed'
148 node.reason = node.reason || reason
149 }
150}
151
152// claude -p --output-format json prints the result object, or the whole event list
153function resultOf(stdout) {
154 try {
155 const out = JSON.parse(stdout)
156 const res = Array.isArray(out) ? out.find(x => x.type === 'result') : out
157 return res && res.session_id ? res : null
158 } catch {
159 return null
160 }
161}
162
163// Find the id of the assistant message that asked the question, in the session's transcript
164async function lastAssistantId($, sid, answer) {
165 // The Stop hook's transcript path names the folder; without it, rebuild it from the cwd
166 // (a Windows path uses \, and a native Windows terminal sets USERPROFILE, not HOME)
167 const home = (await $.env.get('HOME')) || (await $.env.get('USERPROFILE'))
168 const folder = transcriptPath ? transcriptPath.replace(/[\\/][^\\/]+$/, '') :
169 home + '/.claude/projects/' + (await $.session.cwd()).replace(/[^a-zA-Z0-9]/g, '-')
170 const file = folder + '/' + sid + '.jsonl'
171 if (!(await $.fs.exists(file))) return undefined
172 // A transcript past $.fs.read's 4 MiB cannot be searched: fork from the latest point
173 const lines = (await $.fs.read(file).catch(() => '')).split('\n')
174 const want = (answer || '').trim().slice(-60)
175 for (let n = lines.length - 1; n >= 0; n--) {
176 let row
177 try { row = JSON.parse(lines[n]) } catch { continue }
178 if (row.type !== 'assistant' || row.isSidechain) continue
179 const text = (row.message.content || []).filter(b => b.type === 'text').map(b => b.text).join('')
180 if (text && text.trim().endsWith(want)) return row.uuid
181 }
182 return undefined
183}
184
185// The map: one row per question and per option, drawn as a tree with the path to each row
186// Question: Which storage?
187// ├ A JSON file on disk ▸
188// │ └ Q: How should I build it?
189// └ B SQLite ★
190function mapRows(node, p, prefix, rows) {
191 const data = node.data
192 if (!data || !data.question) return rows
193 rows.push({ text: prefix + 'Q: ' + data.question, path: p, kind: 'question' })
194 const pick = (data.recommendation && data.recommendation.label) || ''
195 data.options.forEach((o, i) => {
196 const last = i === data.options.length - 1
197 const child = node.children[i]
198 const mark = !child ? '' : child.status === 'exploring' ? ' ...' : child.status === 'failed' ? ' ✗' : ' ▸'
199 rows.push({
200 text: prefix + (last ? '└ ' : '├ ') + String.fromCharCode(65 + i) + ' ' + o.label + (o.label === pick ? ' ★' : '') + (o.mine ? ' ✎' : '') + mark,
201 path: child ? [...p, i] : null,
202 kind: child ? 'explored' : 'option',
203 })
204 if (child && child.status === 'ready') mapRows(child, [...p, i], prefix + (last ? ' ' : '│ '), rows)
205 })
206 return rows
207}
208
209function nodeAt(p) {
210 let node = root
211 for (const i of p) node = node && node.children[i]
212 return node
213}
214
215// Continue a branch for real: a new Claude session forked from it, in a Herdr pane if there is one
216async function continueBranch($, node) {
217 if (!node || !node.sid) return
218 const command = 'claude --resume ' + node.sid + ' --fork-session'
219 if ((await $.env.get('HERDR_ENV')) === '1') {
220 try {
221 const split = await $.process.run(['herdr', 'pane', 'split', '--current', '--direction', 'down',
222 '--cwd', await $.session.cwd(), '--no-focus'])
223 const id = JSON.parse(split.stdout).result.pane.pane_id
224 await $.process.run(['herdr', 'pane', 'run', id, command])
225 return $.ui.toast('decision-tree: branch opened in pane ' + id)
226 } catch (err) {
227 $.ui.log('could not open a Herdr pane: ' + err)
228 }
229 }
230 await $.ui.copy({ text: command })
231 $.ui.toast('decision-tree: copied ' + command)
232}
233
234// Open the side pane. Unasked, Claude Code only places it on a wide terminal.
235async function openPane($, asked) {
236 // A -p run with DECISION_TREE_WAIT still builds the tree, but has no pane to open
237 if (headless) return
238 // focus takes only true, so leave it out for an unasked open
239 const pane = { id: PANE, title: 'Decision tree' }
240 // Asked from /explain: take the keys, Escape closes it, and ask for room above the prompt
241 const opened = await $.ui.open(asked ? { ...pane, focus: true, closeOnEscape: true, rows: 30 } : pane)
242 if (!opened.isPlaced) $.ui.toast('decision-tree: run /explain to see the pane')
243}
244
245// The fork may wrap its JSON in prose or a fence; take the outermost braces
246function parseJson(text) {
247 const start = text.indexOf('{')
248 const end = text.lastIndexOf('}')
249 if (start < 0 || end <= start) return null
250 try {
251 return JSON.parse(text.slice(start, end + 1))
252 } catch {
253 return null
254 }
255}
256
257export function register(on, options) {
258 on('session.start', async ($, e, next) => {
259 headless = e.isInteractive === false
260 if (headless) return next(e)
261 await $.command.register({
262 name: 'explain',
263 description: 'Show the decision tree; A to H explores an option, other <answer> explores your own',
264 argumentHint: '[A-H | other <answer> | map | back | top | continue]',
265 immediate: true,
266 })
267 return next(e)
268 })
269
270 // Remember where transcripts are written, to find message ids to fork at
271 on('classic.Stop', async ($, e, next) => {
272 if (e.transcript_path) transcriptPath = e.transcript_path
273 return next(e)
274 }).catch(($, e, next) => (next.called ? undefined : next(e)))
275
276 // After each of Claude's replies: regex check, then the gate, then the fork
277 on('turn.complete', async ($, e, next) => {
278 const result = await next(e)
279 // Headless: nothing would be shown, so skip the gate and the fork, unless DECISION_TREE_WAIT asks for it
280 const wait = (await $.env.get('DECISION_TREE_WAIT')) === '1'
281 if (headless && !wait) return result
282 // A branch's own claude -p run never explains its own replies
283 if ((await $.env.get('DECISION_TREE_CHILD')) === '1') return result
284 if (e.agentId || e.reason !== 'answer' || !looksLikeQuestion(e.answer)) return result
285 if (!(await needsDecision($, e.answer, options.gateModel || 'haiku'))) return result
286 // Run the fork without holding up the prompt; in a -p run, wait so the process lives on
287 const work = explainRoot($, e.answer).catch(err => $.ui.log('decision-tree failed: ' + err))
288 if (wait) await work
289 return result
290 })
291
292 // /explain opens the pane; /explain B explores option B; back, top and continue move around
293 on('command.run', { command: 'explain' }, async ($, e) => {
294 if (!root) return { text: 'No question to explain yet.' }
295 const raw = (e.args || '').trim()
296 const arg = raw.toLowerCase()
297 view = arg === 'map' ? 'map' : 'node'
298 if (arg === 'back') path = path.slice(0, -1)
299 else if (arg === 'top') path = []
300 else if (arg === 'continue') await continueBranch($, nodeAt(path))
301 else if (/^[a-h]$/.test(arg) || /^other\s+\S/.test(arg)) {
302 const own = /^other\s/.test(arg) ? raw.replace(/^other\s+/i, '') : undefined
303 const work = explore($, own ? -1 : arg.charCodeAt(0) - 97, own).catch(err => $.ui.log('explore failed: ' + err))
304 if ((await $.env.get('DECISION_TREE_WAIT')) === '1') await work
305 }
306 $.ui.invalidate('ui.render')
307 await openPane($, true)
308 return {}
309 })
310
311 // The pane: where you are in the tree, what the branch did, then the question and its options
312 on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
313 const { Box, Text, Button, Input } = $.ui.resolve(e)
314 const width = Math.max(30, (e.props.bodyColumns || 60) - 2)
315 const node = nodeAt(path)
316
317 if (!root || !node) return <Text dimColor>Waiting for Claude to ask you something.</Text>
318
319 // The breadcrumb: Question › B SQLite › A WAL mode
320 const crumbs = ['Question']
321 let walk = root
322 for (const i of path) {
323 crumbs.push(String.fromCharCode(65 + i) + ' ' + walk.children[i].label)
324 walk = walk.children[i]
325 }
326 const nav = (
327 <Box gap={2} marginTop={1}>
328 {path.length ? <Button key="back" label="Back" onPress={() => { path = path.slice(0, -1); $.ui.invalidate('ui.render') }} /> : null}
329 {path.length > 1 ? <Button key="top" label="Top" onPress={() => { path = []; $.ui.invalidate('ui.render') }} /> : null}
330 {node.sid && path.length ? <Button key="cont" label="Continue branch" onPress={() => continueBranch($, node)} /> : null}
331 <Button key="map" label="Map" onPress={() => { view = 'map'; $.ui.invalidate('ui.render') }} />
332 <Button key="close" label="Close" onPress={() => $.ui.close({ id: PANE })} />
333 </Box>
334 )
335
336 if (node.status === 'thinking') return <Text color="yellow">Reading the conversation to explain the question...</Text>
337
338 // The map: the whole tree at once. Press a question or an explored option to open it.
339 if (view === 'map') {
340 const here = path.join('.')
341 return (
342 <Box flexDirection="column" width={width}>
343 <Text bold>Map · ★ recommended · ▸ explored · ✎ yours</Text>
344 <Text>{' '}</Text>
345 {mapRows(root, [], '', []).map((row, n) => {
346 // Mark the option you are on, or the first question when you are at the top
347 const isHere = row.path && row.path.join('.') === here && (row.kind !== 'question' || !row.path.length)
348 const text = (isHere ? '● ' : ' ') + row.text
349 if (!row.path) return <Text key={'r' + n} dimColor>{text}</Text>
350 return <Button key={'r' + n} plain label={text}
351 onPress={() => { path = row.path; view = 'node'; $.ui.invalidate('ui.render') }} />
352 })}
353 <Box gap={2} marginTop={1}>
354 <Button key="node" label="Back to question" onPress={() => { view = 'node'; $.ui.invalidate('ui.render') }} />
355 <Button key="close" label="Close" onPress={() => $.ui.close({ id: PANE })} />
356 </Box>
357 </Box>
358 )
359 }
360 if (node.status === 'exploring') {
361 return (
362 <Box flexDirection="column" width={width}>
363 <Text dimColor>{crumbs.join(' › ')}</Text>
364 <Text color="yellow">{'Forking the session and playing out "' + node.label + '"... (read-only, about 20 to 60s)'}</Text>
365 {nav}
366 </Box>
367 )
368 }
369 if (node.status === 'failed') {
370 return (
371 <Box flexDirection="column" width={width}>
372 <Text dimColor>{crumbs.join(' › ')}</Text>
373 <Text color="red">Could not explain it: {String(node.reason)}</Text>
374 {nav}
375 </Box>
376 )
377 }
378
379 const data = node.data
380 const pick = (data.recommendation && data.recommendation.label) || ''
381 return (
382 <Box flexDirection="column" width={width}>
383 <Text dimColor>{crumbs.join(' › ')}</Text>
384 {path.length ? (
385 <Box borderStyle="quote" borderColor="magenta" paddingLeft={1} flexDirection="column" marginBottom={1}>
386 <Text bold color="magenta">{'If you pick ' + node.label}</Text>
387 {data.outcome ? <Text>{data.outcome}</Text> : null}
388 {(data.steps || []).map((s, j) => <Text key={'s' + j} color="blue">{(j + 1) + '. ' + s}</Text>)}
389 <Text dimColor>{'branch session ' + String(node.sid).slice(0, 8) + (node.ms ? ' · ' + Math.round(node.ms / 1000) + 's' : '')}</Text>
390 </Box>
391 ) : null}
392 {data.question ? (
393 <Box borderStyle="double" borderColor="cyan" paddingX={1} flexDirection="column">
394 <Text bold color="cyan">{data.question}</Text>
395 {data.context ? <Text dimColor>{data.context}</Text> : null}
396 </Box>
397 ) : <Text dimColor>No further decision on this branch.</Text>}
398 {data.options.map((o, i) => {
399 const isPick = o.label === pick && !o.mine
400 const child = node.children[i]
401 const color = isPick ? 'green' : o.mine ? 'yellow' : 'gray'
402 return (
403 <Box key={'opt' + i} flexDirection="column">
404 <Text dimColor>{' │'}</Text>
405 <Box borderStyle={isPick ? 'bold' : 'round'} borderColor={color} paddingX={1} flexDirection="column">
406 <Text bold color={color === 'gray' ? 'white' : color}>{String.fromCharCode(65 + i) + ' ' + o.label + (isPick ? ' ★ recommended' : '') + (o.mine ? ' ✎ your answer' : '')}</Text>
407 {o.detail ? <Text>{o.detail}</Text> : null}
408 {o.leadsTo ? <Text color="blue">{'→ ' + o.leadsTo}</Text> : null}
409 {(o.pros || []).map((p, j) => <Text key={'p' + j} color="green">{'+ ' + p}</Text>)}
410 {(o.cons || []).map((c, j) => <Text key={'c' + j} color="red">{'- ' + c}</Text>)}
411 <Button key={'x' + i} label={child ? (child.status === 'exploring' ? 'Exploring...' : 'Open branch ▸') : 'Explore ▸'}
412 onPress={() => explore($, i)} />
413 </Box>
414 </Box>
415 )
416 })}
417 {data.question ? (
418 <Box flexDirection="column">
419 <Text dimColor>{' │'}</Text>
420 <Box borderStyle="round" borderColor="gray" borderDimColor paddingX={1} flexDirection="column">
421 <Text dimColor bold>{String.fromCharCode(65 + data.options.length) + ' Other'}</Text>
422 <Input key={'other.' + path.join('.')} placeholder="type your own answer" submitLabel="explore"
423 onSubmit={value => { if (value.trim()) explore($, -1, value.trim()) }} />
424 </Box>
425 </Box>
426 ) : null}
427 {pick ? <Text>{' '}</Text> : null}
428 {pick ? <Text color="green">{'★ ' + pick + ': ' + data.recommendation.why}</Text> : null}
429 {nav}
430 </Box>
431 )
432 })
433}
434