Read-only harness model, issue, budget, context, and nightly status

Claude Code 2.1.289 mod showing read-only harness status in the status line, AbovePrompt band, and /hstatus.
$.session.model() (shortened, e.g. Opus 5.5) first in the status line and as 모델 … in /hstatus; refreshed at session start and after each main turn, so /model switches appear after the next turn..claude/issue-db/registry.json by walking up from the session working directory (nearest wins, stopping at $HOME or /) on session start and after main turns when its modification time changes. Shows the latest IN_PROGRESS issue and count.opus_budget_state.daily.cost_usd and daily.limit_usd, written by opus-budget-check.sh (estimated per-dispatch cost of opus/fable subagents, limit = Hard Cap). Until that hook records once, both appear as —. The recorded budget date appears in the detailed view to avoid presenting an old daily record as today's spending.$.session.usage().context.percent when available.~/Library/Logs/insuregraph-night/ on session start and every 30 minutes. An unavailable log is omitted.df -k /Volumes/E_SSD at session start, every five minutes, and after main turns (skipping a lookup within 60 seconds of the last successful one). The status line begins with a 10-cell free-space bar; /hstatus and the AbovePrompt band use a 20-cell bar and show free and total capacity. The band appears whenever free space is below 20%, even without an active issue. It is green at 20% or more, yellow below 20%, and red below 10%. An unavailable or unmounted disk appears as E_SSD 없음.$.state.Unknown or unreadable values appear as —; no information is written back to either source.
hooks/register.tsx 251 lines1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, Register } from 'claude-code'
3import type { HarnessBudget, HarnessDisk, HarnessIssue, HarnessNight, HarnessSnapshot } from '../types/index'
4
5const snapshot = atom({ plugin: 'harness-status', key: 'snapshot' } as const, {
6 issueCount: null, latestIssue: null, budget: null, registryMtimeMs: null,
7 night: null, contextPercent: null, disk: null, diskNotifiedThresholds: [],
8 model: null, registryPath: null,
9} as HarnessSnapshot)
10
11export function parseDf(raw: string): Pick<HarnessDisk, 'totalKb' | 'availableKb' | 'percent'> | null {
12 const columns = raw.trim().split(/\r?\n/).at(-1)?.trim().split(/\s+/) ?? []
13 const totalKb = Number(columns[1])
14 const availableKb = Number(columns[3])
15 if (columns.length < 6 || columns.at(-1) !== '/Volumes/E_SSD' || !Number.isSafeInteger(totalKb) || totalKb <= 0 ||
16 !Number.isSafeInteger(availableKb) || availableKb < 0 || availableKb > totalKb) return null
17 return { totalKb, availableKb, percent: availableKb / totalKb * 100 }
18}
19
20export function diskBar(percent: number, width: number): string {
21 const filled = Math.max(0, Math.min(width, Math.round(percent / 100 * width)))
22 return '▓'.repeat(filled) + '░'.repeat(width - filled)
23}
24
25function size(kb: number): string {
26 const gb = kb / 1024 / 1024
27 return gb >= 1024 ? `${(gb / 1024).toFixed(1)}T` : `${Math.round(gb)}G`
28}
29
30function diskText(disk: HarnessDisk | null, width: number, detailed = false): string {
31 if (!disk) return 'E_SSD 없음'
32 const pct = Math.round(disk.percent)
33 return `E_SSD ${diskBar(disk.percent, width)} ${pct}% 남음 ` +
34 (detailed ? `(여유 ${size(disk.availableKb)} / 전체 ${size(disk.totalKb)})` : `(${size(disk.availableKb)})`)
35}
36
37export function crossedDiskThresholds(previous: number | null, current: number, notified: number[]): number[] {
38 return [20, 10, 5].filter(level => previous !== null && previous >= level && current < level && !notified.includes(level))
39}
40
41export function notifyDiskThresholds(previous: number | null, current: number, notified: number[], toast: (text: string) => void): number[] {
42 const crossed = crossedDiskThresholds(previous, current, notified)
43 for (const level of crossed) toast(`E_SSD 여유 ${Math.round(current)}% — ${level}% 경계 아래로 하락`)
44 return [...notified, ...crossed]
45}
46
47async function refreshDisk($: EngineInterface): Promise<void> {
48 const old = await read($, snapshot)
49 const now = await $.clock.now()
50 if (old.disk && now - old.disk.checkedAt < 60_000) return
51 let disk: HarnessDisk | null = null
52 try {
53 const result = await $.process.run(['df', '-k', '/Volumes/E_SSD'], { timeoutMs: 3000 })
54 const parsed = result.exitCode === 0 ? parseDf(result.stdout) : null
55 if (parsed) disk = { ...parsed, checkedAt: now }
56 } catch { /* Unmounted or unavailable disk. */ }
57 const crossed = disk ? crossedDiskThresholds(old.disk?.percent ?? null, disk.percent, old.diskNotifiedThresholds ?? []) : []
58 await update($, snapshot, current => ({ ...current, disk,
59 diskNotifiedThresholds: [...(current.diskNotifiedThresholds ?? []), ...crossed] }))
60 if (disk) notifyDiskThresholds(old.disk?.percent ?? null, disk.percent, old.diskNotifiedThresholds ?? [], text => $.ui.toast(text))
61}
62
63function object(value: unknown): Record<string, unknown> | null {
64 return value !== null && typeof value === 'object' && !Array.isArray(value)
65 ? value as Record<string, unknown> : null
66}
67
68function finite(value: unknown): number | null {
69 return typeof value === 'number' && Number.isFinite(value) ? value : null
70}
71
72export function parseRegistry(raw: string): Pick<HarnessSnapshot, 'issueCount' | 'latestIssue' | 'budget'> {
73 const data = object(JSON.parse(raw))
74 if (!data) return { issueCount: null, latestIssue: null, budget: null }
75 const issues = Array.isArray(data.issues) ? data.issues : null
76 const active: HarnessIssue[] = (issues ?? []).flatMap(value => {
77 const issue = object(value)
78 if (!issue || issue.status !== 'IN_PROGRESS' || typeof issue.id !== 'string') return []
79 return [{ id: issue.id, title: typeof issue.title === 'string' ? issue.title : '—',
80 updatedAt: typeof issue.updated_at === 'string' ? issue.updated_at :
81 typeof issue.created_at === 'string' ? issue.created_at : '' }]
82 })
83 active.sort((a, b) => b.updatedAt.localeCompare(a.updatedAt))
84 const budgetState = object(data.opus_budget_state)
85 const daily = object(budgetState?.daily)
86 const budget: HarnessBudget | null = budgetState ? {
87 date: typeof daily?.date === 'string' ? daily.date : null,
88 costUsd: finite(daily?.cost_usd),
89 limitUsd: finite(daily?.limit_usd),
90 } : null
91 return { issueCount: issues ? active.length : null, latestIssue: active[0] ?? null, budget }
92}
93
94const REGISTRY_REL = '.claude/issue-db/registry.json'
95
96/** Directories from `start` up to (and including) `home`, or the filesystem root when `start` is outside home. */
97export function ancestorDirs(start: string, home: string | null): string[] {
98 const trim = (p: string) => p.length > 1 ? p.replace(/\/+$/, '') : p
99 let dir = trim(start)
100 const stop = home ? trim(home) : null
101 const dirs: string[] = []
102 while (dir) {
103 dirs.push(dir)
104 if (dir === '/' || dir === stop) break
105 const cut = dir.lastIndexOf('/')
106 dir = cut <= 0 ? '/' : dir.slice(0, cut)
107 }
108 return dirs
109}
110
111/** First `<dir>/.claude/issue-db/registry.json` that is a file, walking up from `start`. */
112export async function findRegistry(start: string, home: string | null,
113 stat: (path: string) => Promise<{ kind: string; mtimeMs: number }>): Promise<{ path: string; mtimeMs: number } | null> {
114 for (const dir of ancestorDirs(start, home)) {
115 const path = `${dir === '/' ? '' : dir}/${REGISTRY_REL}`
116 try {
117 const s = await stat(path)
118 if (s.kind === 'file') return { path, mtimeMs: s.mtimeMs }
119 } catch { /* not here; keep walking up */ }
120 }
121 return null
122}
123
124async function refreshRegistry($: EngineInterface, force = false): Promise<void> {
125 try {
126 const home = (await $.env.get('HOME')) ?? null
127 const found = await findRegistry(await $.session.cwd(), home, path => $.fs.stat(path))
128 if (!found) throw new Error('no registry')
129 const old = await read($, snapshot)
130 if (!force && found.mtimeMs === old.registryMtimeMs && found.path === old.registryPath) return
131 const parsed = parseRegistry(await $.fs.read(found.path))
132 await update($, snapshot, old => ({ ...old, ...parsed, registryMtimeMs: found.mtimeMs, registryPath: found.path }))
133 } catch {
134 await update($, snapshot, old => ({ ...old, issueCount: null, latestIssue: null,
135 budget: null, registryMtimeMs: null, registryPath: null }))
136 }
137}
138
139/** `claude-opus-5-5` / `claude-fable-5-1[1m]` / `opus` → `Opus 5.5` / `Fable 5.1` / `Opus`; unknown spellings pass through. */
140export function shortModelName(raw: string | null | undefined): string | null {
141 const text = (raw ?? '').trim()
142 if (!text) return null
143 const cap = (f: string | undefined) => f ? f.charAt(0).toUpperCase() + f.slice(1).toLowerCase() : ''
144 const m = text.match(/(opus|sonnet|haiku|fable)[-\s]?(\d{1,2})(?!\d)(?:[-.](\d{1,2})(?!\d))?/i)
145 if (m) return `${cap(m[1])} ${m[2]}${m[3] ? `.${m[3]}` : ''}`
146 const legacy = text.match(/(\d{1,2})[-.](\d{1,2})-(opus|sonnet|haiku)/i)
147 if (legacy) return `${cap(legacy[3])} ${legacy[1]}.${legacy[2]}`
148 const family = text.match(/^(opus|sonnet|haiku|fable)$/i)
149 if (family) return cap(family[1])
150 return text.replace(/\[[^\]]*\]$/, '')
151}
152
153async function refreshModel($: EngineInterface): Promise<void> {
154 let model: string | null = null
155 try { model = shortModelName(await $.session.model()) } catch { /* unavailable */ }
156 await update($, snapshot, old => ({ ...old, model }))
157}
158
159export function parseNight(date: string, raw: string): HarnessNight | null {
160 const last = raw.trimEnd().split(/\r?\n/).at(-1) ?? ''
161 const time = last.match(/\b(\d{2}:\d{2})(?::\d{2})?\b/)?.[1]
162 const result = /실패|에러|오류|failed|error/i.test(last) ? '실패'
163 : /완료|성공|completed|success/i.test(last) ? '완료'
164 : /진행|실행 중|시작|running|started/i.test(last) ? '진행' : null
165 return time && result ? { date, time, result } : null
166}
167
168async function refreshNight($: EngineInterface): Promise<void> {
169 let night: HarnessNight | null = null
170 try {
171 const home = await $.env.get('HOME')
172 if (home) {
173 const dir = `${home}/Library/Logs/insuregraph-night`
174 const dates = (await $.fs.list(dir)).filter(entry => entry.kind === 'file' &&
175 /^\d{4}-\d{2}-\d{2}\.log$/.test(entry.name)).sort((a, b) => b.name.localeCompare(a.name))
176 if (dates[0]) night = parseNight(dates[0].name.slice(0, 10), await $.fs.read(`${dir}/${dates[0].name}`))
177 }
178 } catch { /* An absent or unreadable log has no status. */ }
179 await update($, snapshot, old => ({ ...old, night }))
180}
181
182async function refreshContext($: EngineInterface): Promise<void> {
183 let contextPercent: number | null = null
184 try { contextPercent = finite((await $.session.usage()).context.percent) } catch { /* unavailable */ }
185 await update($, snapshot, old => ({ ...old, contextPercent }))
186}
187
188function money(value: number | null): string { return value === null ? '—' : `$${value}` }
189function budgetText(value: HarnessBudget | null): string {
190 return `예산${value?.date ? `(${value.date})` : ''} ${money(value?.costUsd ?? null)}/${money(value?.limitUsd ?? null)}`
191}
192export function shortText(s: HarnessSnapshot): string {
193 const parts = [...(s.model ? [s.model] : []), diskText(s.disk, 10), s.latestIssue?.id ?? '이슈 —', budgetText(s.budget)]
194 if (s.contextPercent !== null) parts.push(`컨텍스트 ${Math.round(s.contextPercent)}%`)
195 if (s.night) parts.push(`야간 ${s.night.time} ${s.night.result}`)
196 return parts.join(' · ')
197}
198export function detailText(s: HarnessSnapshot): string {
199 const issue = s.latestIssue
200 ? `${s.latestIssue.id} ${s.latestIssue.title.slice(0, 20)}${s.issueCount !== null && s.issueCount > 1 ? ` (진행 중 ${s.issueCount}건)` : ''}`
201 : s.issueCount === 0 ? '진행 중 이슈 없음' : '진행 중 이슈 —'
202 const parts = [...(s.model ? [`모델 ${s.model}`] : []), diskText(s.disk, 20, true), issue, budgetText(s.budget)]
203 if (s.contextPercent !== null) parts.push(`컨텍스트 ${Math.round(s.contextPercent)}%`)
204 if (s.night) parts.push(`야간 ${s.night.date} ${s.night.time} ${s.night.result}`)
205 return parts.join(' · ')
206}
207
208export const register: Register = on => {
209 on('session.start', async ($, e, next) => {
210 await $.command.register({ name: 'hstatus', description: '하네스 상태 표시' })
211 await refreshModel($)
212 await refreshRegistry($, true)
213 await refreshNight($)
214 await refreshContext($)
215 await refreshDisk($)
216 $.ui.status(shortText(await read($, snapshot)))
217 $.clock.every(30 * 60 * 1000, async () => {
218 await refreshNight($)
219 $.ui.status(shortText(await read($, snapshot)))
220 })
221 $.clock.every(5 * 60 * 1000, async () => {
222 await refreshDisk($)
223 $.ui.status(shortText(await read($, snapshot)))
224 })
225 return next(e)
226 })
227
228 on('turn.complete', async ($, e, next) => {
229 if (e.agentId === undefined) {
230 await refreshModel($)
231 await refreshRegistry($)
232 await refreshContext($)
233 await refreshDisk($)
234 $.ui.status(shortText(await read($, snapshot)))
235 }
236 return next(e)
237 })
238
239 on('command.run', { command: 'hstatus' }, async $ => {
240 return { text: detailText(await read($, snapshot)) }
241 })
242
243 on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
244 const s = await read($, snapshot)
245 if (e.props.hasSurvey || (!s.latestIssue && (s.disk?.percent ?? 100) >= 20)) return next(e)
246 const { Box, Text } = $.ui.resolve(e)
247 const color = !s.disk ? undefined : s.disk.percent < 10 ? 'red' : s.disk.percent < 20 ? 'yellow' : 'green'
248 return <Box><Text color={color} wrap="truncate-end">{detailText(s)}</Text></Box>
249 })
250}
251types/index.d.ts 25 lines1export type HarnessIssue = { id: string; title: string; updatedAt: string }
2export type HarnessBudget = { date: string | null; costUsd: number | null; limitUsd: number | null }
3export type HarnessNight = { date: string; time: string; result: '완료' | '실패' | '진행' }
4export type HarnessDisk = { totalKb: number; availableKb: number; percent: number; checkedAt: number }
5export type HarnessSnapshot = {
6 issueCount: number | null
7 latestIssue: HarnessIssue | null
8 budget: HarnessBudget | null
9 registryMtimeMs: number | null
10 night: HarnessNight | null
11 contextPercent: number | null
12 disk: HarnessDisk | null
13 diskNotifiedThresholds: number[]
14 /** Main-loop model as `$.session.model()` returns it; null when unavailable. */
15 model?: string | null
16 /** registry.json path found by walking up from cwd; null when none. */
17 registryPath?: string | null
18}
19
20declare module 'claude-code' {
21 interface PluginState {
22 'harness-status': { snapshot: HarnessSnapshot }
23 }
24}
25