A fuse for your head: it shows the heat, warns you, then trips before you burn out.

A fuse for your head in Claude Code. It shows how hot this hour runs above the prompt, and after 40 minutes without a break it holds your prompts for ten minutes so you take one.
Works in Claude Code only. It needs the free cogload command line tool, which you install yourself; the plugin never installs anything.
bun add -g @drakulavich/cogload
/plugin marketplace add drakulavich/cogload
/plugin install cognitive-load@cogload
cogload 0.13.0 or newer, with Bun on the machine.
/cogload. Names what drives the last sixty minutes in counts, and the week's rests taken and skipped.skip: <reason> (three words or more) as the first or last line of a prompt. Sent on its own, it lifts the rest and brings the held prompts back into the box.cogload status when a session starts, after each turn and every minute, and cogload today --json for /cogload. It looks for cogload on Claude Code's PATH, then in ~/.bun/bin.~/.claude/projects on your machine and turns them into counts: prompts, sessions, decisions, tokens, minutes. It keeps, writes and prints no message text, prompt length, file path or session title.skip: line. While a rest lasts, the held prompts' text stays in the session's memory, never on disk, until the rest is lifted or the first prompt after it ends.cogload status and cogload today --json. The program is cogload on Claude Code's PATH, or ~/.bun/bin/cogload when the PATH has none, which is why the command is not one fixed string. It runs nothing else.session.start and turn.complete refresh the reading; ui.render draws the band above the prompt; command.run answers only /cogload; prompt.submit sees the prompts you type or send from your phone, to hold them during a rest, find a skip: line and add the notes below. Prompts from other plugins, notifications or scheduled tasks pass untouched.skip: sent alone, asking Claude to say in one line that the rest is lifted. Everything else stays on your screen: the band, toasts and /cogload's answer.How the numbers are made explains the score. Privacy policy. MIT licensed. The icon is 🤯 from Noto Emoji, under the Apache License 2.0.
hooks/register.ts 344 lines1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, Register } from 'claude-code'
3
4import type { Level, Status } from '../types'
5
6const status = atom({ plugin: 'cognitive-load', key: 'status' } as const, null)
7const lastToast = atom({ plugin: 'cognitive-load', key: 'lastToast' } as const, 0)
8const held = atom({ plugin: 'cognitive-load', key: 'held' } as const, [] as string[])
9
10const LEVELS = ['Calm', 'Warming', 'Heating', 'Fried'] as const
11const COLOR: Record<Level, string> = { Calm: 'success', Warming: 'warning', Heating: '#ff8700', Fried: 'red' }
12const NARROW = 50
13const CLOCK_SKEW_MS = 60_000
14const TOAST_GAP_MS = 2100
15const HELD: readonly string[] = ['composer', 'bridge']
16const WEEK_MS = 7 * 24 * 60 * 60_000
17const HOUR_MS = 60 * 60_000
18const SKIP = /^(?:skip|override):(.*)$/i
19const PHRASES = [
20 'Stand up and stretch.',
21 'Water, then a window.',
22 'Look at something far away.',
23 'Walk to the kitchen and back.',
24 'Roll your shoulders, unclench your jaw.',
25 'Close your eyes for a minute.',
26 'Breathe out slower than you breathe in.',
27 'The code will wait.',
28]
29const SHORT = 'A skip needs a reason of three words or more.'
30const BACK = 'Your prompt is back in the box: to send it, add "skip: <reason>" as its last line.'
31const WELCOME = 'Keep your head cold. The dot above the prompt shows how hot this hour runs.'
32const MISSING = "cogload is not on Claude Code's PATH: bun add -g @drakulavich/cogload"
33const NO_READING = 'cogload gave no reading.'
34const OLDER = 'cogload is older than this plugin: bun add -g @drakulavich/cogload@latest'
35const ISO_INSTANT = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})$/
36
37type Override = { at: number; reason: string }
38type Part = 'parallel' | 'pace' | 'supervision' | 'reading' | 'streak' | 'late'
39type Live = {
40 sessions: number
41 prompts: number
42 decisions: number
43 contextSwitches: number
44 outputTokens: number
45 streakMin: number
46 score: { index: number; level: Level; capped: Part[]; top: Part } | null
47}
48
49const isInt = (v: unknown, min: number, max: number): v is number =>
50 Number.isInteger(v) && (v as number) >= min && (v as number) <= max
51
52const isIndex = (v: unknown): v is number | null => v === null || isInt(v, 0, 100)
53
54const isInstant = (v: unknown): v is string => typeof v === 'string' && ISO_INSTANT.test(v)
55
56const decodeStatus = (stdout: string, nowMs: number): Status | null => {
57 let s: unknown
58 try {
59 s = JSON.parse(stdout.trim())
60 } catch {
61 return null
62 }
63 if (typeof s !== 'object' || s === null || Array.isArray(s)) return null
64 const o = s as Record<string, unknown>
65 const asOf = isInstant(o.asOf) ? Date.parse(o.asOf) : Number.NaN
66 const isLevel = o.index === null ? o.level === null : LEVELS.includes(o.level as Level)
67 const isValid =
68 o.schema === 1 &&
69 !Number.isNaN(asOf) &&
70 asOf <= nowMs + CLOCK_SKEW_MS &&
71 typeof o.date === 'string' &&
72 /^\d{4}-\d{2}-\d{2}$/.test(o.date) &&
73 isInt(o.hour, 0, 23) &&
74 isIndex(o.index) &&
75 isIndex(o.peak) &&
76 isLevel &&
77 isInt(o.activeMin, 0, 1500) &&
78 isInt(o.streakMin, 0, 1500) &&
79 (o.restAt === null || isInstant(o.restAt)) &&
80 isInt(o.restMin, 1, 60)
81 return isValid
82 ? {
83 schema: 1,
84 asOf: o.asOf as string,
85 date: o.date as string,
86 hour: o.hour as number,
87 index: o.index as number | null,
88 level: o.level as Level | null,
89 peak: o.peak as number | null,
90 activeMin: o.activeMin as number,
91 streakMin: o.streakMin as number,
92 restAt: o.restAt as string | null,
93 restMin: o.restMin as number,
94 }
95 : null
96}
97
98// Claude Code drops a plugin's toast that comes within 2000 ms of its last one.
99const toast = async ($: EngineInterface, text: string) => {
100 const now = await $.clock.now()
101 let at = now
102 await update($, lastToast, last => {
103 at = Math.max(now, last + TOAST_GAP_MS)
104 return at
105 })
106 if (at === now) $.ui.toast(text)
107 else $.clock.after(at - now, () => $.ui.toast(text))
108}
109
110const formatMinutes = (min: number): string =>
111 min < 60 ? `${min}m` : `${Math.floor(min / 60)}h${String(min % 60).padStart(2, '0')}`
112
113const clockTime = (ms: number): string => new Date(ms).toTimeString().slice(0, 5)
114
115const past = (until: number): string =>
116 `The person is on a rest until ${clockTime(until)}. This prompt came from their phone through Remote Control, which the rest lets through. Begin your reply with one short line saying it went past the rest, then answer as usual.`
117
118const LIFTED =
119 'The person just lifted their rest with this skip line, and nothing else was sent. Reply with one short line saying the rest is lifted.'
120
121const PHRASE: Record<Part, (l: Live) => string> = {
122 parallel: l => `${l.sessions} sessions at once`,
123 pace: l => `${l.prompts} prompts`,
124 supervision: l => `${l.decisions} decisions and ${l.contextSwitches} context switches`,
125 reading: l => `${Math.round(l.outputTokens / 1000)}k output tokens`,
126 streak: l => `a ${formatMinutes(l.streakMin)} streak`,
127 late: () => 'late at night',
128}
129
130const joinHeld = (list: string[]): string =>
131 list.filter((p, i) => !list.slice(i + 1).some(q => q.includes(p))).join('\n\n')
132
133const hourLine = (live: Live, score: NonNullable<Live['score']>): string => {
134 const head = `${score.level} ${score.index} this hour`
135 if (score.index === 0) return `${head}: you have been away.`
136 if (score.capped.length > 0) return `${head}, at the cap: ${score.capped.map(p => PHRASE[p](live)).join(', ')}.`
137 return `${head}, mostly ${PHRASE[score.top](live)}.`
138}
139
140type Day = { live?: Live | null }
141
142const plural = (n: number, word: string): string => `${n} ${word}${n === 1 ? '' : 's'}`
143
144const restUntil = async ($: EngineInterface, now: number): Promise<number | null> => {
145 const until = await $.store.get('restUntil')
146 return typeof until === 'number' && now < until ? until : null
147}
148
149const overridesSince = async ($: EngineInterface, since: number): Promise<Override[]> => {
150 const list = await $.store.get('overrides')
151 return Array.isArray(list) ? (list as Override[]).filter(o => o.at > since) : []
152}
153
154const restsSince = async ($: EngineInterface, since: number): Promise<number[]> => {
155 const list = await $.store.get('rests')
156 return Array.isArray(list) ? (list as number[]).filter(at => at > since) : []
157}
158
159const isSpent = async ($: EngineInterface, s: Status): Promise<boolean> =>
160 s.restAt !== null && (await $.store.get('spent')) === s.restAt
161
162const startRestIfDue = async ($: EngineInterface, s: Status) => {
163 const now = await $.clock.now()
164 const isFried = s.level === 'Fried'
165 const friedAt = await $.store.get('friedAt')
166 const isFriedDue = isFried && (typeof friedAt !== 'number' || now - friedAt >= HOUR_MS)
167 const isStreakDue = s.restAt !== null && Date.parse(s.asOf) >= Date.parse(s.restAt)
168 if (!isStreakDue && !isFriedDue) return
169 if (await isSpent($, s)) return
170 const until = now + s.restMin * 60_000
171 await $.store.set('restUntil', until)
172 await $.store.set('rests', [...(await restsSince($, now - WEEK_MS)), now])
173 await $.store.set('spent', s.restAt)
174 if (isFried) await $.store.set('friedAt', now)
175 await toast($, `Rest until ${clockTime(until)}. Streak ${formatMinutes(s.streakMin)}, ${s.level} ${s.index}.`)
176}
177
178const toastOnce = async ($: EngineInterface, key: string, text: string) => {
179 if ((await $.store.get(key)) === true) return
180 await $.store.set(key, true)
181 await toast($, text)
182}
183
184const RUN_TIMEOUT_MS = 10_000
185const REFRESH_MS = 60_000
186const STALE_MS = 5 * 60_000
187
188const weekLine = async ($: EngineInterface, now: number): Promise<string | null> => {
189 const rests = await restsSince($, now - WEEK_MS)
190 if (rests.length === 0) return null
191 const pushed = (await overridesSince($, now - WEEK_MS)).filter(o => rests.some(at => at <= o.at))
192 const taken = `This week: ${plural(rests.length - pushed.length, 'rest')} taken`
193 const newest = pushed.at(-1)
194 return newest === undefined ? `${taken}.` : `${taken}, ${pushed.length} skipped (last: "${newest.reason}").`
195}
196
197const spawn = async ($: EngineInterface, argv: string[], env?: Record<string, string>) => {
198 const startedAt = await $.clock.now()
199 try {
200 return await $.process.run(argv, { timeoutMs: RUN_TIMEOUT_MS, env })
201 } catch {
202 return (await $.clock.now()) - startedAt >= RUN_TIMEOUT_MS ? 'timeout' : 'not found'
203 }
204}
205
206const run = async ($: EngineInterface, args: string[]) => {
207 const r = await spawn($, ['cogload', ...args])
208 if (r !== 'not found') return r
209 const home = await $.env.get('HOME')
210 if (home === undefined) return r
211 const bin = `${home}/.bun/bin`
212 const path = await $.env.get('PATH')
213 // cogload is a `#!/usr/bin/env bun` script, and a script-installed bun sits beside it.
214 return spawn($, [`${bin}/cogload`, ...args], { PATH: path ? `${bin}:${path}` : bin })
215}
216
217const take = async ($: EngineInterface, s: Status) => {
218 await startRestIfDue($, s)
219 await update($, status, () => s)
220}
221
222const isOlder = (stdout: string): boolean => {
223 try {
224 const o = JSON.parse(stdout.trim())
225 return o?.schema === 1 && o.restAt === undefined
226 } catch {
227 return false
228 }
229}
230
231const refresh = async ($: EngineInterface) => {
232 const r = await run($, ['status'])
233 const decoded = typeof r === 'string' || r.exitCode !== 0 ? null : decodeStatus(r.stdout, await $.clock.now())
234 if (decoded === null) {
235 const failure = typeof r === 'string' ? r : r.exitCode === 0 ? 'bad line' : `exit ${r.exitCode}`
236 $.ui.log(failure, { to: 'debug' })
237 if (failure === 'not found') await toastOnce($, 'missingShown', MISSING)
238 if (typeof r !== 'string' && r.exitCode === 0 && isOlder(r.stdout)) await toastOnce($, 'olderShown', OLDER)
239 return false
240 }
241 await $.store.set('reading', decoded)
242 await take($, decoded)
243 return true
244}
245
246const tick = async ($: EngineInterface) => {
247 const reading = (await $.store.get('reading')) as Status | undefined
248 const age = reading === undefined ? Number.POSITIVE_INFINITY : (await $.clock.now()) - Date.parse(reading.asOf)
249 if (reading !== undefined && age < REFRESH_MS) return take($, reading)
250 if ((await refresh($)) || age < STALE_MS) return
251 await $.store.delete('reading')
252 await update($, status, () => null)
253}
254
255export const register: Register = on => {
256 // Not awaited: the engine holds the turn until these hooks return.
257 on('session.start', async ($, e, next) => {
258 const result = await next(e)
259 await $.command.register({ name: 'cogload', description: "What drives this hour's load, and the week's rests and skips" })
260 toastOnce($, 'welcomed', WELCOME)
261 .catch(() => {})
262 .then(() => refresh($))
263 .catch(() => {})
264 $.clock.every(REFRESH_MS, () => {
265 tick($).catch(() => {})
266 })
267 return result
268 })
269
270 on('turn.complete', async ($, e, next) => {
271 const result = await next(e)
272 refresh($).catch(() => {})
273 return result
274 })
275
276 on('command.run', { command: 'cogload' }, async $ => {
277 const r = await run($, ['today', '--json'])
278 if (r === 'not found') return { text: MISSING }
279 let day: unknown = null
280 try {
281 if (r !== 'timeout' && r.exitCode === 0) day = JSON.parse(r.stdout)
282 } catch {}
283 if (typeof day !== 'object' || day === null) return { text: NO_READING }
284 const live = (day as Day).live
285 const score = live?.score
286 if (score && !Array.isArray(score.capped)) return { text: OLDER }
287 const hour = live && score ? hourLine(live, score) : 'Nothing scored this hour.'
288 const week = await weekLine($, await $.clock.now())
289 return { text: [hour, ...(week === null ? [] : [week])].join('\n') }
290 })
291
292 on('prompt.submit', async ($, e, next) => {
293 if (!HELD.includes(e.origin.kind)) return next(e)
294 const now = await $.clock.now()
295 const until = await restUntil($, now)
296 if (until === null) {
297 await update($, held, () => [])
298 return next(e)
299 }
300 const lines = e.text.trimEnd().split('\n')
301 const first = SKIP.exec(lines[0] ?? '')
302 const last = lines.length > 1 ? SKIP.exec(lines.at(-1) ?? '') : null
303 const skip = first ?? last
304 const reason = skip?.[1]?.trim() ?? ''
305 if (reason.split(/\s+/).length >= 3) {
306 await $.store.delete('restUntil')
307 await $.store.set('overrides', [...(await overridesSince($, now - WEEK_MS)), { at: now, reason }])
308 const text = lines.slice(first ? 1 : 0, last ? -1 : undefined).join('\n').trim()
309 const back = joinHeld(await read($, held))
310 await update($, held, () => [])
311 if (text !== '') return next({ ...e, text })
312 // The submit empties the box after this hook returns, so the fill waits for it.
313 if (back !== '') $.clock.after(0, () => void $.prompt.fill({ text: back, mode: 'replace' }))
314 return next({ ...e, context: [...(e.context ?? []), LIFTED] })
315 }
316 if (e.origin.kind === 'bridge') return next({ ...e, context: [...(e.context ?? []), past(until)] })
317 if (skip !== null) return { drop: `${SHORT} Your prompt is back in the box.` }
318 const phrase = await $.store.get('phrase')
319 const n = typeof phrase === 'number' ? phrase : 0
320 await $.store.set('phrase', (n + 1) % PHRASES.length)
321 await update($, held, list => [...list, e.text])
322 const left = `${Math.ceil((until - now) / 60_000)} min left`
323 return { drop: `${PHRASES[n % PHRASES.length]} ${left}. ${BACK}` }
324 })
325
326 on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
327 const beneath = await next(e)
328 const s = await read($, status)
329 if (e.props.hasSurvey || s === null || s.index === null || s.level === null) return beneath
330 const now = await $.clock.now()
331 const until = await restUntil($, now)
332 const isAhead = until === null && s.restAt !== null && Date.parse(s.restAt) > Date.parse(s.asOf) && !(await isSpent($, s))
333 const parts: string[] = []
334 if (until !== null) parts.push(`rest until ${clockTime(until)} (${Math.ceil((until - now) / 60_000)} min)`)
335 else if (isAhead && s.restAt !== null) parts.push(`rest at ${clockTime(Date.parse(s.restAt))}`)
336 else if (e.props.bodyColumns >= NARROW && s.streakMin > 0) parts.push(`streak ${formatMinutes(s.streakMin)}`)
337 const { Box, Text } = $.ui.resolve(e)
338 const head = Text({ color: COLOR[s.level], children: `● ${s.level}` })
339 const own =
340 parts.length === 0 ? head : Box({ children: [head, Text({ dimColor: true, children: parts.map(p => ` · ${p}`).join('') })] })
341 return Box({ flexDirection: 'column', children: [own, beneath] })
342 })
343}
344types/index.d.ts 22 lines1export type Level = 'Calm' | 'Warming' | 'Heating' | 'Fried'
2
3export type Status = {
4 schema: 1
5 asOf: string
6 date: string
7 hour: number
8 index: number | null
9 level: Level | null
10 peak: number | null
11 activeMin: number
12 streakMin: number
13 restAt: string | null
14 restMin: number
15}
16
17declare module 'claude-code' {
18 interface PluginState {
19 'cognitive-load': { status: Status | null; lastToast: number; held: string[] }
20 }
21}
22