Provides estimate, checkpoint, and overrun feedback for clm tracker tasks, with explicit extra-time records in its own history.

Requirements:
curl -L dotfiles.ranolp.dev/setup | cmd /Q
Requirements:
curl dotfiles.ranolp.dev/setup | iex
Requirements:
curl -L dotfiles.ranolp.dev/setup | sh
Requirements:
curl -L dotfiles.ranolp.dev/setup | shhooks/register.ts 724 lines1import type { EngineInterface, Register, Timer, ToolSpec, ToolCallResult } from 'claude-code'
2import type { Report, Unit } from '../types'
3import {
4 CHECKPOINTS, LAST, TOOL, budgetFor, budgetLine, calibrationFactor, crossed, dueAt,
5 extensionSummary, isReport, mins, parseExtensions, parsePairs, projectedMin, reportText, statusText,
6 type Extension, type Pair,
7} from './budget'
8import { AWAKE_DEF, AWAKE_TOOL, MAX_AWAKE_MIN, awakeFile, awakeUntil } from './awake'
9
10// time-budget provides feedback on plans and estimates. Checkpoints and
11// overruns add reminders to tool results; the model records added time with
12// `extend`, and work continues while those reminders are shown.
13
14const UNITS = { plugin: 'time-budget', key: 'units' } as const
15const PARKED = { plugin: 'time-budget', key: 'parked' } as const
16const STATUS_REFRESH_MS = 60_000
17
18const GOAL = { plugin: 'time-budget', key: 'goal' } as const
19const UNLIMITED_ENV = 'CLAUDE_TIME_BUDGET_UNLIMITED'
20const GOAL_COMMAND = 'goal'
21// The words `/goal` itself reads as a clear (the binary's set of them).
22const GOAL_CLEAR_WORDS = new Set(['clear', 'stop', 'off', 'reset', 'none', 'cancel'])
23// The daemon re-reads the deadline each minute, so a 30-minute lease refreshed
24// every minute keeps the Mac up while the goal runs and lapses soon after a crash.
25const GOAL_AWAKE_MIN = 30
26const GOAL_AWAKE_REFRESH_MS = 60_000
27
28const minutes = { type: 'number', exclusiveMinimum: 0 }
29const TOOLS = [
30 {
31 name: 'estimate',
32 description: 'Open a clm tracker task and estimate its duration, or pass task with an existing issue id to resume or refine that estimate. The result shows the calibrated budget, checkpoint reminders, and recent extension history.',
33 inputSchema: {
34 type: 'object',
35 properties: {
36 minutes: { ...minutes, description: 'Your estimate for the whole task, in minutes' },
37 scope: { type: 'string', description: 'What the task covers, in one line' },
38 steps: { type: 'array', items: { type: 'string' }, description: 'The planned steps, in order' },
39 task: { type: 'string', description: 'An existing clm issue id to resume' },
40 },
41 required: ['minutes', 'scope', 'steps'],
42 },
43 },
44 {
45 name: 'report',
46 description: 'Record verified work, open items, and a finish-time projection. If more time is needed, call extend with the minutes and reason.',
47 inputSchema: {
48 type: 'object',
49 properties: {
50 done: { type: 'array', items: { type: 'object', properties: { item: { type: 'string' }, check: { type: 'string', description: 'The check that proved it done' } }, required: ['item', 'check'] } },
51 open: { type: 'array', items: { type: 'object', properties: { item: { type: 'string' }, next: { type: 'string', description: 'The next action on it' } }, required: ['item', 'next'] } },
52 more_min: { type: 'number', minimum: 0, description: 'Extra minutes the open items need beyond the budget' },
53 },
54 required: ['done', 'open'],
55 },
56 },
57 {
58 name: 'extend',
59 description: 'Record extra time for your own unit and add those minutes to its current budget. Give a reason describing the remaining work or why the estimate was low.',
60 inputSchema: {
61 type: 'object',
62 properties: {
63 minutes: { ...minutes, description: 'Additional minutes to add to the current budget' },
64 reason: { type: 'string', minLength: 1, description: 'What the extra time is for or why the estimate was low' },
65 },
66 required: ['minutes', 'reason'],
67 },
68 },
69 {
70 name: 'grant',
71 description: 'Add minutes to a running subagent’s current budget after reviewing its report.',
72 inputSchema: {
73 type: 'object',
74 properties: { agent_id: { type: 'string', description: 'The subagent id its report names' }, minutes },
75 required: ['agent_id', 'minutes'],
76 },
77 },
78] satisfies ToolSpec[]
79
80type Ctx = EngineInterface
81type S = {
82 units: Record<string, Unit>
83 parked: Record<string, Unit>
84 timers: Map<string, Timer>
85 pairs?: Pair[]
86 calibrationWrite?: Promise<void>
87 extensions?: Extension[]
88 extensionWrite?: Promise<void>
89 refresh?: Timer
90 envUnlimited: boolean
91 /** The condition of the user's active `/goal`, null when none runs; it alone turns unlimited on. */
92 goal: string | null
93 /** Why the last goal ended, shown until the next one starts. */
94 goalEnd?: string
95 /** A goal_status row came after the main loop's last response: the evaluator let the turn end. */
96 goalRowLast: boolean
97 awake?: Timer
98}
99
100const isUnlimited = (s: S) => s.goal !== null || s.envUnlimited
101
102const errText = (err: unknown) => (err instanceof Error ? err.message : String(err))
103
104function log($: Ctx, text: string) {
105 $.ui.log(`[time-budget] ${text}`, { to: 'debug' })
106}
107
108function toolError(text: string) {
109 return { result: text, isError: true, text }
110}
111
112async function save($: Ctx, s: S) {
113 try {
114 await $.state.set(UNITS, structuredClone(s.units))
115 await $.state.set(PARKED, structuredClone(s.parked))
116 } catch (err) {
117 log($, `state.set failed: ${errText(err)}`)
118 }
119}
120
121function goalText(s: S): string | undefined {
122 if (s.goal !== null) return `unlimited until goal: ${s.goal.length > 40 ? `${s.goal.slice(0, 39)}…` : s.goal}`
123 if (s.goalEnd) return `${s.goalEnd}; ${s.envUnlimited ? `unlimited stays on (${UNLIMITED_ENV})` : 'unlimited off'}`
124 return undefined
125}
126
127async function showStatus($: Ctx, s: S) {
128 const u = mainEntry(s)?.[1]
129 try {
130 const parts = [u ? statusText(u, await $.clock.now()) : undefined, goalText(s)].filter(Boolean)
131 $.ui.status(parts.length ? parts.join(' · ') : undefined)
132 } catch (err) {
133 log($, `ui.status failed: ${errText(err)}`)
134 }
135}
136
137function mainEntry(s: S): [string, Unit] | undefined {
138 return Object.entries(s.units).find(([, unit]) => unit.kind === 'main')
139}
140
141async function calibrationFile($: Ctx) {
142 const dir = (await $.env.get('TIME_BUDGET_DIR')) ?? `${(await $.env.get('HOME')) ?? '.'}/.local/share/claude-time-budget`
143 return `${dir}/calibration.jsonl`
144}
145
146async function extensionsFile($: Ctx) {
147 const path = await calibrationFile($)
148 return path.replace(/calibration\.jsonl$/, 'extensions.jsonl')
149}
150
151async function loadPairs($: Ctx, s: S): Promise<Pair[]> {
152 if (s.pairs) return s.pairs
153 const path = await calibrationFile($)
154 try {
155 s.pairs = (await $.fs.exists(path)) ? parsePairs((await $.fs.read(path)) as string) : []
156 } catch (err) {
157 log($, `cannot read ${path}: ${errText(err)}; calibration falls back to 1.0`)
158 s.pairs = []
159 }
160 return s.pairs
161}
162
163async function loadExtensions($: Ctx, s: S): Promise<Extension[]> {
164 if (s.extensions) return s.extensions
165 const path = await extensionsFile($)
166 try {
167 s.extensions = (await $.fs.exists(path)) ? parseExtensions((await $.fs.read(path)) as string) : []
168 } catch (err) {
169 log($, `cannot read ${path}: ${errText(err)}; extension history starts empty`)
170 s.extensions = []
171 }
172 return s.extensions
173}
174
175async function appendJsonLine($: Ctx, path: string, value: unknown) {
176 const line = JSON.stringify(value)
177 const result = await $.process.run([
178 'sh', '-c', 'mkdir -p "$(dirname "$2")" && printf "%s\\n" "$1" >> "$2"', 'sh', line, path,
179 ], { timeoutMs: 5_000 })
180 if (result.exitCode !== 0) throw new Error(`append ${path} failed (${result.exitCode}): ${result.stderr}`)
181}
182
183// One pair per unit, logged when the unit closes; `end` is when its last turn ended.
184async function logPair($: Ctx, s: S, u: Unit, end: number) {
185 if (u.estimateMin === undefined || u.budgetMin === undefined) return
186 const pair: Pair = {
187 kind: u.kind, agent_type: u.agentType ?? null, estimate_min: u.estimateMin, budget_min: u.budgetMin,
188 actual_min: Math.round(((end - u.start) / 60_000) * 100) / 100, at: Math.floor(end / 1000),
189 extended_min: u.extendedMin ?? 0, extensions: u.extensions ?? 0,
190 }
191 const write = async () => {
192 const path = await calibrationFile($)
193 try {
194 const existing = await loadPairs($, s)
195 await appendJsonLine($, path, pair)
196 s.pairs = [...existing, pair]
197 } catch (err) {
198 log($, `cannot append ${JSON.stringify(pair)} to ${path}: ${errText(err)}`)
199 }
200 }
201 const pending = s.calibrationWrite ?? Promise.resolve()
202 s.calibrationWrite = pending.catch(() => undefined).then(write)
203 await s.calibrationWrite
204}
205
206async function appendExtension($: Ctx, s: S, record: Extension) {
207 const write = async () => {
208 const path = await extensionsFile($)
209 try {
210 const existing = await loadExtensions($, s)
211 await appendJsonLine($, path, record)
212 s.extensions = [...existing, record]
213 } catch (err) {
214 log($, `cannot append ${JSON.stringify(record)} to ${path}: ${errText(err)}`)
215 }
216 }
217 const pending = s.extensionWrite ?? Promise.resolve()
218 s.extensionWrite = pending.catch(() => undefined).then(write)
219 await s.extensionWrite
220}
221
222function disarm(s: S, key: string) {
223 s.timers.get(key)?.cancel()
224 s.timers.delete(key)
225}
226
227// Moves the unit to the checkpoint the clock has reached; the timer and every tool call run it.
228async function advance($: Ctx, s: S, key: string, now: number) {
229 const u = s.units[key]
230 if (!u || u.budgetMin === undefined) return
231 const c = crossed(now - u.start, u.budgetMin)
232 let changed = false
233 if (c > u.fired) {
234 u.fired = c
235 if (c < LAST) u.reportDue = CHECKPOINTS[c - 1]!.label
236 changed = true
237 }
238 if (!changed) return
239 await save($, s)
240 if (u.kind === 'main') await showStatus($, s)
241}
242
243async function arm($: Ctx, s: S, key: string) {
244 disarm(s, key)
245 const u = s.units[key]
246 if (!u || u.budgetMin === undefined || u.fired >= LAST) return
247 const delay = Math.max(0, u.start + dueAt(u.fired, u.budgetMin) - (await $.clock.now()))
248 s.timers.set(key, $.clock.after(delay, () => {
249 void (async () => {
250 await advance($, s, key, await $.clock.now())
251 await arm($, s, key)
252 })().catch(err => log($, `checkpoint for ${key} failed: ${errText(err)}`))
253 }))
254}
255
256async function closeMain($: Ctx, s: S, now: number, key = mainEntry(s)?.[0]) {
257 if (!key) return
258 const u = s.units[key]
259 if (!u) return
260 disarm(s, key)
261 delete s.units[key]
262 // Its clm issue can be resumed by id, so the start and budget it ran under are kept for that.
263 if (u.kind === 'main') s.parked[key] = { ...u, calibrated: true }
264 if (!u.calibrated) await logPair($, s, u, u.lastEnd ?? now)
265}
266
267async function syncMainTask($: Ctx, s: S, now: number) {
268 const entry = mainEntry(s)
269 if (!entry) return
270 const [key] = entry
271 try {
272 const issue = (await $.clm.issues({ issue: key }))[0]
273 if (issue?.status === 'done' || issue?.status === 'dropped') {
274 await closeMain($, s, now, key)
275 await save($, s)
276 }
277 } catch (err) {
278 log($, `clm task status failed for ${key}: ${errText(err)}`)
279 }
280}
281
282function unreadReports(s: S, now: number): string[] {
283 const out: string[] = []
284 for (const [id, u] of Object.entries(s.units)) {
285 if (!u.unread || !u.report) continue
286 u.unread = false
287 out.push(`Subagent report (${u.agentType ?? 'subagent'} ${id}, ${mins(now - u.start)}/${Math.round(u.budgetMin ?? 0)} min):\n${reportText(u.report)}\nReview the remaining work and use ${TOOL.grant} {agent_id: "${id}", minutes} to add time when needed.`)
288 }
289 return out
290}
291
292function withFeedback<T extends ToolCallResult>(result: T, feedback: string[]): T {
293 if (!feedback.length) return result
294 if ('result' in result && typeof result.result === 'string')
295 return { ...result, result: `${result.result}\n${feedback.join('\n')}` } as T
296 return { ...result, context: [...(result.context ?? []), ...feedback] } as T
297}
298
299function withContext<T extends ToolCallResult>(result: T, context: string[]): T {
300 if (!context.length) return result
301 return { ...result, context: [...('context' in result ? result.context ?? [] : []), ...context] } as T
302}
303
304function overrunReason(unit: Unit, now: number): string | undefined {
305 if (unit.budgetMin === undefined) return undefined
306 const budget = unit.budgetMin
307 if (now - unit.start >= budget * 60_000) return `${mins(now - unit.start)} min elapsed is beyond the ${Math.round(budget)} min budget`
308 if (unit.report && unit.reportAt !== undefined) {
309 const projected = projectedMin(unit.reportAt - unit.start, unit.report)
310 if (projected > budget) return `the latest report projects ${Math.round(projected)} min against the ${Math.round(budget)} min budget`
311 }
312 return undefined
313}
314
315async function unitFeedback($: Ctx, s: S, unit: Unit | undefined, now: number, reportFiled = false): Promise<string[]> {
316 if (!unit) return []
317 let changed = false
318 const through = Math.min(unit.fired, LAST - 1)
319 const notes: string[] = []
320 if (reportFiled) {
321 if ((unit.lastNudge ?? 0) < through) {
322 unit.lastNudge = through
323 changed = true
324 }
325 } else if ((unit.lastNudge ?? 0) < through) {
326 for (let index = unit.lastNudge ?? 0; index < through; index++) {
327 const label = CHECKPOINTS[index]?.label
328 if (label) notes.push(`Checkpoint ${label} is due. Record verified work and open items with ${TOOL.report}, then continue.`)
329 }
330 unit.lastNudge = through
331 changed = true
332 }
333
334 const reason = isUnlimited(s) ? undefined : overrunReason(unit, now)
335 const interval = (unit.budgetMin ?? 0) * 60_000 / 6
336 if (reason && (unit.lastOverrunNudgeAt === undefined || now - unit.lastOverrunNudgeAt >= interval)) {
337 notes.push(`Budget feedback: ${reason}. Record extra time with ${TOOL.extend} {minutes, reason} if more time is needed, then continue.`)
338 unit.lastOverrunNudgeAt = now
339 changed = true
340 }
341 if (changed) await save($, s)
342 return notes
343}
344
345async function recordExtension(
346 $: Ctx,
347 s: S,
348 unit: Unit,
349 task: string,
350 now: number,
351 minutes: number,
352 reason: string,
353 source: Extension['source'],
354 budgetBefore: number,
355 budgetAfter: number,
356 estimateMin = unit.estimateMin ?? 0,
357) {
358 const record: Extension = {
359 at: Math.floor(now / 1000), kind: unit.kind, agent_type: unit.agentType ?? null, task,
360 scope: unit.scope ?? '', estimate_min: estimateMin, budget_before: budgetBefore, budget_after: budgetAfter,
361 minutes, elapsed_min: Math.round(((now - unit.start) / 60_000) * 100) / 100, reason, source,
362 }
363 if (source === 'extend' || source === 'grant') {
364 unit.extendedMin = (unit.extendedMin ?? 0) + minutes
365 unit.extensions = (unit.extensions ?? 0) + 1
366 }
367 await appendExtension($, s, record)
368}
369
370async function saveGoal($: Ctx, s: S) {
371 try {
372 await $.state.set(GOAL, s.goal)
373 } catch (err) {
374 log($, `state.set (goal) failed: ${errText(err)}`)
375 }
376}
377
378function stopAwakeRefresh(s: S) {
379 s.awake?.cancel()
380 s.awake = undefined
381}
382
383/** Writes the deadline `minutes` from now, or removes it at 0; the stay_awake tool and the goal's refresh share it. Throws on failure. */
384async function setAwake($: Ctx, minutes: number): Promise<number | undefined> {
385 const until = awakeUntil(await $.clock.now(), minutes)
386 const { dir, path } = awakeFile((await $.env.get('HOME')) ?? '.')
387 try {
388 if (until === undefined) {
389 const rm = await $.process.run(['rm', '-f', path], { timeoutMs: 5_000 })
390 if (rm.exitCode !== 0) throw new Error(`rm -f ${path} failed (${rm.exitCode}): ${rm.stderr}`)
391 return undefined
392 }
393 const mk = await $.process.run(['mkdir', '-p', dir], { timeoutMs: 5_000 })
394 if (mk.exitCode !== 0) throw new Error(`mkdir -p ${dir} failed (${mk.exitCode}): ${mk.stderr}`)
395 await $.fs.write(path, `${until}\n`)
396 return until
397 } catch (err) {
398 throw new Error(`could not update ${path}: ${errText(err)}`)
399 }
400}
401
402async function refreshAwake($: Ctx) {
403 try {
404 await setAwake($, GOAL_AWAKE_MIN)
405 } catch (err) {
406 log($, `stay-awake refresh failed: ${errText(err)}`)
407 }
408}
409
410async function startAwakeRefresh($: Ctx, s: S) {
411 stopAwakeRefresh(s)
412 await refreshAwake($)
413 s.awake = $.clock.every(GOAL_AWAKE_REFRESH_MS, () => { void refreshAwake($) })
414}
415
416// The goal is over however it ended: nothing keeps the run going, so neither the mode nor the Mac stays up for it.
417async function endGoal($: Ctx, s: S, reason: string) {
418 if (s.goal === null) return
419 s.goal = null
420 s.goalEnd = reason
421 s.goalRowLast = false
422 stopAwakeRefresh(s)
423 try {
424 await setAwake($, 0)
425 } catch (err) {
426 log($, `stay-awake clear failed: ${errText(err)}`)
427 }
428 await saveGoal($, s)
429 await showStatus($, s)
430 try {
431 $.ui.toast(`time-budget: ${goalText(s)}`)
432 } catch (err) {
433 log($, `ui.toast failed: ${errText(err)}`)
434 }
435}
436
437export const register: Register = (on) => {
438 const s: S = { units: {}, parked: {}, timers: new Map(), envUnlimited: false, goal: null, goalRowLast: false }
439
440 on('session.start', async ($, e, next) => {
441 const started = await next(e)
442 try {
443 const read = await $.state.get(UNITS)
444 s.units = read.value ? { ...read.value } : {}
445 const parked = await $.state.get(PARKED)
446 s.parked = parked.value ? { ...parked.value } : {}
447 s.goal = (await $.state.get(GOAL)).value ?? null
448 } catch (err) {
449 log($, `state.get failed: ${errText(err)}`)
450 }
451 s.envUnlimited = /^(1|true|on|yes)$/i.test((await $.env.get('CLAUDE_TIME_BUDGET_UNLIMITED')) ?? '')
452 // The old prompt-scoped state used the literal key `main`; it cannot be tied to a clm issue.
453 if (s.units.main?.kind === 'main') {
454 disarm(s, 'main')
455 delete s.units.main
456 await save($, s)
457 }
458 for (const t of [...TOOLS, AWAKE_DEF]) {
459 try {
460 await $.tool.register(t)
461 } catch (err) {
462 log($, `tool.register(${t.name}) failed: ${errText(err)}`)
463 }
464 }
465 for (const key of Object.keys(s.units)) await arm($, s, key)
466 if (s.goal !== null) await startAwakeRefresh($, s)
467 s.refresh?.cancel()
468 s.refresh = $.clock.every(STATUS_REFRESH_MS, () => { void showStatus($, s) })
469 await showStatus($, s)
470 return started
471 })
472
473 on('session.end', async ($, e, next) => {
474 stopAwakeRefresh(s)
475 await closeMain($, s, await $.clock.now())
476 await save($, s)
477 return next(e)
478 })
479
480 on('command.run', { command: GOAL_COMMAND }, async ($, e, next) => {
481 const args = e.args.trim()
482 const clearWord = GOAL_CLEAR_WORDS.has(args.toLowerCase())
483 const r = await next(e)
484 const out = r.text ?? ''
485 const cleared = clearWord || out.startsWith('Goal cleared') || out.startsWith('No goal set')
486 if (cleared) {
487 await endGoal($, s, `goal cleared by /${GOAL_COMMAND} ${args}`)
488 } else if (out.startsWith('Goal set: ') || (!out && args)) {
489 s.goal = out.startsWith('Goal set: ') ? out.slice('Goal set: '.length) : args
490 s.goalEnd = undefined
491 s.goalRowLast = false
492 await saveGoal($, s)
493 await startAwakeRefresh($, s)
494 }
495 return r
496 })
497
498 // The goal's evaluator writes a goal_status row after every check: one the
499 // model answers was "not met", one the turn ends on was met, failed, or a
500 // clear after an unrecoverable error. The row's payload is not on the event.
501 on('session.append', ($, e, next) => {
502 if (e.agentId === undefined && s.goal !== null) {
503 if (e.message.type === 'attachment' && e.message.name === 'goal_status') s.goalRowLast = true
504 else if (e.door === 'response') s.goalRowLast = false
505 }
506 return next(e)
507 })
508
509 on('turn.complete', async ($, e, next) => {
510 if (e.agentId === undefined && !e.isAborted && s.goal !== null && s.goalRowLast) await endGoal($, s, 'goal ended (met, failed, or cleared after an error)')
511 const r = await next(e)
512 const now = await $.clock.now()
513 if (e.agentId) {
514 const u = s.units[e.agentId]
515 if (u) {
516 disarm(s, e.agentId)
517 delete s.units[e.agentId]
518 await logPair($, s, u, now)
519 await save($, s)
520 }
521 return r
522 }
523 await syncMainTask($, s, now)
524 const u = mainEntry(s)?.[1]
525 if (!u) return r
526 u.lastEnd = now
527 await save($, s)
528 // The status line already shows the budget; a line under every answer becomes a focus-view notice row.
529 if (u.budgetMin === undefined || (!u.reportDue && now - u.start < u.budgetMin * 60_000 && !overrunReason(u, now))) return r
530 const head = `⏱ estimate ${u.estimateMin}m → ${statusText(u, now)}`
531 const line = u.report ? `${head}\n${reportText(u.report)}` : head
532 // A text other than the answer is shown beneath it; another plugin's line stays above ours.
533 return { ...r, text: r.text === e.answer ? line : `${r.text}\n${line}` }
534 })
535
536 on('agent.spawn', async ($, e, next) => {
537 const declared = budgetLine(e.prompt)
538 const r = await next(e)
539 if (!r.agentId) return r
540 const now = await $.clock.now()
541 const u: Unit = { kind: 'sub', agentType: e.subagentType, start: now, fired: 0 }
542 if (declared !== undefined) {
543 u.estimateMin = declared
544 u.budgetMin = budgetFor(declared, calibrationFactor(await loadPairs($, s)))
545 }
546 s.units[r.agentId] = u
547 await save($, s)
548 await arm($, s, r.agentId)
549 return r
550 })
551
552 on('tool.call', { tool: AWAKE_TOOL }, async ($, e) => {
553 const key = e.agentId
554 const main = key === undefined
555 const now = await $.clock.now()
556 if (main) await syncMainTask($, s, now)
557 const unitKey = key ?? mainEntry(s)?.[0]
558 const unit = unitKey ? s.units[unitKey] : undefined
559 if (unit && unitKey) await advance($, s, unitKey, now)
560 const feedback = async (result: ToolCallResult) => {
561 const notes = await unitFeedback($, s, unit, now)
562 const reports = main ? unreadReports(s, now) : []
563 if (reports.length) await save($, s)
564 return withContext(withFeedback(result, notes), reports)
565 }
566 const m = (e as unknown as Record<string, unknown>).minutes
567 if (typeof m !== 'number' || !Number.isFinite(m) || m < 0) return feedback(toolError(`Call ${AWAKE_TOOL} with minutes as a number from 0 to ${MAX_AWAKE_MIN}.`))
568 let until
569 try {
570 until = await setAwake($, m)
571 } catch (err) {
572 return feedback(toolError(`stay_awake ${errText(err)}`))
573 }
574 if (until === undefined) return feedback({ result: 'Stay-awake cleared; the Mac may sleep with the lid closed again within a minute.' })
575 const clamped = m > MAX_AWAKE_MIN ? ` (clamped from ${m} to ${MAX_AWAKE_MIN} min)` : ''
576 return feedback({ result: `Staying awake until ${new Date(until * 1000).toISOString()} (epoch ${until})${clamped}; call again before then to extend.` })
577 })
578
579 on('tool.call', async ($, e, next) => {
580 const key = e.agentId
581 const main = key === undefined
582 const now = await $.clock.now()
583 // An agent id no spawn of ours named (the engine's own forks) runs ungated.
584 if (main) await syncMainTask($, s, now)
585 let unitKey = key ?? mainEntry(s)?.[0]
586 let u = unitKey ? s.units[unitKey] : undefined
587 if (u && unitKey) await advance($, s, unitKey, now)
588 const args = e as unknown as Record<string, unknown>
589
590 if (e.tool === TOOL.estimate) {
591 const m = args.minutes
592 if (typeof m !== 'number' || !Number.isFinite(m) || !(m > 0)) return toolError(`Call ${TOOL.estimate} with minutes as a positive number, scope as one line and steps as a list.`)
593 const factor = calibrationFactor(await loadPairs($, s))
594 const baseBudget = budgetFor(m, factor)
595 const scope = typeof args.scope === 'string' ? args.scope : ''
596 if (main) {
597 const requested = args.task
598 if (requested !== undefined && (typeof requested !== 'string' || !requested.trim()))
599 return toolError(`Call ${TOOL.estimate} with task as an existing clm issue id when resuming one.`)
600 const targetKey = typeof requested === 'string' ? requested : undefined
601 let issue
602 try {
603 issue = await $.clm.track({ title: scope, status: 'doing', ...(targetKey ? { issue: targetKey } : {}) })
604 } catch (err) {
605 return toolError(`${TOOL.estimate}: ${errText(err)}`)
606 }
607 if (unitKey && unitKey !== issue.id) await closeMain($, s, now, unitKey)
608 unitKey = issue.id
609 u = s.units[unitKey]
610 const parked = s.parked[unitKey]
611 delete s.parked[unitKey]
612 // A resumed task keeps its first start and calibration estimate.
613 if (!u || u.kind !== 'main') u = s.units[unitKey] = parked
614 ? { ...parked, lastEnd: undefined }
615 : { kind: 'main', start: now, fired: 0 }
616 } else {
617 unitKey = key
618 u = s.units[unitKey] ?? (s.units[unitKey] = { kind: 'sub', start: now, fired: 0 })
619 }
620 if (!u || !unitKey) return toolError(`Could not open a time-budget unit for ${TOOL.estimate}.`)
621 const unit = u
622 const first = unit.budgetMin === undefined
623 const before = unit.budgetMin
624 const extended = unit.extendedMin ?? 0
625 const beforeBase = before === undefined ? undefined : before - extended
626 const budget = baseBudget + extended
627 if (first) unit.estimateMin = m
628 unit.budgetMin = budget
629 unit.scope = scope || undefined
630 unit.steps = Array.isArray(args.steps) ? args.steps.filter((step): step is string => typeof step === 'string') : undefined
631 if (before !== undefined && beforeBase !== undefined && baseBudget > beforeBase) {
632 await recordExtension($, s, unit, unitKey, now, budget - before,
633 `Estimate refined for ${scope || unit.scope || 'the task'}.`, 'reestimate', before, budget, m)
634 }
635 if (first) {
636 unit.fired = crossed(now - unit.start, unit.budgetMin)
637 unit.reportDue = undefined
638 unit.lastNudge = 0
639 } else {
640 await advance($, s, unitKey, now)
641 }
642 await save($, s)
643 await arm($, s, unitKey)
644 if (main) await showStatus($, s)
645 const at = CHECKPOINTS.slice(0, LAST - 1).map((c, i) => `${c.label} at ${mins(dueAt(i, unit.budgetMin!))}m`).join(', ')
646 const history = extensionSummary(await loadPairs($, s), await loadExtensions($, s))
647 const planFeedback = (unit.steps?.length ?? 0) <= 1 && m > 30 ? ' Plan feedback: split this estimate into smaller steps.' : ''
648 const result = { result: `Budget ${Math.round(unit.budgetMin)} min (estimate ${m} min × calibration ${factor.toFixed(2)}, floor 15); ${mins(now - unit.start)} min elapsed. Reports are due at ${at}; the budget ends at ${Math.round(unit.budgetMin)}m. ${history}${planFeedback} Use this budget and the planned steps to guide the work.` }
649 return withFeedback(result, await unitFeedback($, s, unit, now))
650 }
651
652 if (e.tool === TOOL.report) {
653 if (!u || !unitKey) return toolError(`Call ${TOOL.estimate} to associate a report with a unit.`)
654 if (!isReport(args)) return toolError(`Call ${TOOL.report} with done as [{item, check}], open as [{item, next}], and more_min as a number when open items need extra time.`)
655 const report: Report = { done: args.done, open: args.open, ...(args.more_min !== undefined ? { more_min: args.more_min } : {}) }
656 u.report = report
657 u.reportAt = now
658 u.reportDue = undefined
659 if (!main) u.unread = true
660 await advance($, s, unitKey, now)
661 await save($, s)
662 if (main) await showStatus($, s)
663 const projection = projectedMin(now - u.start, report)
664 const projected = Math.round(projection)
665 const budgetNow = u.budgetMin
666 const needsMore = budgetNow !== undefined && projection > budgetNow && (report.more_min ?? 0) > 0
667 if (needsMore) {
668 const reason = `Report projects ${projected} min for the remaining work: ${report.open.map(item => item.item).join(', ') || 'no open items listed'}.`
669 await recordExtension($, s, u, unitKey, now, report.more_min!, reason, 'report', budgetNow!, budgetNow!)
670 }
671 const budgetText = budgetNow === undefined ? 'no estimate yet' : `${Math.round(budgetNow)} min`
672 const extra = needsMore ? ` If you still need the requested extra time, call ${TOOL.extend} with minutes ${report.more_min} and a reason.` : ''
673 const result = { result: `Report recorded: projected ${projected} min against ${budgetText}. Continue at the same depth; verification stays part of the work.${extra}` }
674 return withFeedback(result, await unitFeedback($, s, u, now, true))
675 }
676
677 if (e.tool === TOOL.extend) {
678 const extra = args.minutes
679 const reason = typeof args.reason === 'string' ? args.reason.trim() : ''
680 if (typeof extra !== 'number' || !Number.isFinite(extra) || !(extra > 0) || !reason)
681 return toolError(`Call ${TOOL.extend} with positive minutes and a reason for the additional time.`)
682 if (!u || !unitKey || u.budgetMin === undefined)
683 return toolError(`Call ${TOOL.estimate} first so ${TOOL.extend} can add time to your unit's budget.`)
684 const before = u.budgetMin
685 const after = before + extra
686 u.budgetMin = after
687 u.lastOverrunNudgeAt = now
688 u.fired = Math.max(u.fired, crossed(now - u.start, after))
689 await recordExtension($, s, u, unitKey, now, extra, reason, 'extend', before, after)
690 await save($, s)
691 await arm($, s, unitKey)
692 if (main) await showStatus($, s)
693 const result = { result: `Added ${extra} min to this unit's budget; it is now ${Math.round(after)} min. Continue the task and report at the next checkpoint.` }
694 return withFeedback(result, await unitFeedback($, s, u, now))
695 }
696
697 if (e.tool === TOOL.grant) {
698 if (e.agentId) return toolError(`Use ${TOOL.extend} to add time to your own unit.`)
699 const id = String(args.agent_id ?? '')
700 const extra = args.minutes
701 const sub = s.units[id]
702 if (!sub || sub.kind === 'main' || sub.budgetMin === undefined) return toolError(`Call ${TOOL.grant} with the id of a running subagent that has a budget.`)
703 if (typeof extra !== 'number' || !Number.isFinite(extra) || !(extra > 0)) return toolError(`Call ${TOOL.grant} with minutes as a positive number.`)
704 const before = sub.budgetMin
705 const after = before + extra
706 sub.budgetMin = after
707 sub.lastOverrunNudgeAt = now
708 sub.fired = Math.max(sub.fired, crossed(now - sub.start, after))
709 await recordExtension($, s, sub, id, now, extra, 'Main added time after reviewing the subagent report.', 'grant', before, after)
710 await save($, s)
711 await arm($, s, id)
712 const result = { result: `Added ${extra} min to ${id}'s budget; it is now ${Math.round(after)} min.` }
713 return withFeedback(result, await unitFeedback($, s, u, now))
714 }
715
716 const result = await next(e)
717 if ('deny' in result && result.deny !== undefined) return result
718 const feedback = await unitFeedback($, s, u, now)
719 const reports = main ? unreadReports(s, now) : []
720 if (reports.length) await save($, s)
721 return withContext(result, [...feedback, ...reports])
722 })
723}
724hooks/budget.ts 165 lines1// The time budget's arithmetic and feedback formatting, with no `$`.
2//
3// WHY THE HARNESS MEASURES: a model's own time estimate runs 3-10x off, and a
4// mid-task "percent done" self-report is unreliable (arXiv 2609.08589). So the
5// wall clock lives here, and the estimate only seeds a budget after it is
6// scaled by the p90 of actual/estimate over past units, clamped to [0.25, 10].
7// A report lists verified-done and open items, never a percentage, which
8// relieves the late-task pull toward closing over verifying (arXiv 2609.00823).
9
10import type { Report, Unit } from '../types'
11
12// The user's notation; keep exactly these five.
13export const CHECKPOINTS = [
14 { label: '1/3', f: 1 / 3 },
15 { label: '1/2', f: 1 / 2 },
16 { label: '2/3', f: 2 / 3 },
17 { label: '5/6', f: 5 / 6 },
18 { label: '6/6', f: 1 },
19] as const
20export const LAST = CHECKPOINTS.length
21
22export const FLOOR_MIN = 15
23const MIN_HISTORY = 5
24export const HISTORY_WINDOW = 50
25const FACTOR_MIN = 0.25
26const FACTOR_MAX = 10
27export const TOOL = {
28 estimate: 'mcp__time-budget__estimate',
29 report: 'mcp__time-budget__report',
30 extend: 'mcp__time-budget__extend',
31 grant: 'mcp__time-budget__grant',
32} as const
33
34/** One line of calibration.jsonl, as time-budget.py wrote it. */
35export type Pair = {
36 kind: 'main' | 'sub'
37 agent_type: string | null
38 estimate_min: number
39 budget_min: number
40 actual_min: number
41 at: number
42 extended_min?: number
43 extensions?: number
44}
45
46/** One line of extensions.jsonl, recording a deliberate time-budget change or request. */
47export type Extension = {
48 at: number
49 kind: 'main' | 'sub'
50 agent_type: string | null
51 task: string
52 scope: string
53 estimate_min: number
54 budget_before: number
55 budget_after: number
56 minutes: number
57 elapsed_min: number
58 reason: string
59 source: 'extend' | 'reestimate' | 'grant' | 'report'
60}
61
62export function parsePairs(text: string): Pair[] {
63 const out: Pair[] = []
64 for (const line of text.split('\n')) {
65 if (!line.trim()) continue
66 try {
67 const p = JSON.parse(line) as unknown
68 if (p && typeof p === 'object' && !Array.isArray(p)) out.push(p as Pair)
69 } catch { /* a torn line is skipped, as the python reader did */ }
70 }
71 return out
72}
73
74export function parseExtensions(text: string): Extension[] {
75 const out: Extension[] = []
76 for (const line of text.split('\n')) {
77 if (!line.trim()) continue
78 try {
79 const value = JSON.parse(line) as unknown
80 if (value && typeof value === 'object' && !Array.isArray(value)) out.push(value as Extension)
81 } catch { /* a torn line is skipped, as the calibration reader does */ }
82 }
83 return out
84}
85
86export function extensionSummary(pairs: readonly Partial<Pair>[], extensions: readonly Partial<Extension>[]): string {
87 const recentPairs = pairs.slice(-20)
88 const needed = recentPairs.filter(pair => (pair.extended_min ?? 0) > 0)
89 const actualExtensions = extensions.filter(extension => (extension.source === 'extend' || extension.source === 'grant') && (extension.minutes ?? 0) > 0)
90 const amounts = actualExtensions.slice(-20).map(extension => extension.minutes!).sort((a, b) => a - b)
91 const middle = Math.floor(amounts.length / 2)
92 const median = amounts.length === 0 ? undefined : amounts.length % 2
93 ? amounts[middle]
94 : (amounts[middle - 1]! + amounts[middle]!) / 2
95 const reasons = extensions.slice(-3).map(extension => {
96 const reason = String(extension.reason ?? '').replace(/\s+/g, ' ').trim()
97 return reason.length > 100 ? `${reason.slice(0, 99)}…` : reason
98 }).filter(Boolean)
99 const unitHistory = recentPairs.length ? `${needed.length}/${recentPairs.length} recent units needed extra time` : 'no completed units yet'
100 const medianText = median === undefined ? 'no recorded extensions' : `median +${median} min per extension`
101 const reasonText = reasons.length ? ` Recent reasons: ${reasons.map(reason => `“${reason}”`).join('; ')}.` : ''
102 return `Extension history: ${unitHistory}; ${medianText}.${reasonText}`
103}
104
105export function calibrationFactor(pairs: readonly Partial<Pair>[]): number {
106 const ratios = pairs.slice(-HISTORY_WINDOW)
107 .filter(p => (p.estimate_min ?? 0) > 0 && (p.actual_min ?? -1) >= 0)
108 .map(p => p.actual_min! / p.estimate_min!)
109 .sort((a, b) => a - b)
110 if (ratios.length < MIN_HISTORY) return 1
111 const p90 = ratios[Math.max(0, Math.ceil(0.9 * ratios.length) - 1)]!
112 return Math.min(FACTOR_MAX, Math.max(FACTOR_MIN, p90))
113}
114
115export const budgetFor = (estimateMin: number, factor: number) => Math.max(FLOOR_MIN, estimateMin * factor)
116
117/** When checkpoint `i` (0-based) falls, in whole ms since the unit's start. Whole ms keep the timer and
118 * `crossed` in agreement: with a fractional due time, start + due rounded to the timer's ms while
119 * elapsed stayed below due, so the timer fired, found nothing crossed, and re-armed at delay 0 forever. */
120export const dueAt = (i: number, budgetMin: number) => Math.ceil(CHECKPOINTS[i]!.f * budgetMin * 60_000)
121
122/** How many checkpoints the elapsed time has passed. */
123export const crossed = (elapsedMs: number, budgetMin: number) => CHECKPOINTS.filter((_, i) => elapsedMs >= dueAt(i, budgetMin)).length
124
125/** `Budget: <N> min` as the prompt's first line: an optional estimate for a spawned subagent. */
126export const budgetLine = (prompt: string): number | undefined => {
127 const m = /^\s*Budget:\s*(\d+(?:\.\d+)?)\s*min\s*$/i.exec(prompt.split('\n', 1)[0] ?? '')
128 const n = m ? Number(m[1]) : NaN
129 return n > 0 ? n : undefined
130}
131
132/** Minutes the work will take at the pace the report shows: elapsed per done item, times the open items left. */
133export function projectedMin(elapsedMs: number, report: Report): number {
134 const elapsed = elapsedMs / 60_000
135 const rate = elapsed / Math.max(1, report.done.length)
136 return elapsed + rate * report.open.length
137}
138
139export const mins = (ms: number) => Math.round(ms / 60_000)
140
141/** The line the user reads: in the status line and beneath a main answer. */
142export function statusText(unit: Unit, now: number): string {
143 if (unit.budgetMin === undefined) return 'budget: no estimate yet'
144 const elapsed = now - unit.start
145 const base = `budget ${mins(elapsed)}/${Math.round(unit.budgetMin)}m`
146 if (elapsed > unit.budgetMin * 60_000) return `${base} · over by ${mins(elapsed - unit.budgetMin * 60_000)}m`
147 if (unit.reportDue) return `${base} · checkpoint ${unit.reportDue} report due`
148 const next = CHECKPOINTS[unit.fired]
149 return next ? `${base} · next ${next.label} at ${mins(dueAt(unit.fired, unit.budgetMin))}m` : base
150}
151
152export function reportText(r: Report): string {
153 const done = r.done.map(d => `- ${d.item} (checked: ${d.check})`).join('\n') || '- (none)'
154 const open = r.open.map(o => `- ${o.item} -> ${o.next}`).join('\n') || '- (none)'
155 return `Verified done:\n${done}\nOpen:\n${open}${r.more_min ? `\nRequests +${r.more_min} min` : ''}`
156}
157
158export function isReport(x: unknown): x is Report {
159 const r = x as Report
160 return !!r && Array.isArray(r.done) && Array.isArray(r.open)
161 && r.done.every(d => d && typeof d.item === 'string' && typeof d.check === 'string')
162 && r.open.every(o => o && typeof o.item === 'string' && typeof o.next === 'string')
163 && (r.more_min === undefined || (typeof r.more_min === 'number' && r.more_min >= 0))
164}
165hooks/awake.ts 32 lines1// stay_awake: the user's ask, "덮개 닫아도 절전 안 빠지는 걸 클로드가 툴로 연장할 수
2// 있어야 함". The tool only writes an epoch-seconds deadline; the root launchd
3// daemon `org.ranolp.claude-awake` (nix/darwin/default.nix) reads it every
4// minute and flips `pmset disablesleep`, so no sudo ever runs from here.
5
6export const AWAKE_TOOL = 'mcp__time-budget__stay_awake'
7export const MAX_AWAKE_MIN = 240
8
9/** Registered by register.ts's session.start alongside estimate/report/grant, which also serves its calls. */
10export const AWAKE_DEF = {
11 name: 'stay_awake',
12 description: `Keep the Mac awake with the lid closed for the next N minutes (max ${MAX_AWAKE_MIN} per call; 0 lets it sleep again). Call it again before the deadline to extend. A root daemon applies it within a minute, and only while the battery is at 20% or more or on AC power.`,
13 inputSchema: {
14 type: 'object',
15 properties: { minutes: { type: 'number', minimum: 0, description: `Minutes from now to stay awake, 0 to ${MAX_AWAKE_MIN}; 0 clears it` } },
16 required: ['minutes'],
17 },
18}
19
20/** The deadline, in epoch seconds, that `minutes` from `nowMs` writes; undefined clears it. */
21export function awakeUntil(nowMs: number, minutes: number): number | undefined {
22 const m = Math.min(Math.max(0, minutes), MAX_AWAKE_MIN)
23 if (m === 0) return undefined
24 return Math.floor(nowMs / 1000 + m * 60)
25}
26
27/** The deadline file the daemon reads, under `home`. */
28export function awakeFile(home: string) {
29 const dir = `${home}/.local/state/claude-awake`
30 return { dir, path: `${dir}/until` }
31}
32types/index.d.ts 44 lines1export type Report = {
2 done: { item: string; check: string }[]
3 open: { item: string; next: string }[]
4 more_min?: number
5}
6
7/** One timed unit: a main-thread clm task, or one subagent run. */
8export type Unit = {
9 kind: 'main' | 'sub'
10 agentType?: string
11 /** `$.clock.now()` milliseconds when the unit began. */
12 start: number
13 estimateMin?: number
14 /** Calibrated budget; undefined until the estimate is declared. */
15 budgetMin?: number
16 scope?: string
17 steps?: string[]
18 /** How many of CHECKPOINTS have fired. */
19 fired: number
20 /** The latest checkpoint label, shown as a report reminder. */
21 reportDue?: string
22 /** Highest checkpoint index whose reminder has reached the model. */
23 lastNudge?: number
24 /** Time of the last overrun reminder, used to space reminders by one sixth of the budget. */
25 lastOverrunNudgeAt?: number
26 report?: Report
27 reportAt?: number
28 extendedMin?: number
29 extensions?: number
30 /** A subagent report main has not been shown yet. */
31 unread?: boolean
32 /** The last time a main turn of this unit ended: the unit's actual end for calibration. */
33 lastEnd?: number
34 /** The unit's calibration pair is already logged; a resumed main task logs none again. */
35 calibrated?: boolean
36}
37
38declare module 'claude-code' {
39 interface PluginState {
40 /** `parked`: closed main units whose clm task can still be resumed, keyed by issue id. */
41 'time-budget': { units: Record<string, Unit>; parked: Record<string, Unit>; goal: string | null }
42 }
43}
44