Asks what you expect while a long task runs, then shows how your predictions hold up

A Claude Code mod that keeps you doing your own thinking about your business and its users. It does two things:
PLAN.md explains the reasoning and the review that shaped this version.
My take: on a new line. A notice says why.Details:
CLASSIFY in hooks/register.tsx. Code, tooling, chores, and short replies go straight through. Edit the definition to match what you mean by a thinking question.My take: line to any prompt without being asked. Claude gets the same instruction, and it counts as a take.expect: to any prompt: `` Find out why cancellations rose in September expect: the price change in August drove it ``d to discuss, which puts your prediction and the verdict in the prompt box as a question for Claudex to dismissA prediction that names something checkable teaches more than "it will work", which gets rated Too vague.
Covers the last 6 weeks, across every project:
Each take and prediction is one JSON file in ~/.claude/think-first/records/.
claude --plugin-dir ~/Code/claude-code-setup/mods/think-firstCLAUDE_CODE_PLUGIN_DIRS in ~/.claude/settings.json. That change is yours to make.expect: line in one reaches Claude.claude plugin validate mods/think-first
claude plugin test mods/think-firsthooks/register.tsx 430 lines1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, PromptOrigin, Register } from 'claude-code'
3
4import type { Entry, Gate, Open, Prediction, Rating, Take } from '../types'
5
6const PANE = 'think-first'
7const MARKER = 'My take:'
8const EXPECT_LINE = /^[ \t]*expect:[ \t]*(.*)$/gim
9/** Shorter prompts are replies in a conversation, not questions worth a take. */
10const MIN_QUESTION_CHARS = 20
11const QUIET_AFTER_SKIP_MS = 30 * 60_000
12const HISTORY_WEEKS = 6
13const OFF_LIST = 10
14const DAY_MS = 86_400_000
15const MONTHS = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
16const RATING_LABELS: Record<Rating, string> = {
17 hit: 'Hit',
18 partly: 'Partly right',
19 miss: 'Miss',
20 vague: 'Too vague to check',
21}
22
23const CLASSIFY = `You sort a message a person sent to their coding agent. The message is inside <message> tags. Do not answer or act on it. Reply with one word, THINK or BUILD.
24
25THINK: the message asks for judgment about the person's business or its users: what users need, do, or feel and why; how the business works, makes money, or grows; strategy; priorities; product direction; or whether a product decision is right.
26
27BUILD: anything else, including writing, fixing, reviewing, explaining, or running code; configuration and tooling; chores; and short replies within a conversation.`
28
29const CHECK = `You check a person's prediction against what actually happened. The person wrote the prediction before an AI agent did the work. Reply in exactly two lines:
30
31RATING: hit, partly, miss, or vague
32GAP: one sentence
33
34hit: the result matches the prediction's specific claim.
35partly: some of its claims matched and some did not. A prediction with one right claim and one wrong claim is partly.
36miss: the result contradicts all of it.
37vague: it is too general to check against the result, such as "it will work".
38
39GAP, for partly or miss: what the person expected versus what turned out to be true, concretely. For hit: what made the prediction right. For vague: what a checkable prediction would have named. Address the person as "you".`
40
41const TAKE_NOTE =
42 'think-first: the user wrote their own take after "My take:" before seeing yours. Before giving your answer, respond to their take: say what holds up, what is wrong or missing, and what evidence would settle it. Do not simply agree with it.'
43
44const NOTICE = `Your take first: write it after "${MARKER}" and press Enter. To skip, press Enter with it empty.`
45
46const GATE = atom({ plugin: 'think-first', key: 'gate' } as const, null as Gate | null)
47const OPEN = atom({ plugin: 'think-first', key: 'open' } as const, null as Open | null)
48const HISTORY = atom({ plugin: 'think-first', key: 'history' } as const, [] as Entry[])
49
50let isOn = false
51let dir = ''
52let sessionId = ''
53let folder = ''
54let quietUntil = 0
55// The full prompt behind the open prediction, for the check. A reload loses it,
56// and the check then reads the prediction's shortened copy.
57let predictedPrompt: string | null = null
58
59function isPersonsWords(origin: PromptOrigin): boolean {
60 return origin.kind === 'composer' || origin.kind === 'bridge' || (origin.kind === 'plugin' && origin.asUser === true)
61}
62
63/** Takes the `expect:` lines out of a prompt. */
64function splitExpect(text: string): { text: string; expect: string | null } {
65 const found = [...text.matchAll(EXPECT_LINE)].map(m => (m[1] ?? '').trim()).filter(Boolean)
66 if (found.length === 0) return { text, expect: null }
67
68 return {
69 text: text
70 .replace(EXPECT_LINE, '')
71 .replace(/\n{3,}/g, '\n\n')
72 .trim(),
73 expect: found.join(' '),
74 }
75}
76
77/** Splits a prompt at its last `My take:` line, or returns null when it has none. */
78function splitTake(text: string): { question: string; take: string } | null {
79 const at = text.lastIndexOf(MARKER)
80 if (at === -1 || (at > 0 && text[at - 1] !== '\n')) return null
81
82 return { question: text.slice(0, at).trim(), take: text.slice(at + MARKER.length).trim() }
83}
84
85// One prompt can make a take and a prediction in the same millisecond, so the kind is part of the id.
86async function newId($: EngineInterface, kind: Entry['kind']): Promise<{ id: string; at: number }> {
87 const at = await $.clock.now()
88
89 return { id: `${at}-${sessionId.slice(0, 8)}-${kind}`, at }
90}
91
92// Each record is its own file, written only by the session that made it, so
93// sessions running at once never overwrite each other's records.
94async function save($: EngineInterface, entry: Entry) {
95 await $.fs.write(`${dir}/${entry.id}.json`, JSON.stringify(entry))
96 await update($, HISTORY, h => [entry, ...h.filter(one => one.id !== entry.id)])
97}
98
99async function saveTake($: EngineInterface, question: string, take: string | null) {
100 const { id, at } = await newId($, 'take')
101 const entry: Take = { kind: 'take', id, at, folder, question: question.slice(0, 300), take }
102 await save($, entry)
103}
104
105async function isThinkingQuestion($: EngineInterface, text: string): Promise<boolean> {
106 $.ui.status('Checking whether this asks for your take…')
107 const r = await $.model.complete({
108 model: 'haiku',
109 system: CLASSIFY,
110 prompt: `<message>\n${text.slice(0, 4000)}\n</message>`,
111 maxTokens: 5,
112 effort: 'low',
113 timeoutMs: 3000,
114 })
115 $.ui.status(undefined)
116
117 return r.isAnswered && /THINK/i.test(r.text)
118}
119
120/** Fills the prompt box once the engine has cleared it of the dropped prompt. */
121function refill($: EngineInterface, text: string) {
122 $.clock.after(50, () => {
123 void $.prompt.fill({ text: `${text.trimEnd()}\n\n${MARKER} `, mode: 'replace' })
124 })
125}
126
127function parseCheck(text: string): { rating: Rating; gap: string } | null {
128 const rating = /RATING:\s*(hit|partly|miss|vague)/i.exec(text)?.[1]?.toLowerCase() as Rating | undefined
129 const gap = /GAP:\s*(.+)/i.exec(text)?.[1]?.trim()
130
131 return rating && gap ? { rating, gap } : null
132}
133
134async function check($: EngineInterface, p: Prediction, prompt: string, answer: string) {
135 const r = await $.model.complete({
136 model: 'sonnet',
137 system: CHECK,
138 prompt: `<request>\n${prompt.slice(0, 6000)}\n</request>\n<prediction>\n${p.expect}\n</prediction>\n<result>\n${answer.slice(0, 12_000)}\n</result>`,
139 maxTokens: 300,
140 effort: 'low',
141 timeoutMs: 60_000,
142 })
143 const parsed = r.isAnswered ? parseCheck(r.text) : null
144 const checked: Prediction = { ...p, rating: parsed?.rating ?? null, gap: parsed?.gap ?? null }
145 await save($, checked)
146 await update($, OPEN, o => (o?.prediction.id === p.id ? { prediction: checked, phase: 'checked' as const } : o))
147}
148
149async function discuss($: EngineInterface) {
150 const o = await read($, OPEN)
151 if (!o) return
152 await update($, OPEN, () => null)
153 const p = o.prediction
154 const verdict = p.rating ? ` A check rated it "${RATING_LABELS[p.rating]}": ${p.gap}` : ''
155 await $.prompt.fill({
156 text: `Before that turn I predicted: "${p.expect}".${verdict} Where was my thinking off, and what should I have looked at?`,
157 mode: 'replace',
158 })
159}
160
161function parseEntry(text: string): Entry | null {
162 try {
163 const e = JSON.parse(text) as Entry
164 if (typeof e.id !== 'string' || typeof e.at !== 'number') return null
165
166 return e.kind === 'take' || e.kind === 'prediction' ? e : null
167 } catch {
168 return null
169 }
170}
171
172async function loadHistory($: EngineInterface) {
173 const since = (await $.clock.now()) - HISTORY_WEEKS * 7 * DAY_MS
174 const files = await $.fs.list(dir).catch(() => [])
175 const names = files.map(f => f.name).filter(name => name.endsWith('.json') && Number(name.split('-')[0]) >= since)
176 const texts = await Promise.all(names.map(name => $.fs.read(`${dir}/${name}`).catch(() => '')))
177 const list = texts
178 .map(t => parseEntry(String(t)))
179 .filter((e): e is Entry => e !== null)
180 .sort((a, b) => b.at - a.at)
181 await update($, HISTORY, () => list)
182}
183
184function day(at: number): string {
185 const d = new Date(at)
186
187 return `${MONTHS[d.getMonth()]} ${d.getDate()}`
188}
189
190/** Midnight of the Monday that starts the week holding `at`, local time. */
191function weekStart(at: number): number {
192 const d = new Date(at)
193 d.setHours(0, 0, 0, 0)
194 d.setDate(d.getDate() - ((d.getDay() + 6) % 7))
195
196 return d.getTime()
197}
198
199function counts(list: Entry[]) {
200 const takes = list.filter((e): e is Take => e.kind === 'take')
201 const predictions = list.filter((e): e is Prediction => e.kind === 'prediction')
202 const rated = (rating: Rating) => predictions.filter(p => p.rating === rating).length
203
204 return {
205 asked: takes.length,
206 given: takes.filter(t => t.take !== null).length,
207 predictions: predictions.length,
208 hit: rated('hit'),
209 partly: rated('partly'),
210 miss: rated('miss'),
211 vague: rated('vague'),
212 }
213}
214
215function lastSegment(path: string): string {
216 return path.split('/').filter(Boolean).at(-1) ?? path
217}
218
219export const register: Register = on => {
220 on('session.start', async ($, e, next) => {
221 const r = await next(e)
222 isOn = e.isInteractive
223 if (!isOn) return r
224 sessionId = await $.session.id()
225 folder = await $.session.root()
226 dir = `${(await $.env.get('HOME')) ?? ''}/.claude/think-first/records`
227 await $.command.register({ name: 'think', description: 'Show your takes and where your predictions were off' })
228
229 return r
230 })
231
232 on('session.end', async ($, e, next) => {
233 if (isOn && e.reason === 'clear') {
234 await update($, GATE, () => null)
235 await update($, OPEN, () => null)
236 predictedPrompt = null
237 }
238
239 return next(e)
240 })
241
242 on('prompt.submit', async ($, e, next) => {
243 // A prompt sent while a turn runs reaches that turn directly; it is left alone.
244 if (!isOn || e.turnId || !isPersonsWords(e.origin)) return next(e)
245 const { text, expect } = splitExpect(e.text)
246 const take = splitTake(text)
247 let context = e.context
248 let sent = text
249
250 if (await read($, GATE)) {
251 await update($, GATE, () => null)
252 if (take?.take) {
253 await saveTake($, take.question, take.take)
254 context = [...(context ?? []), TAKE_NOTE]
255 } else {
256 // An empty take, or a prompt rewritten without one: a skip.
257 await saveTake($, take?.question ?? text, null)
258 quietUntil = (await $.clock.now()) + QUIET_AFTER_SKIP_MS
259 if (take) sent = take.question
260 }
261 } else if (take?.take) {
262 // A take the person wrote without being asked.
263 await saveTake($, take.question, take.take)
264 context = [...(context ?? []), TAKE_NOTE]
265 } else if (
266 !take &&
267 text.length >= MIN_QUESTION_CHARS &&
268 (await $.clock.now()) >= quietUntil &&
269 (await isThinkingQuestion($, text))
270 ) {
271 const at = await $.clock.now()
272 await update($, GATE, () => ({ question: text, at }))
273 refill($, e.text)
274
275 return { drop: NOTICE }
276 }
277
278 if (expect && sent) {
279 const { id, at } = await newId($, 'prediction')
280 const prediction: Prediction = {
281 kind: 'prediction',
282 id,
283 at,
284 folder,
285 prompt: sent.slice(0, 300),
286 expect,
287 rating: null,
288 gap: null,
289 }
290 predictedPrompt = sent
291 await update($, OPEN, () => ({ prediction, phase: 'running' as const }))
292 }
293
294 return next({ ...e, text: sent || e.text, context })
295 })
296
297 on('turn.complete', async ($, e, next) => {
298 const r = await next(e)
299 if (!isOn || e.agentId) return r
300 const o = await read($, OPEN)
301 if (o?.phase !== 'running') return r
302 const p = o.prediction
303 const prompt = predictedPrompt ?? p.prompt
304 predictedPrompt = null
305 if (e.reason === 'answer' && !e.isAborted && e.answer.trim()) {
306 await update($, OPEN, () => ({ prediction: p, phase: 'checking' as const }))
307 void check($, p, prompt, e.answer)
308 } else {
309 // An interrupted turn has no result to check the prediction against.
310 await update($, OPEN, () => null)
311 await save($, p)
312 }
313
314 return r
315 })
316
317 on('command.run', { command: 'think' }, async $ => {
318 await loadHistory($)
319 await $.ui.open({ id: PANE, title: 'Your thinking', focus: true, closeOnEscape: true })
320
321 return { text: 'Opened your thinking record.' }
322 })
323
324 on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
325 if (!isOn || e.props.hasSurvey) return next(e)
326 const o = await read($, OPEN)
327 if (!o) return next(e)
328 const { Box, Button, Text } = $.ui.resolve(e)
329 const p = o.prediction
330
331 if (o.phase !== 'checked') {
332 return (
333 <Text dimColor wrap="truncate-end">
334 You expect: {p.expect}
335 {o.phase === 'checking' ? ' · checking it against the result…' : ''}
336 </Text>
337 )
338 }
339
340 return (
341 <Box flexDirection="column">
342 <Text wrap="truncate-end">
343 <Text bold>You expected:</Text> {p.expect}
344 </Text>
345 {p.rating ? (
346 <Text wrap="wrap">
347 <Text bold>{RATING_LABELS[p.rating]}.</Text> {p.gap}
348 </Text>
349 ) : (
350 <Text dimColor>The check didn't answer.</Text>
351 )}
352 <Box flexDirection="row" gap={2}>
353 <Button key="discuss" label="Discuss" hotkey="d" plain onPress={() => discuss($)} />
354 <Button key="dismiss" label="Dismiss" hotkey="x" plain onPress={() => update($, OPEN, () => null)} />
355 </Box>
356 </Box>
357 )
358 })
359
360 on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
361 const { Box, Text } = $.ui.resolve(e)
362 const list = await read($, HISTORY)
363
364 if (list.length === 0) {
365 return (
366 <Box flexDirection="column">
367 <Text>Nothing recorded in the last {HISTORY_WEEKS} weeks.</Text>
368 <Text dimColor>A question about your business or users asks for your take first.</Text>
369 <Text dimColor>To make a prediction, add a line starting "expect:" to a prompt.</Text>
370 </Box>
371 )
372 }
373
374 const all = counts(list)
375 const weeks = new Map<number, Entry[]>()
376 for (const entry of list) {
377 const w = weekStart(entry.at)
378 weeks.set(w, [...(weeks.get(w) ?? []), entry])
379 }
380 const off = list
381 .filter(
382 (p): p is Prediction =>
383 p.kind === 'prediction' && (p.rating === 'miss' || p.rating === 'partly' || p.rating === 'vague'),
384 )
385 .slice(0, OFF_LIST)
386
387 return (
388 <Box flexDirection="column">
389 <Text dimColor>Last {HISTORY_WEEKS} weeks, all projects</Text>
390 <Text>
391 Your take first on <Text bold>{all.given}</Text> of {all.asked} thinking questions
392 </Text>
393 <Text>
394 {all.predictions} predictions: {all.hit} hit · {all.partly} partly · {all.miss} miss · {all.vague} too vague
395 </Text>
396 <Text> </Text>
397 <Text bold>
398 {'Week of'.padEnd(10)}
399 {'Takes'.padEnd(10)}Predictions
400 </Text>
401 {[...weeks.entries()].map(([w, entries]) => {
402 const c = counts(entries)
403
404 return (
405 <Text>
406 {day(w).padEnd(10)}
407 {`${c.given} of ${c.asked}`.padEnd(10)}
408 {c.predictions}
409 </Text>
410 )
411 })}
412 <Text> </Text>
413 <Text bold>Where your thinking was off</Text>
414 {off.length === 0 && <Text dimColor>No missed, partial, or vague predictions yet.</Text>}
415 {off.map(p => (
416 <Box flexDirection="column" marginBottom={1}>
417 <Text wrap="wrap">
418 <Text bold>{p.rating ? RATING_LABELS[p.rating] : ''}:</Text> you expected "{p.expect}"
419 </Text>
420 <Text wrap="wrap">{p.gap}</Text>
421 <Text dimColor wrap="truncate-end">
422 {day(p.at)} · {lastSegment(p.folder)} · {p.prompt.replace(/\s+/g, ' ')}
423 </Text>
424 </Box>
425 ))}
426 </Box>
427 )
428 })
429}
430types/index.d.ts 44 lines1export type Rating = 'hit' | 'partly' | 'miss' | 'vague'
2
3/** A thinking question the mod held back for the person's own take. `take` is null when they skipped. */
4export type Take = {
5 kind: 'take'
6 id: string
7 at: number
8 /** The session's project folder. */
9 folder: string
10 question: string
11 take: string | null
12}
13
14/** A prediction from an `expect:` line. `rating` and `gap` stay null until the check answers. */
15export type Prediction = {
16 kind: 'prediction'
17 id: string
18 at: number
19 folder: string
20 /** The start of the prompt, without its `expect:` line. */
21 prompt: string
22 expect: string
23 rating: Rating | null
24 /** One sentence from the check: where the person's thinking was off, or what made it right. */
25 gap: string | null
26}
27
28export type Entry = Take | Prediction
29
30/** A thinking question waiting in the prompt box for the person's take. */
31export type Gate = { question: string; at: number }
32
33/**
34 * The prediction the band shows: `running` while its turn runs, `checking`
35 * while the check reads the result, `checked` once it answered or failed.
36 */
37export type Open = { prediction: Prediction; phase: 'running' | 'checking' | 'checked' }
38
39declare module 'claude-code' {
40 interface PluginState {
41 'think-first': { gate: Gate | null; open: Open | null; history: Entry[] }
42 }
43}
44