SLOPSHOPPER

Brain Bar

A human-knowledge health bar that drains as Claude edits your code and refills when you pass a quiz about your own project.

panebandguardcommandtoastmodel
v1.2.5no licenseupdated 2026-10-24sameerthapax/know-your-claude/brain-bar
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · brain-bar
│ ┃ brain-test ✕ › fix the failing auth test and add ╭──────────────────────────────╮ │ ┃ ╔═══════════════════════════════════════════ │ brain-bar │ │ ┃ ║ ▓▒░ BRAIN TEST ░▒▓ ⏺ Read(src/auth.ts) │ Could not write a brain test │ │ ┃ ║ ══════════════════════════════════════════ ⎿ 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 │ ┃ ║ LOADING. │ ┃ ║ READING THIS SESSION › /brain-test │ ┃ ║ │ ┃ ║ ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ │ ┃ ║ │ ┃ ║ │ ┃ ║ │ ┃ ║ │ ┃ ║ │ ┃ ║ │ ┃ ║ │ ┃ ║ │ ┃ ║ │ ┃ ║ 💥 ███████████████████████████████████████▓ 10,000 / 10,000 HP -78 Claude created cache.ts writing your brain te ⟨Claude Code's own drawing⟩ ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Band
💥 ███████████████████████████████████████▓ 10,000 / 10,000 HP -78 Claude created cache.ts writi ⟨Claude Code's own drawing⟩
Pane · brain-test
╔══════════════════════════════════════════════════════╗ ║ ▓▒░ BRAIN TEST ░▒▓ · ║ ║ ════════════════════════════════════════════════════ ║ ║ ║ ║ ▄▄▄▄▄▄ ║ ║ ▀▀▀▀▀▀▀ ▄ ▄▀▀▀▄▀▀▄▀▀▀▄ ║ ║ ▀▀▀▀▀▀▀▀▀▀▀ ▀ ▄ ▀ ▀▀▀▀▄▀▀▄▀▀▀▀ ║ ║ ▀ ▀ ▀ ▀ ▀▀▀▄▀ ║ ║ ║ ║ ║ ║ ║ ║ LOADING. ║ ║ READING THIS SESSION ║ ║ ║ ║ ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ║ ╚══════════════════════════════════════════════════════╝
README

Brain Bar

A health bar for your knowledge of the code. Every line Claude writes for you is a line you did not write yourself, so the bar drains as Claude works. Win it back by passing a short quiz about your own project.

🧠 ████████████████████████████████░░░░░░░░  7,936 / 10,000 HP   -24 Claude edited architecture.md (architecture ×2)   [ Test my brain ]

How health changes

Health starts at 10,000 and is kept per project (per folder you start Claude Code in), across sessions.

EventHP
Each line Claude adds−4
Each line Claude changes−2
Each line Claude deletes−5
A new file Claude creates−50, plus its lines
Lines in an architecture file×2
Right answer: easy / medium / hard+200 / +500 / +1,000
Wrong answer−100

Health never goes above 10,000. The bar is green from 6,000, yellow below 6,000, and red below 3,000. Every change plays a short animation: a loss blinks red and drains away, a gain glows green and grows in.

Claude's Edit, Write, and NotebookEdit tools count, and so do files Claude changes through Bash (for example sed or a Python one-liner): the mod reads git status before and after each Bash command and charges for every file whose text changed in between. That works only inside a git repository, and only for files git sees (gitignored files are not counted). A file you edit yourself while a Bash command is running is counted as Claude's.

Architecture files are anything under infra/, terraform/, .github/workflows/, docs/adr/, or a contract/ or contracts/ folder, plus docs/architecture.md and any .tf, .tfvars, or .bicep file. Change the list in ARCHITECTURE at the top of hooks/register.js.

The brain test

Start it with the Test my brain button on the bar, or:

/brain-test              five questions about the project, mostly its architecture
/brain-test animation    every question about the topic you type
  • Five questions: two easy, two medium, one hard, four choices each.
  • ↑ ↓ select, Enter answers, Esc cancels at any stage, loading included.
  • A right answer flashes and counts up its points; a wrong one shakes, is struck through, and shows the right answer with a one-line reason.
  • It opens by itself while Claude is working once health is below 6,000, at most once per reply. Claude Code only opens a panel unasked in a terminal at least 144 columns wide; in a narrower one you get a reminder instead.

The questions are written by a separate model call (Sonnet) that this mod makes, so the mod holds the answers and Claude never sees them.

Sound and music

Short effects (start, select, right, wrong, done, alert) and a quiet looping 8-bit track while a test is open. All sounds are generated and included in sounds/.

  • Windows (WSL): a small hidden PowerShell player (sounds/player.ps1) mixes the music and the effects. It stops when the test ends or the panel closes, when a newer player starts, and by itself if the mod stops sending a heartbeat for 6 seconds. Volumes are at the top of player.ps1 ($musicVolume = 0.06, $sfxVolume = 0.55).
  • macOS: effects play through Claude Code's own player; there is no music.
  • Linux (not WSL): no sound; everything else works.

What it reads, runs, and sends

  • Reads: the files Claude edits (to count lines), git status and the changed files' text around each Bash command, and for a quiz: this session's recent conversation including the tool calls Claude made, git diff HEAD, git log, git ls-files, and the first part of README.md, CLAUDE.md, and docs/architecture.md.
  • Sends: that quiz context to a model on your own Claude plan, once per test. Nothing else leaves your machine.
  • Runs: git, and on WSL wslpath and powershell.exe for sound.
  • Writes: health to Claude Code's per-plugin store (~/.claude/plugins/store/), and on WSL the sound files and player to %TEMP%\brain-bar on Windows.

Requirements

Claude Code 2.1.287 or newer, git. Tested with 2.1.289 on Windows (WSL, Ubuntu).

Tests

claude plugin test

Nine tests cover the quiz panel, right and wrong answers, the final screen, a small panel, the automatic opening below 6,000 HP, and each health cost.

Source 1 files
hooks/register.js 1133 lines
1// Human knowledge bar: a health bar above the prompt that Claude's edits
2// drain (4 HP per added line, 2 per changed line, 5 per deleted line) and a
3// brain test about the project wins back (easy 200, medium 500, hard 1000).
4// Health is kept per project, capped at 10,000.
5//
6// The quiz is written by a separate model call, so this mod holds the right
7// answers and Claude never sees them. It runs in this mod's own pane, where
8// the arrow keys move between answer cards and Enter picks one; Claude Code's
9// question dialog is never used for it, so Claude's own questions are untouched.
10//
11// Below 6,000 HP the test opens by itself while Claude is working.
12
13const MAX_HP = 10_000
14const LOW_HP = 6_000
15const COST = { add: 4, change: 2, del: 5 }
16const NEW_FILE_COST = 50
17const WRONG_ANSWER_COST = 100
18// Files that shape the whole system cost double: Terraform and other
19// infrastructure, pipelines, the alert contract, and decision records
20const ARCHITECTURE = [
21  /(^|\/)infra\//,
22  /(^|\/)terraform\//,
23  /\.(tf|tfvars|bicep)$/,
24  /(^|\/)\.github\/workflows\//,
25  /(^|\/)docs\/adr\//,
26  /(^|\/)contracts?\//,
27  /(^|\/)docs\/architecture\.md$/,
28]
29const POINTS = { easy: 200, medium: 500, hard: 1000 }
30const DOTS = { easy: 1, medium: 2, hard: 3 }
31const PLAN = ['easy', 'easy', 'medium', 'medium', 'hard']
32const LETTERS = ['A', 'B', 'C', 'D']
33const TICK_MS = 100
34const CONTEXT_CHARS = 40_000
35const CONVERSATION_CHARS = 25_000
36const PANE = 'brain-test'
37const INLINE_ROWS = 24
38
39// One theme color, in three shades; everything else is the terminal's own text color
40const THEME = '#d97757'
41const THEME_LIGHT = '#f2b49b'
42const THEME_DEEP = '#8f4a35'
43const INK = '#1c1c1c'
44
45// Claude Code's own spinner glyphs
46const SPINNER = ['·', '✢', '✳', '✶', '✻', '✽', '✻', '✶', '✳', '✢']
47
48// Shared by the hooks below
49let hp = MAX_HP
50let projectKey = 'hp'
51let lastDelta = null
52let quiz = null // { questions, index, score, right, isLoading, isDone, feedback, startHp, doneAt }
53let selected = 0
54let resolveAnswer = null
55let frame = 0
56let timer = null
57let isWorking = false
58let autoOpenedThisTurn = false
59const touched = new Set()
60
61// ---------- health ----------
62
63// Green from 6,000, yellow below 6,000, red below 3,000
64function hpColor(value) {
65  if (value >= 6000) return '#87af87'
66  if (value >= 3000) return '#d7af5f'
67  return '#d75f5f'
68}
69
70// The change animation: { from, to, ms }, stepped by its own timer
71const ANIM_MS = 1500
72const ANIM_STEP = 50
73let anim = null
74let animTimer = null
75
76function startHpAnim($, from, to) {
77  // A second change mid-animation starts from what is on screen now
78  anim = { from: anim ? shownHp() : from, to, ms: 0 }
79  if (animTimer) return
80  animTimer = $.clock.every(ANIM_STEP, () => {
81    if (anim) anim.ms += ANIM_STEP
82    if (!anim || anim.ms >= ANIM_MS) {
83      anim = null
84      if (animTimer) animTimer.cancel()
85      animTimer = null
86    }
87    $.ui.invalidate('ui.render')
88  })
89}
90
91// Eased progress 0..1 of the animation's second phase (after a short hold)
92function animProgress() {
93  if (!anim) return 1
94  const t = Math.max(0, (anim.ms - 350) / (ANIM_MS - 350))
95  return 1 - Math.pow(1 - Math.min(1, t), 3)
96}
97
98// The number on screen: counts from the old value to the new one
99function shownHp() {
100  if (!anim) return hp
101  return Math.round(anim.from + (anim.to - anim.from) * animProgress())
102}
103
104// ---------- desktop band ----------
105
106// The bar as three colored boxes sharing the row by flex weight, so it
107// stretches with the window the way the desktop lays out any row
108function barBoxes(Box, solid, ghost, color, ghostColor) {
109  const piece = (key, grow, backgroundColor) => Box({ key, width: 0, height: 1, flexGrow: grow, backgroundColor })
110  return [
111    piece('solid', solid, color),
112    piece('ghost', ghost, ghostColor),
113    piece('empty', 1 - solid - ghost, '#8884'),
114  ]
115}
116
117// Claude Code Desktop: everything on one row, the bar taking the room left over.
118// Narrow rows drop the change note first, then shorten the labels.
119async function desktopBand($, e, next) {
120  const { Box, Text, Button } = $.ui.resolve(e)
121  const cols = typeof e.props.bodyColumns === 'number' ? e.props.bodyColumns : 120
122  const color = hpColor(hp)
123  const shown = shownHp()
124  const isHit = anim && anim.to < anim.from
125  const isHeal = anim && anim.to > anim.from
126  const blink = anim ? Math.floor(anim.ms / 150) % 2 === 0 : false
127
128  // Same pieces as the terminal bar, as fractions of the whole
129  let solid = hp / MAX_HP
130  let ghost = 0
131  let ghostColor = color
132  if (isHit) {
133    const edge = anim.from + (anim.to - anim.from) * animProgress()
134    ghost = Math.max(0, edge / MAX_HP - solid)
135    ghostColor = blink ? '#ff5f5f' : '#870000'
136  } else if (isHeal) {
137    solid = (anim.from + (anim.to - anim.from) * animProgress()) / MAX_HP
138    ghost = Math.max(0, hp / MAX_HP - solid)
139    ghostColor = blink ? '#d7ffd7' : '#87af87'
140  }
141  solid = Math.min(1, Math.max(0, solid))
142  ghost = Math.min(ghost, 1 - solid)
143
144  const fixed = (child, key) => Box({ key, flexShrink: 0, children: [child] })
145  const children = [
146    fixed(Text({ children: [isHit && anim.ms < 450 ? '💥' : '🧠'] }), 'icon'),
147    Box({
148      key: 'bar',
149      flexGrow: 1,
150      flexShrink: 1,
151      minWidth: 8,
152      flexDirection: 'row',
153      height: 1,
154      overflow: 'hidden',
155      children: barBoxes(Box, solid, ghost, color, ghostColor),
156    }),
157    fixed(
158      Text({
159        bold: true,
160        ...(isHit ? { color: '#ff8787' } : isHeal ? { color: '#afffaf' } : {}),
161        children: [shown.toLocaleString() + (cols >= 60 ? ' / 10,000 HP' : ' HP')],
162      }),
163      'hp',
164    ),
165  ]
166  if (lastDelta && cols >= 80) {
167    children.push(
168      Box({
169        key: 'delta',
170        flexShrink: 1,
171        minWidth: 0,
172        children: [
173          Text({
174            wrap: 'truncate-end',
175            color: lastDelta.value > 0 ? '#87af87' : '#d78787',
176            children: [(lastDelta.value > 0 ? '+' : '') + lastDelta.value + ' ' + lastDelta.note],
177          }),
178        ],
179      }),
180    )
181  }
182  if (quiz && quiz.isLoading) {
183    children.push(fixed(Text({ dimColor: true, children: [cols >= 50 ? 'writing your brain test…' : 'writing…'] }), 'status'))
184  } else if (quiz && !quiz.isDone) {
185    children.push(fixed(Text({ dimColor: true, children: [(cols >= 50 ? 'brain test ' : '') + (quiz.index + 1) + '/' + quiz.questions.length] }), 'status'))
186  } else if (!quiz) {
187    children.push(fixed(Button({ key: 'brain-test', label: cols >= 50 ? 'Test my brain' : 'Test', onPress: () => startFromButton($) }), 'button'))
188  }
189  const bar = Box({ flexDirection: 'row', flexWrap: 'nowrap', alignItems: 'center', gap: 1, width: '100%', children })
190  const theirs = await next(e)
191  return Box({ flexDirection: 'column', children: theirs ? [bar, theirs] : [bar] })
192}
193
194// Lines added, changed, and deleted between two texts, by line content
195function lineDiff(before, after) {
196  const count = (text) => {
197    const m = new Map()
198    for (const l of text === '' ? [] : text.replace(/\n$/, '').split('\n')) m.set(l, (m.get(l) || 0) + 1)
199    return m
200  }
201  const a = count(before)
202  const b = count(after)
203  let added = 0
204  let removed = 0
205  for (const [l, n] of b) added += Math.max(0, n - (a.get(l) || 0))
206  for (const [l, n] of a) removed += Math.max(0, n - (b.get(l) || 0))
207  const change = Math.min(added, removed)
208  return { add: added - change, change, del: removed - change }
209}
210
211async function setHp($, value, note) {
212  const before = hp
213  hp = Math.max(0, Math.min(MAX_HP, Math.round(value)))
214  await $.store.set(projectKey, hp)
215  if (hp !== before) {
216    startHpAnim($, before, hp)
217    lastDelta = { value: hp - before, note }
218    $.clock.after(15_000, () => {
219      lastDelta = null
220      $.ui.invalidate('ui.render')
221    })
222  }
223  $.ui.invalidate('ui.render')
224}
225
226function isArchitecture(file) {
227  return ARCHITECTURE.some((pattern) => pattern.test(String(file || '')))
228}
229
230async function drain($, diff, file, isNewFile) {
231  const isArch = isArchitecture(file)
232  const lines = diff.add * COST.add + diff.change * COST.change + diff.del * COST.del
233  const cost = lines * (isArch ? 2 : 1) + (isNewFile ? NEW_FILE_COST : 0)
234  if (file) touched.add(file)
235  const name = String(file || '').split('/').pop()
236  const why = (isNewFile ? 'Claude created ' : 'Claude edited ') + name + (isArch ? ' (architecture ×2)' : '')
237  if (cost > 0) await setHp($, hp - cost, why)
238  await maybeAutoOpen($)
239}
240
241// Files Claude changes through Bash (sed, a heredoc, a script) never pass
242// through Edit or Write, so each Bash call is bracketed by two looks at git:
243// every file git calls changed or untracked, with its text. A file whose text
244// differs between the two looks was changed by the command, and is measured
245// against its text before (or HEAD's, if it was clean then). Outside a git
246// repository nothing is measured.
247const SNAPSHOT_MAX_FILES = 300
248const SNAPSHOT_MAX_CHARS = 1_000_000
249
250async function gitTop($) {
251  const out = await run($, ['git', '-C', await $.session.root(), 'rev-parse', '--show-toplevel'])
252  return out.trim() || null
253}
254
255async function readText($, path) {
256  try {
257    if (!(await $.fs.exists(path))) return ''
258    const text = await $.fs.read(path)
259    // Binary or huge files are not lines of code
260    return text.length > SNAPSHOT_MAX_CHARS || text.includes('\u0000') ? null : text
261  } catch {
262    return null
263  }
264}
265
266// { path: text } for every changed or untracked file, paths relative to top
267async function snapshot($, top) {
268  const out = await run($, ['git', '-C', top, 'status', '--porcelain=v1', '-z', '--untracked-files=all'])
269  const entries = out.split('\0')
270  const files = new Map()
271  for (let i = 0; i < entries.length && files.size < SNAPSHOT_MAX_FILES; i++) {
272    const entry = entries[i]
273    if (entry.length < 4) continue
274    // A rename is followed by its old path, which is not a file to read
275    if (entry[0] === 'R' || entry[0] === 'C') i++
276    const path = entry.slice(3)
277    files.set(path, await readText($, top + '/' + path))
278  }
279  return files
280}
281
282async function drainShellChanges($, top, before, after) {
283  for (const [path, text] of after) {
284    if (text === null) continue
285    const wasDirty = before.has(path)
286    if (wasDirty && before.get(path) === text) continue
287    const old = wasDirty ? before.get(path) : await run($, ['git', '-C', top, 'show', 'HEAD:' + path])
288    if (old === null) continue
289    await drain($, lineDiff(old, text), top + '/' + path, old === '' && !wasDirty)
290  }
291}
292
293// Below 6,000 HP, while Claude is working, open the test once per turn
294async function maybeAutoOpen($) {
295  if (hp >= LOW_HP || !isWorking || quiz || autoOpenedThisTurn) return
296  autoOpenedThisTurn = true
297  const r = await $.ui.open({ id: PANE, title: 'Brain test', closeOnEscape: true, rows: INLINE_ROWS })
298  if (r && r.isPlaced === false) {
299    await $.ui.close({ id: PANE })
300    $.ui.toast('🧠 Knowledge is low (' + hp.toLocaleString() + ' HP). Type /brain-test to win it back.', { timeoutMs: 8000 })
301    return
302  }
303  sfx($, 'alert')
304  runQuiz($).catch(() => {}) // stopped by a reload; nothing to report
305}
306
307// ---------- sound ----------
308
309// Under WSL a small Windows PowerShell player (sounds/player.ps1) mixes quiet
310// looping music with short effects; this mod sends it numbered commands
311// through a file. Claude Code's own player is macOS only, so elsewhere the
312// effects use $.audio.play and there is no music.
313const SOUND_FILES = ['alert', 'correct', 'done', 'music', 'select', 'start', 'wrong']
314let soundDir = null // the player's folder, as this side sees it
315let soundStarting = null
316let soundSeq = 0
317let soundQueue = []
318
319async function startPlayer($) {
320  const temp = await $.process.run(['powershell.exe', '-NoProfile', '-Command', '[IO.Path]::GetTempPath()'], { timeoutMs: 8000 })
321  if (temp.exitCode !== 0 || !temp.stdout.trim()) return null
322  const unix = await $.process.run(['wslpath', '-u', temp.stdout.trim()], { timeoutMs: 3000 })
323  if (unix.exitCode !== 0) return null
324  const dir = unix.stdout.trim().replace(/\/$/, '') + '/brain-bar'
325  const src = $.plugin.root + '/sounds/'
326  await $.process.run(['mkdir', '-p', dir], { timeoutMs: 3000 })
327  await $.process.run(
328    ['cp', ...SOUND_FILES.map((n) => src + n + '.wav'), src + 'player.ps1', dir + '/'],
329    { timeoutMs: 10000 },
330  )
331  await $.process.run(['rm', '-f', dir + '/commands.txt', dir + '/player.log'], { timeoutMs: 3000 })
332  await $.fs.write(dir + '/alive.txt', String(Date.now()))
333  const win = (await $.process.run(['wslpath', '-w', dir], { timeoutMs: 3000 })).stdout.trim()
334  await $.process.run(
335    [
336      'powershell.exe', '-NoProfile', '-Command',
337      "Start-Process powershell.exe -WindowStyle Hidden -ArgumentList '-NoProfile','-ExecutionPolicy','Bypass','-File','" +
338        win + "\\player.ps1','-Dir','" + win + "'",
339    ],
340    { timeoutMs: 10000 },
341  )
342  // Wait for the player to say it started, so no command is missed
343  for (let i = 0; i < 40; i++) {
344    if (await $.fs.exists(dir + '/player.log')) return dir
345    await $.clock.sleep(100)
346  }
347  return null
348}
349
350// Starts the player once per quiz; resolves to its folder, or null without one
351let soundUnavailable = false
352
353async function player($) {
354  if (soundDir) return soundDir
355  if (soundUnavailable) return null
356  if (!soundStarting) {
357    soundSeq = 0
358    soundQueue = []
359    soundStarting = startPlayer($).catch(() => null)
360  }
361  soundDir = await soundStarting
362  soundStarting = null
363  // No Windows player here (not WSL): stop trying, use $.audio.play
364  if (!soundDir) soundUnavailable = true
365  return soundDir
366}
367
368async function sendSound($, command) {
369  const dir = await player($)
370  if (!dir) return false
371  soundSeq += 1
372  soundQueue = [...soundQueue, soundSeq + ' ' + command].slice(-20)
373  try {
374    await $.fs.write(dir + '/commands.txt', soundQueue.join('\n') + '\n')
375    return true
376  } catch {
377    return false
378  }
379}
380
381async function sfx($, name) {
382  if (await sendSound($, 'sfx ' + name)) return
383  try {
384    await $.audio.play({ asset: 'sounds/' + name + '.wav' })
385  } catch {
386    // No player here; the quiz works without sound
387  }
388}
389
390async function music($, isOn) {
391  await sendSound($, 'music ' + (isOn ? 'start' : 'stop'))
392}
393
394// Tells the player the mod is still here; it stops itself without this
395function heartbeat($) {
396  if (soundDir) $.fs.write(soundDir + '/alive.txt', String(Date.now())).catch(() => {})
397}
398
399// Stops the music and lets the player exit after its last effect
400async function stopPlayer($) {
401  if (!soundDir) return
402  await sendSound($, 'quit')
403  soundDir = null
404}
405
406// ---------- quiz ----------
407
408async function run($, args) {
409  try {
410    const r = await $.process.run(args, { timeoutMs: 15_000 })
411    return r.exitCode === 0 ? r.stdout : ''
412  } catch {
413    return ''
414  }
415}
416
417async function readHead($, path, chars) {
418  try {
419    if (!(await $.fs.exists(path))) return ''
420    return (await $.fs.read(path)).slice(0, chars)
421  } catch {
422    return ''
423  }
424}
425
426// The newest part of this session's conversation, with the code Claude ran
427async function conversation($) {
428  let messages = []
429  try {
430    messages = await $.session.messages()
431  } catch {
432    return ''
433  }
434  const lines = []
435  for (const m of messages.slice(-120)) {
436    if (m.text && m.text.trim()) lines.push(m.role + ': ' + m.text.trim().slice(0, 2000))
437    for (const u of m.toolUses || []) lines.push('[' + u.tool + '] ' + JSON.stringify(u.input || {}).slice(0, 2500))
438  }
439  return lines.join('\n').slice(-CONVERSATION_CHARS)
440}
441
442async function gatherContext($) {
443  const parts = []
444  const add = (title, text) => {
445    if (text && text.trim()) parts.push('## ' + title + '\n' + text.trim())
446  }
447  add('This session so far (newest last)', await conversation($))
448  add('Files Claude changed this session', [...touched].join('\n'))
449  add('Uncommitted changes', (await run($, ['git', 'diff', 'HEAD'])).slice(0, 12_000))
450  add('Recent commits', await run($, ['git', 'log', '--stat', '-8', '--format=--- %s']))
451  add('Project files', (await run($, ['git', 'ls-files'])).split('\n').slice(0, 300).join('\n'))
452  add('README.md', await readHead($, 'README.md', 6_000))
453  add('CLAUDE.md', await readHead($, 'CLAUDE.md', 6_000))
454  add('docs/architecture.md', await readHead($, 'docs/architecture.md', 6_000))
455  return parts.join('\n\n').slice(0, CONTEXT_CHARS)
456}
457
458function parseQuiz(text) {
459  const start = text.indexOf('{')
460  const end = text.lastIndexOf('}')
461  if (start < 0 || end < start) return null
462  const data = JSON.parse(text.slice(start, end + 1))
463  const questions = (data.questions || []).filter(
464    (q) =>
465      POINTS[q.difficulty] &&
466      typeof q.question === 'string' &&
467      Array.isArray(q.choices) &&
468      q.choices.length === 4 &&
469      Number.isInteger(q.answer) &&
470      q.answer >= 0 &&
471      q.answer < 4,
472  )
473  return questions.length ? questions : null
474}
475
476function startTicker($) {
477  if (timer) return
478  timer = $.clock.every(TICK_MS, () => {
479    frame += 1
480    if (frame % 20 === 0) heartbeat($)
481    $.ui.invalidate('ui.render')
482  })
483}
484
485function stopTicker() {
486  if (timer) timer.cancel()
487  timer = null
488}
489
490// Opens the quiz pane; called from what the person did, so it shows at any width
491async function openPane($) {
492  const r = await $.ui.open({ id: PANE, title: 'Brain test', focus: true, closeOnEscape: true, rows: INLINE_ROWS })
493  if (r && r.isPlaced === false) $.ui.toast('The brain test pane is waiting: ' + (r.reason || 'widen the terminal'))
494}
495
496// Resolves with the answer index the person picks, or null when the pane closes
497function waitForAnswer() {
498  return new Promise((resolve) => {
499    resolveAnswer = resolve
500  })
501}
502
503function answer(i) {
504  if (!resolveAnswer || !quiz || quiz.feedback) return
505  const resolve = resolveAnswer
506  resolveAnswer = null
507  resolve(i)
508}
509
510async function startFromButton($) {
511  await openPane($)
512  runQuiz($).catch(() => {}) // stopped by a reload; nothing to report
513}
514
515// Each quiz run gets a number; closing the pane cancels the current one.
516// A run that finds its number out of date stops at its next step.
517let quizRun = 0
518let quizAbort = null
519
520function cancelQuiz($, shouldSay) {
521  if (!quiz) return
522  quizRun += 1
523  if (quizAbort) quizAbort.abort()
524  quizAbort = null
525  if (resolveAnswer) {
526    const resolve = resolveAnswer
527    resolveAnswer = null
528    resolve(null)
529  }
530  quiz = null
531  stopTicker()
532  stopPlayer($).catch(() => {})
533  $.ui.invalidate('ui.render')
534  if (shouldSay) $.ui.toast('Brain test cancelled')
535}
536
537async function runQuiz($, topic) {
538  if (quiz) return
539  quizRun += 1
540  const thisRun = quizRun
541  const isCurrent = () => thisRun === quizRun
542  quizAbort = new AbortController()
543  const signal = quizAbort.signal
544  quiz = { questions: [], index: 0, score: 0, right: 0, isLoading: true, isDone: false, feedback: null, startHp: hp, loadAt: frame }
545  selected = 0
546  startTicker($)
547  sfx($, 'start').then(() => music($, true)).catch(() => {})
548  $.ui.invalidate('ui.render')
549  try {
550    const context = await gatherContext($)
551    if (!isCurrent()) return
552    const r = await $.model.complete({
553      model: 'sonnet',
554      system:
555        'You write short multiple-choice quizzes that check whether a developer understands their own project. ' +
556        'Reply with JSON only, no prose and no code fences.',
557      prompt:
558        'Write ' + PLAN.length + ' questions in this order of difficulty: ' + PLAN.join(', ') + '.\n' +
559        (topic
560          ? 'Every question must be about this topic: ' + topic + '. Use the session conversation and the code Claude ran in it.\n'
561          : '') +
562        'Otherwise focus mostly on the architecture: how the parts fit together, what calls what, where data and secrets live, and why. ' +
563        'Include at least one question about the changes made this session if there are any.\n' +
564        'Easy checks a fact, medium checks how two parts connect, hard checks a design reason or a consequence of a change.\n' +
565        'Each question at most 160 characters. Exactly 4 choices, each at most 70 characters, only one correct, wrong ones plausible.\n' +
566        'Format: {"questions":[{"difficulty":"easy","question":"...","choices":["...","...","...","..."],"answer":0,"why":"one short sentence"}]}\n\n' +
567        context,
568      maxTokens: 3000,
569      timeoutMs: 120_000,
570    }, { signal })
571    if (!isCurrent()) return
572    const questions = r.isAnswered ? parseQuiz(r.text) : null
573    if (!questions) {
574      $.ui.toast('Could not write a brain test' + (r.isAnswered ? '' : ' (' + r.reason + ')'))
575      await $.ui.close({ id: PANE })
576      return
577    }
578    quiz = { ...quiz, questions, isLoading: false }
579
580    for (let i = 0; i < questions.length; i++) {
581      quiz.index = i
582      quiz.feedback = null
583      selected = 0
584      $.ui.invalidate('ui.render')
585      const q = questions[i]
586      const picked = await waitForAnswer()
587      if (picked === null || !isCurrent()) return
588      const points = POINTS[q.difficulty]
589      const isRight = picked === q.answer
590      quiz.feedback = { picked, isRight, at: frame }
591      $.ui.invalidate('ui.render')
592      sfx($, isRight ? 'correct' : 'wrong')
593      if (isRight) {
594        quiz.score += points
595        quiz.right += 1
596        await setHp($, hp + points, 'brain test')
597      } else {
598        quiz.lost = (quiz.lost || 0) + WRONG_ANSWER_COST
599        await setHp($, hp - WRONG_ANSWER_COST, 'wrong answer')
600      }
601      await $.clock.sleep(isRight ? 2000 : 5000)
602      if (!isCurrent()) return
603    }
604    quiz.isDone = true
605    quiz.doneAt = frame
606    quiz.feedback = null
607    $.ui.invalidate('ui.render')
608    sfx($, 'done')
609    $.ui.log('brain test done: ' + quiz.right + ' of ' + quiz.questions.length + ' right, +' + quiz.score + ' HP, now ' + hp.toLocaleString() + ' / 10,000')
610    await $.clock.sleep(6000)
611    if (isCurrent()) await $.ui.close({ id: PANE })
612  } finally {
613    // A cancelled run was already cleaned up by cancelQuiz
614    if (isCurrent()) {
615      stopTicker()
616      stopPlayer($).catch(() => {})
617      quiz = null
618      resolveAnswer = null
619      quizAbort = null
620      $.ui.invalidate('ui.render')
621    }
622  }
623}
624
625// ---------- fitting ----------
626
627// Rows a text takes when wrapped to a width
628function rowsOf(text, width) {
629  return Math.max(1, Math.ceil([...String(text)].length / Math.max(1, width)))
630}
631
632// Text cut to a number of characters, with an ellipsis
633function clip(text, n) {
634  const chars = [...String(text)]
635  return chars.length > n ? chars.slice(0, Math.max(0, n - 1)).join('') + '…' : chars.join('')
636}
637
638// ---------- pixel art ----------
639
640const DEFAULT_COLOR = 0x01000000
641const hex = (c) => parseInt(c.slice(1), 16)
642
643// Claude Code's mascot: X body, o eyes, l legs (two leg poses)
644const CLAWD = [
645  '..XXXXXXX..',
646  '..XoXXXoX..',
647  'XXXXXXXXXXX',
648  '..XXXXXXX..',
649]
650const LEGS = [
651  ['..l.l.l.l..', '..l.l.l.l..'],
652  ['..l.l.l.l..', '.l.l...l.l.'],
653]
654
655const BRAIN = [
656  '...XXXXXX...',
657  '.XXX.XX.XXX.',
658  'XX.XXXXXX.XX',
659  'XXXX.XX.XXXX',
660  'XX.XXXXXX.XX',
661  '.XXX.XX.XXX.',
662  '...XXXXXX...',
663  '.....XX.....',
664]
665
666// The loading picture: Claude sends knowledge across to the brain
667function loadingPixels(t, width, height) {
668  const px = Array.from({ length: height }, () => Array(width).fill(null))
669  const put = (x, y, c) => {
670    if (x >= 0 && x < width && y >= 0 && y < height) px[y][x] = c
671  }
672  const clawdX = Math.floor(width * 0.18) - 5
673  const brainX = Math.floor(width * 0.82) - 6
674  const bob = Math.floor(t / 4) % 2
675  const top = Math.floor((height - 8) / 2)
676  const art = [...CLAWD, ...LEGS[Math.floor(t / 3) % 2]]
677  art.forEach((row, y) =>
678    [...row].forEach((ch, x) => {
679      if (ch === 'X' || ch === 'l') put(clawdX + x, top + 1 + y - bob, THEME)
680      if (ch === 'o') put(clawdX + x, top + 1 + y - bob, INK)
681    }),
682  )
683  const glow = Math.floor(t / 5) % 2 === 0 ? THEME_LIGHT : THEME
684  BRAIN.forEach((row, y) => [...row].forEach((ch, x) => ch === 'X' && put(brainX + x, top + y, glow)))
685  // Sparks travel from Claude to the brain
686  const from = clawdX + 13
687  const to = brainX - 2
688  const span = Math.max(1, to - from)
689  for (let k = 0; k < 4; k++) {
690    const x = from + ((t * 1 + k * Math.ceil(span / 4)) % span)
691    const y = top + 3 + Math.round(Math.sin((x - from) / 3) * 1.2)
692    put(x, y, k % 2 ? THEME : THEME_LIGHT)
693  }
694  return px
695}
696
697// Pixels to a Raster: two pixel rows per cell, drawn with half blocks
698function toCells(px) {
699  const nums = []
700  for (let y = 0; y < px.length; y += 2) {
701    for (let x = 0; x < px[y].length; x++) {
702      const top = px[y][x]
703      const bottom = y + 1 < px.length ? px[y + 1][x] : null
704      if (top && bottom) nums.push('▀'.codePointAt(0), hex(top), hex(bottom))
705      else if (top) nums.push('▀'.codePointAt(0), hex(top), DEFAULT_COLOR)
706      else if (bottom) nums.push('▄'.codePointAt(0), hex(bottom), DEFAULT_COLOR)
707      else nums.push(32, DEFAULT_COLOR, DEFAULT_COLOR)
708    }
709  }
710  return new Uint8Array(Uint32Array.from(nums).buffer).toBase64()
711}
712
713// ---------- hooks ----------
714
715export function register(on) {
716  on('session.start', async ($, e, next) => {
717    projectKey = 'hp:' + (await $.session.root())
718    const saved = await $.store.get(projectKey)
719    hp = typeof saved === 'number' ? saved : MAX_HP
720    try {
721      await $.command.register({
722        name: 'brain-test',
723        description: 'Test your knowledge of this project to win back HP',
724        argumentHint: '[topic]',
725        immediate: true,
726      })
727    } catch {
728      // The name is taken; the button still works
729    }
730    return next(e)
731  })
732
733  // Know when Claude is working, for the low-health auto-open
734  on('turn.start', async ($, e, next) => {
735    isWorking = true
736    autoOpenedThisTurn = false
737    await maybeAutoOpen($)
738    return next(e)
739  })
740
741  on('turn.complete', async ($, e, next) => {
742    isWorking = false
743    return next(e)
744  })
745
746  // Claude's file edits drain health once they succeed
747  on('tool.call', { tool: 'Edit' }, async ($, e, next) => {
748    const r = await next(e)
749    if (r && !r.deny && !r.isError) await drain($, lineDiff(e.old_string || '', e.new_string || ''), e.file_path)
750    return r
751  })
752
753  on('tool.call', { tool: 'Write' }, async ($, e, next) => {
754    let before = ''
755    let isNewFile = false
756    try {
757      if (await $.fs.exists(e.file_path)) before = await $.fs.read(e.file_path)
758      else isNewFile = true
759    } catch {
760      before = ''
761    }
762    const r = await next(e)
763    if (r && !r.deny && !r.isError) await drain($, lineDiff(before, e.content || ''), e.file_path, isNewFile)
764    return r
765  })
766
767  on('tool.call', { tool: 'Bash' }, async ($, e, next) => {
768    const top = await gitTop($)
769    const before = top ? await snapshot($, top) : null
770    const r = await next(e)
771    // A failing command can still have written files, so isError is not checked
772    if (top && r && !r.deny) await drainShellChanges($, top, before, await snapshot($, top))
773    return r
774  })
775
776  on('tool.call', { tool: 'NotebookEdit' }, async ($, e, next) => {
777    const r = await next(e)
778    if (r && !r.deny && !r.isError) {
779      const lines = (e.new_source || '').split('\n').length
780      const diff =
781        e.edit_mode === 'insert' ? { add: lines, change: 0, del: 0 }
782        : e.edit_mode === 'delete' ? { add: 0, change: 0, del: 1 }
783        : { add: 0, change: lines, del: 0 }
784      await drain($, diff, e.notebook_path)
785    }
786    return r
787  })
788
789  on('command.run', { command: 'brain-test' }, async ($, e) => {
790    if (quiz) return {}
791    await openPane($)
792    runQuiz($, (e.args || '').trim()).catch(() => {}) // stopped by a reload
793    return {}
794  })
795
796  // The bar, always above the prompt; other mods' band drawing stays under it
797  on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
798    if (e.props.hasSurvey) return next(e)
799    if (e.surface === 'desktop') return desktopBand($, e, next)
800    const { Box, Text, Button } = $.ui.resolve(e)
801    const width = 40
802    const cells = (v) => Math.round((Math.max(0, v) / MAX_HP) * width)
803    const color = hpColor(hp)
804    const shown = shownHp()
805    const isHit = anim && anim.to < anim.from
806    const isHeal = anim && anim.to > anim.from
807    const blink = anim ? Math.floor(anim.ms / 150) % 2 === 0 : false
808
809    // Bar: the new health, then the piece that changed, then empty
810    let solid = cells(hp)
811    let ghost = 0
812    let ghostColor = color
813    if (isHit) {
814      // The lost piece blinks red, then drains away; at least one cell shows
815      const edge = anim.from + (anim.to - anim.from) * animProgress()
816      ghost = Math.max(anim.ms < ANIM_MS - 100 ? 1 : 0, cells(edge) - solid)
817      ghostColor = blink ? '#ff5f5f' : '#870000'
818    } else if (isHeal) {
819      // The gained piece glows in, growing from the old edge
820      solid = cells(anim.from + (anim.to - anim.from) * animProgress())
821      ghost = Math.max(0, cells(hp) - solid)
822      ghostColor = blink ? '#d7ffd7' : '#87af87'
823    }
824    ghost = Math.min(ghost, width - solid)
825
826    const children = [
827      Text({ children: [isHit && anim.ms < 450 ? '💥 ' : '🧠 '] }),
828      Text({ color, children: ['█'.repeat(solid)] }),
829      Text({ color: ghostColor, children: [(isHit ? '▓' : '█').repeat(ghost)] }),
830      Text({ dimColor: true, children: ['░'.repeat(width - solid - ghost)] }),
831      Text({
832        bold: true,
833        ...(isHit ? { color: '#ff8787' } : isHeal ? { color: '#afffaf' } : {}),
834        children: ['  ' + shown.toLocaleString() + ' / 10,000 HP'],
835      }),
836    ]
837    if (lastDelta) {
838      children.push(
839        Text({
840          color: lastDelta.value > 0 ? '#87af87' : '#d78787',
841          children: ['  ' + (lastDelta.value > 0 ? '+' : '') + lastDelta.value + ' ' + lastDelta.note],
842        }),
843      )
844    }
845    children.push(Text({ children: ['   '] }))
846    if (quiz && quiz.isLoading) {
847      children.push(Text({ dimColor: true, children: ['writing your brain test…'] }))
848    } else if (quiz && !quiz.isDone) {
849      children.push(Text({ dimColor: true, children: ['brain test ' + (quiz.index + 1) + '/' + quiz.questions.length] }))
850    } else if (!quiz) {
851      children.push(Button({ key: 'brain-test', label: 'Test my brain', onPress: () => startFromButton($) }))
852    }
853    const bar = Box({ flexDirection: 'row', children })
854    const theirs = await next(e)
855    return Box({ flexDirection: 'column', children: theirs ? [bar, theirs] : [bar] })
856  })
857
858  // Arrow keys move the focus between answer buttons; follow it to light the card
859  on('ui.focus', async ($, e, next) => {
860    if (e.requestId === PANE && typeof e.element === 'string' && e.element.startsWith('ans-')) {
861      const moved = Number(e.element.slice(4))
862      if (moved !== selected && e.origin && e.origin.kind === 'person') sfx($, 'select').catch(() => {})
863      selected = moved
864      $.ui.invalidate('ui.render')
865    }
866    return next(e)
867  })
868
869  // Esc or ctrl+x x closes the pane: stop the test
870  // Closing the pane cancels the test at any stage, loading included
871  on('ui.close', async ($, e, next) => {
872    if (e.id === PANE) {
873      stopPlayer($).catch(() => {})
874      // Only say so when a test was really cut short, not when it closed itself at the end
875      cancelQuiz($, Boolean(quiz && !quiz.isDone))
876    }
877    return next(e)
878  })
879
880  // Arrows scroll a pane taller than its window instead of moving the focus.
881  // While a question waits, turn those arrow presses into moving the selection.
882  on('ui.scroll', async ($, e, next) => {
883    const isArrow = e.origin && e.origin.kind === 'person' && !e.pointer && Math.abs(e.by) === 1
884    const isAsking = quiz && !quiz.isLoading && !quiz.isDone && !quiz.feedback
885    if (e.requestId !== PANE || !isArrow || !isAsking) return next(e)
886    const moved = Math.max(0, Math.min(3, selected + Math.sign(e.by)))
887    if (moved !== selected) sfx($, 'select').catch(() => {})
888    selected = moved
889    $.ui.invalidate('ui.render')
890    $.ui.focus({ requestId: PANE, key: 'ans-' + selected }).catch(() => {})
891    $.ui.scroll({ in: PANE, to: { key: 'card-' + selected } }).catch(() => {})
892    return { deny: 'the arrow moved the selection' }
893  })
894
895  // The quiz pane: retro, and sized to the pane it is given
896  on('ui.render', { component: 'Pane' }, async ($, e, next) => {
897    if (e.requestId !== PANE) return next(e)
898    const { Box, Text, Button, Raster } = $.ui.resolve(e)
899    const width = Math.max(24, e.props.bodyColumns)
900    const viewRows = e.viewport && e.viewport.rows ? e.viewport.rows : 40
901    const height =
902      e.props.placement === 'dock' ? Math.max(10, e.props.scroll.bodyRows) : Math.max(12, Math.min(INLINE_ROWS, viewRows - 8))
903    const inner = width - 4 // inside the double frame and its padding
904    const isTerminal = e.surface === 'terminal'
905    const spin = SPINNER[frame % SPINNER.length]
906    const cursor = Math.floor(frame / 5) % 2 === 0 ? '█' : ' '
907    const blank = () => Text({ children: [' '] })
908    const frameBox = (children, extra = {}) =>
909      Box({ flexDirection: 'column', width, height, borderStyle: 'double', borderColor: THEME, paddingX: 1, ...extra, children })
910    const title = (right) =>
911      Box({
912        flexDirection: 'row',
913        justifyContent: 'space-between',
914        children: [
915          Text({ bold: true, color: THEME, children: [inner < 40 ? '▓▒░ BRAIN' : '▓▒░ BRAIN TEST ░▒▓'] }),
916          Text({ color: THEME, children: [right] }),
917        ],
918      })
919    const rule = Text({ color: THEME_DEEP, children: ['═'.repeat(inner)] })
920
921    // ----- loading: Claude passing knowledge to the brain, filling the pane -----
922    if (!quiz || quiz.isLoading) {
923      const t = quiz ? frame - quiz.loadAt : frame
924      const phases = ['READING THIS SESSION', 'MAPPING THE ARCHITECTURE', 'PICKING WHAT MATTERS', 'WRITING 5 QUESTIONS']
925      const phase = phases[Math.floor(t / 25) % phases.length]
926      const barWidth = Math.min(inner - 2, 30)
927      const filled = Math.min(barWidth, Math.floor(t / 3) % (barWidth + 1))
928      const meter = '▓'.repeat(filled) + '░'.repeat(barWidth - filled)
929      const roomForArt = height - 9 >= 7 && inner >= 34
930      const artWidth = Math.min(inner, 64)
931      const art =
932        isTerminal && roomForArt
933          ? Raster({ key: 'loading', columns: artWidth, rows: 7, cells: toCells(loadingPixels(t, artWidth, 14)) })
934          : Text({ color: THEME, children: [spin + ' ' + '·•'.repeat(1 + (t % 3)) + ' 🧠'] })
935      return frameBox(
936        [
937          title(spin),
938          rule,
939          Box({
940            flexDirection: 'column',
941            flexGrow: 1,
942            justifyContent: 'center',
943            alignItems: 'center',
944            children: [
945              art,
946              blank(),
947              Text({ bold: true, color: THEME, children: ['LOADING' + '.'.repeat((Math.floor(t / 4) % 3) + 1)] }),
948              Text({ dimColor: true, children: [phase] }),
949              blank(),
950              Text({ color: THEME, children: [meter] }),
951            ],
952          }),
953        ],
954        { key: 'loading-frame' },
955      )
956    }
957
958    // ----- done: arcade score -----
959    if (quiz.isDone) {
960      const t = frame - quiz.doneAt
961      const won = Math.round(quiz.score * Math.min(1, t / 12))
962      const score = String(won).padStart(6, '0')
963      const blink = Math.floor(t / 4) % 2 === 0
964      const jump = Math.floor(t / 3) % 2
965      const px = Array.from({ length: 10 }, () => Array(11).fill(null))
966      ;[...CLAWD, ...LEGS[jump]].forEach((row, y) =>
967        [...row].forEach((ch, x) => {
968          const yy = y + 2 - jump * 2
969          if (ch === 'X' || ch === 'l') px[yy][x] = THEME
970          if (ch === 'o') px[yy][x] = INK
971        }),
972      )
973      return frameBox([
974        title('★'),
975        rule,
976        Box({
977          flexDirection: 'column',
978          flexGrow: 1,
979          justifyContent: 'center',
980          alignItems: 'center',
981          children: [
982            ...(isTerminal && height >= 16 ? [Raster({ key: 'done', columns: 11, rows: 5, cells: toCells(px) }), blank()] : []),
983            Text({ bold: true, color: THEME, children: [blink ? '★  QUIZ COMPLETE  ★' : '☆  QUIZ COMPLETE  ☆'] }),
984            blank(),
985            Text({ bold: true, children: ['SCORE  ' + score] }),
986            Text({ children: [quiz.right + ' / ' + quiz.questions.length + ' CORRECT'] }),
987            ...(quiz.lost ? [Text({ dimColor: true, children: ['−' + quiz.lost + ' HP for wrong answers'] })] : []),
988            Text({ dimColor: true, children: ['HP ' + quiz.startHp.toLocaleString() + ' → ' + hp.toLocaleString()] }),
989          ],
990        }),
991      ])
992    }
993
994    // ----- a question -----
995    const q = quiz.questions[quiz.index]
996    const fb = quiz.feedback
997    const t = fb ? frame - fb.at : 0
998    const progress = quiz.questions.map((_, i) => (i <= quiz.index ? '▰' : '▱')).join('')
999    const dots = '●'.repeat(DOTS[q.difficulty]) + '○'.repeat(3 - DOTS[q.difficulty])
1000    const right = inner < 44 ? dots : dots + '  +' + POINTS[q.difficulty] + '  ' + progress
1001
1002    // Fit to the pane: wrapped answers if they fit, one line each if not
1003    const optWidth = inner - 7 // "▶ [A] "
1004    const fixed = 2 /* frame */ + 2 /* title, rule */ + 1 /* Q n/5 */ + 1 + 1 + 1 /* blanks */ + (fb ? 3 : 1) /* footer */
1005    const questionRows = rowsOf('> ' + q.question + ' ', inner)
1006    const wrappedRows = q.choices.reduce((n, c) => n + rowsOf(c, optWidth), 0)
1007    const isRoomy = fixed + questionRows + wrappedRows <= height
1008    const isTight = fixed + questionRows + 4 > height
1009    const choiceText = (c) => (isRoomy ? c : clip(c, optWidth))
1010
1011    const rows = q.choices.map((choice, i) => {
1012      // Desktop: the whole answer is one button, its letter the hotkey chip
1013      // beside it; the app sends a mod no arrow keys, so nothing is highlighted
1014      if (e.surface === 'desktop' && !fb) {
1015        return Box({
1016          key: 'card-' + i,
1017          flexDirection: 'row',
1018          children: [
1019            Button({
1020              key: 'ans-' + i,
1021              label: choiceText(choice),
1022              plain: true,
1023              hotkey: LETTERS[i].toLowerCase(),
1024              onPress: () => answer(i),
1025            }),
1026          ],
1027        })
1028      }
1029      const isSel = i === selected && !fb
1030      const isAnswer = i === q.answer
1031      const isPicked = fb && i === fb.picked
1032      let fill = {}
1033      let text = {}
1034      let marker = ' '
1035      let shift = 0
1036
1037      if (isSel) {
1038        // Selected: an inverse bar with a blinking pointer
1039        fill = { backgroundColor: THEME }
1040        text = { color: INK, bold: true }
1041        marker = Math.floor(frame / 5) % 2 === 0 ? '▶' : '▷'
1042      } else if (fb && fb.isRight && isPicked) {
1043        // Right: the bar flashes, then stays lit
1044        const flash = t < 8 && Math.floor(t / 2) % 2 === 0
1045        fill = { backgroundColor: flash ? THEME_LIGHT : THEME }
1046        text = { color: INK, bold: true }
1047        marker = '✓'
1048      } else if (fb && !fb.isRight && isPicked) {
1049        // Wrong: the row shakes and is struck through
1050        shift = t < 8 ? [0, 2, 0, 2, 1, 0, 1, 0][t] : 0
1051        text = { strikethrough: true, dimColor: true }
1052        marker = '✗'
1053      } else if (fb && !fb.isRight && isAnswer && t >= 6) {
1054        // Then the right answer lights up and pulses
1055        fill = { backgroundColor: Math.floor(t / 3) % 2 === 0 ? THEME : THEME_LIGHT }
1056        text = { color: INK, bold: true }
1057        marker = '✓'
1058      } else if (fb) {
1059        text = { dimColor: true }
1060      }
1061
1062      return Box({
1063        key: 'card-' + i,
1064        flexDirection: 'row',
1065        marginLeft: shift,
1066        ...fill,
1067        children: [
1068          Text({ color: fill.backgroundColor ? INK : THEME, bold: true, children: [marker + ' '] }),
1069          fb
1070            ? Text({ ...text, children: ['[' + LETTERS[i] + '] '] })
1071            : Button({
1072                key: 'ans-' + i,
1073                label: '[' + LETTERS[i] + ']',
1074                plain: true,
1075                ...(i === selected ? { autoFocus: true } : {}),
1076                onPress: () => answer(i),
1077              }),
1078          Text({ ...text, wrap: isRoomy ? 'wrap' : 'truncate-end', children: [' ' + choiceText(choice)] }),
1079        ],
1080      })
1081    })
1082
1083    let footer
1084    if (!fb) {
1085      footer =
1086        e.surface === 'desktop'
1087          ? Text({ dimColor: true, children: [inner < 44 ? 'Press A–D or click' : 'Press A, B, C or D on your keyboard, or click an answer'] })
1088          : Text({ dimColor: true, children: [inner < 44 ? '↑↓ ⏎ esc' : '↑↓ SELECT   ⏎ CONFIRM   ESC QUIT'] })
1089    } else if (fb.isRight) {
1090      const won = Math.round(POINTS[q.difficulty] * Math.min(1, t / 8))
1091      const stars = Math.floor(t / 2) % 2 === 0 ? '★ ☆ ★' : '☆ ★ ☆'
1092      footer = Box({
1093        flexDirection: 'column',
1094        alignItems: 'center',
1095        children: [
1096          Text({ color: THEME, children: [stars] }),
1097          Text({ bold: true, color: THEME, children: ['CORRECT  +' + won + ' HP'] }),
1098          blank(),
1099        ],
1100      })
1101    } else {
1102      const why = 'ANSWER: ' + LETTERS[q.answer] + '. ' + (q.why || '')
1103      const typed = t < 6 ? '' : why.slice(0, (t - 6) * 4)
1104      footer = Box({
1105        flexDirection: 'column',
1106        children: [
1107          Text({ bold: true, color: THEME_DEEP, children: ['✗ WRONG  −' + WRONG_ANSWER_COST + ' HP'] }),
1108          Text({ wrap: isTight ? 'truncate-end' : 'wrap', children: [typed + (typed.length < why.length && t >= 6 ? '█' : '')] }),
1109        ],
1110      })
1111    }
1112
1113    return frameBox([
1114      title(right),
1115      rule,
1116      Text({ color: THEME, children: ['Q' + (quiz.index + 1) + '/' + quiz.questions.length + '  ' + q.difficulty.toUpperCase()] }),
1117      Text({
1118        bold: true,
1119        wrap: isTight ? 'truncate-end' : 'wrap',
1120        children: [
1121          Text({ color: THEME, children: ['> '] }),
1122          isTight ? clip(q.question, inner - 4) : q.question,
1123          Text({ color: THEME, children: [' ' + (fb ? '' : cursor)] }),
1124        ],
1125      }),
1126      ...(isTight ? [] : [blank()]),
1127      ...rows,
1128      ...(isTight ? [] : [blank()]),
1129      footer,
1130    ])
1131  })
1132}
1133