Band above the prompt: context fill, last turn's cost, session cost and rate limits; /gauge toggles it

Claude Code mods: hooks modules that change Claude's interface and behaviour, published as the god-mods plugin marketplace.
In Claude Code:
/plugin marketplace add KZ-HQ/god-mods
/plugin install context-gauge@god-mods
Install the mods you want one by one. Restart Claude Code (a full restart; /reload-plugins does not load new mod code) for them to take effect.
| Mod | What it does |
|---|---|
| agent-spend | /spend [days] [here]: pane of subagent spend by model and agent type, with the costliest agents, from subagent transcripts |
| context-gauge | Band above the prompt: context fill, last turn's cost, session cost and rate limits; /gauge toggles it |
| long-turn-notify | macOS notification when a long turn finishes or Claude needs your input, in terminal sessions |
| merge-gate | Holds gh pr merge until CI passes on the PR head; /gate runs the project's CI steps locally |
| mod-stats | /mod-stats [days]: what each mod did, cost and saved, and how often it faulted |
| mod-faults | Passive: records any god-mod hook that fails, times out or is refused, and toasts at a mod's third fault in a session; /mod-faults. It sees only mods beneath it: put mod-faults@god-mods first in enabledPlugins (that order is the chain order) |
| next-steps | Suggests 2–3 likely next prompts after each turn; press 1/2/3 to draft one; /next off |
| prompt-shaper | Expands your shorthand and attaches git state to each prompt; adds a project-toolchain note to the system prompt |
| secret-scrubber | Masks API keys and tokens in tool output, and refuses to write them into source files |
| test-on-edit | When Claude's answer ends, runs the tests of the files it edited; failures go to Claude with your next prompt |
Installed mods nest in the order of enabledPlugins in ~/.claude/settings.json, first outermost; a plugin can't choose its place. mod-faults only sees faults in mods beneath it, so keep it first:
"enabledPlugins": {
"mod-faults@god-mods": true,
"context-gauge@god-mods": true,
...
}
Plugins installed later are appended, so they land beneath it. Reinstalling mod-faults moves it to the end again; its start-up toast and /mod-faults name any mods it can't see.
Every mod appends local JSON lines to ~/.claude/mods/metrics.jsonl; nothing leaves your machine. Rows (schema v: 2) carry t, mod, event, ver, session and project:
loaded: once per session start, with the mod's versionturn: once per turn, counting each hook's calls, e.g. {"tool.call": 3, "command.run{goal}": 1}verdictRows hold counts, kinds and lengths only, never prompt, command or tool-input text. /mod-stats summarises them. mod-faults adds a fault row per failed hook, naming the mod and event; it no longer writes ~/.claude/logs/god-mods-faults.jsonl, which can be deleted.
Each mod is a folder with .claude-plugin/plugin.json and hooks/register.tsx, plus tests in tests/.
The metrics code lives once in shared/metrics.ts and is inlined into every register.tsx between // <metrics> markers, because the engine only lets $ into functions declared in the same file. Edit the shared file, then:
shared/sync.sh # inline into every mod
shared/sync.sh --check # fail if any copy is stale
Check a mod before committing:
claude plugin validate <mod>
claude plugin test <mod>
Bump the mod's version in its plugin.json and in .claude-plugin/marketplace.json together.
hooks/register.tsx 223 lines1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, On, Register, SessionUsage } from 'claude-code'
3
4import type { GaugeSnap } from '../types'
5
6// Thresholds, in percent of the context window
7const WARN_AT = 60
8const HOT_AT = 80
9const BAR_CELLS = 10
10// Absolute size where every call re-reads enough cache to drain the 5h limit fast
11const NAG_TOKENS = 400_000
12const HIDDEN_KEY = 'hidden'
13
14const snap = atom({ plugin: 'context-gauge', key: 'snap' } as const, null)
15const lastTurn = atom({ plugin: 'context-gauge', key: 'lastTurn' } as const, null)
16const isHidden = atom({ plugin: 'context-gauge', key: 'isHidden' } as const, false)
17
18const toSnap = (u: Pick<SessionUsage, 'context' | 'rateLimits' | 'cost'>): GaugeSnap => ({
19 percent: u.context.percent ?? null,
20 tokens: u.context.tokens ?? null,
21 window: u.context.window,
22 usd: u.cost?.usd ?? null,
23 fiveHour: u.rateLimits.find(r => r.kind === 'five_hour')?.percentUsed ?? null,
24 weekly: u.rateLimits.find(r => r.kind === 'seven_day')?.percentUsed ?? null,
25})
26
27const k = (n: number) => (n >= 1000 ? `${Math.round(n / 1000)}k` : String(n))
28
29// <metrics: generated from shared/metrics.ts by shared/sync.sh>
30// Shared mod metrics (schema v2). Source of truth: ~/.claude/mods/shared/metrics.ts.
31// shared/sync.sh inlines it between the metrics markers in each mod's register.tsx (the engine only lets $
32// into functions declared in the same file). Edit here, run sync.sh, never edit an inlined copy.
33//
34// Rows appended to ~/.claude/mods/metrics.jsonl, all with { v: 2, t, mod, event, ver, session, project }:
35// loaded once per load (logLoaded, or count() in the mod's session.start hook), at session.start: proves which version of the mod is running
36// turn once per turn with activity (logTurns, or count() in the mod's turn.complete hook): { hooks: { <event>: calls } }
37// <other> outcome rows from track(), e.g. merge-gate 'verdict'
38// Privacy: never put prompt, command, tool-input or matched-secret text in a row; lengths, kinds and counts only.
39
40const APPEND = 'mkdir -p "$HOME/.claude/mods" && printf "%s\\n" "$1" >> "$HOME/.claude/mods/metrics.jsonl"'
41
42
43const ctx = { ver: '', session: '', project: '' }
44const stats = new Map<string, number>()
45let writeFailed = false
46
47const message = (err: unknown) => (err instanceof Error ? err.message : String(err)).slice(0, 300)
48
49function write($: EngineInterface, mod: string, event: string, data: Record<string, unknown>): void {
50 void (async () => {
51 const t = new Date(await $.clock.now()).toISOString()
52 if (!ctx.project) ctx.project = (await $.session.cwd()).split('/').filter(Boolean).pop() ?? ''
53 const line = JSON.stringify({ v: 2, t, mod, event, ver: ctx.ver, session: ctx.session, project: ctx.project, ...data })
54 const { exitCode, stderr } = await $.process.run(['/bin/sh', '-c', APPEND, 'mod-metrics', line], { timeoutMs: 3000 })
55 if (exitCode !== 0) throw new Error(stderr.trim() || `exit ${exitCode}`)
56 })().catch((err: unknown) => {
57 if (writeFailed) return
58 writeFailed = true
59 $.ui.toast(`${mod}: metrics write failed (${message(err)})`)
60 })
61}
62
63// An outcome row: something the mod decided or did. Fire-and-forget.
64function track($: EngineInterface, mod: string, event: string, data: Record<string, unknown> = {}): void {
65 write($, mod, event, data)
66}
67
68async function loaded($: EngineInterface): Promise<void> {
69 const mod = $.plugin.name
70 ctx.session = await $.session.id().catch(() => '')
71 ctx.project = ''
72 try {
73 const manifest = JSON.parse(await $.fs.read(`${$.plugin.root}/.claude-plugin/plugin.json`)) as { version?: string }
74 ctx.ver = manifest.version ?? ''
75 } catch {
76 ctx.ver = '?'
77 }
78 write($, mod, 'loaded', {})
79}
80
81function flush($: EngineInterface): void {
82 const mod = $.plugin.name
83 if (!stats.size) return
84 const hooks = Object.fromEntries(stats)
85 stats.clear()
86 write($, mod, 'turn', { hooks })
87}
88
89// The engine allows one hook per event per plugin, and counts them by spelling. A mod that hooks
90// session.start or turn.complete itself calls count() in that hook, which writes the row; otherwise
91// it calls the matching helper once in register.
92function logLoaded(on: On): void {
93 on('session.start', async ($, e, next) => {
94 await loaded($)
95
96 return next(e)
97 })
98}
99
100function logTurns(on: On): void {
101 on('turn.complete', async ($, e, next) => {
102 flush($)
103
104 return next(e)
105 })
106}
107
108// First statement of every hook: counts the call into this turn's row. The engine only accepts
109// function literals as hooks, so calls are counted from inside rather than by wrapping.
110// In a session.start hook it also writes the loaded row; in a turn.complete hook it writes the turn row.
111function count($: EngineInterface, event: string): void {
112 stats.set(event, (stats.get(event) ?? 0) + 1)
113 if (event === 'session.start') void loaded($)
114 if (event === 'turn.complete') flush($)
115}
116// </metrics>
117
118// <money: generated from shared/money.ts by shared/sync.sh>
119// US dollars: three decimals under $1, where cents hide the cost of a cheap call; two from $1
120function usd(n: number): string {
121 return `$${Math.abs(n) < 1 ? n.toFixed(3) : n.toFixed(2)}`
122}
123// </money>
124
125export const register: Register = on => {
126 // Baseline for the running main-loop turn
127 let turnStartUsd = 0
128 let turnStartedAt = 0
129 // One toast per crossing; re-armed when context drops back (e.g. after a compact)
130 let hasNagged = false
131
132 on('session.start', async ($, e, next) => {
133 count($, 'session.start')
134 await $.command.register({ name: 'gauge', description: 'Show or hide the context gauge above the prompt' })
135 const usage = await $.session.usage()
136 await update($, snap, () => toSnap(usage))
137 // /gauge's choice carries over to new sessions
138 if ((await $.store.get(HIDDEN_KEY)) === true) await update($, isHidden, () => true)
139
140 return next(e)
141 })
142
143 on('session.measure', async ($, e, next) => {
144 count($, 'session.measure')
145 const s = toSnap(e)
146 await update($, snap, () => s)
147 const big = (s.tokens ?? 0) >= NAG_TOKENS
148 if (big && !hasNagged) track($, 'context-gauge', 'nag', { tokens: s.tokens })
149 if (big && !hasNagged) $.ui.toast(`context-gauge: context is ${k(s.tokens ?? 0)}; every call now re-reads it. Run /compact or start a new session to save usage.`)
150 hasNagged = big
151
152 return next(e)
153 })
154
155 on('turn.start', async ($, e, next) => {
156 count($, 'turn.start')
157 turnStartUsd = (await $.session.usage()).cost?.usd ?? 0
158 turnStartedAt = await $.clock.now()
159
160 return next(e)
161 })
162
163 on('turn.complete', async ($, e, next) => {
164 count($, 'turn.complete')
165 const done = await next(e)
166 if (e.agentId !== undefined) return done
167
168 const nowUsd = (await $.session.usage()).cost?.usd ?? turnStartUsd
169 const seconds = Math.round(((await $.clock.now()) - turnStartedAt) / 1000)
170 await update($, lastTurn, () => ({ usd: Math.max(0, nowUsd - turnStartUsd), seconds }))
171
172 return done
173 })
174
175 on('command.run', { command: 'gauge' }, async $ => {
176 count($, 'command.run{gauge}')
177 const hidden = await update($, isHidden, h => !h)
178 await $.store.set(HIDDEN_KEY, hidden).catch(() => undefined)
179
180 return { text: hidden ? 'Context gauge hidden. /gauge shows it again.' : 'Context gauge shown.' }
181 })
182
183 on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
184 count($, 'ui.render')
185 const s = await read($, snap)
186 if (e.props.hasSurvey || s === null || (await read($, isHidden))) return next(e)
187
188 const turn = await read($, lastTurn)
189 const { Box, Text } = $.ui.resolve(e)
190
191 const pct = s.percent
192 const filled = pct === null ? 0 : Math.min(BAR_CELLS, Math.round((pct / 100) * BAR_CELLS))
193 const bar = '▰'.repeat(filled) + '▱'.repeat(BAR_CELLS - filled)
194 const isBig = (s.tokens ?? 0) >= NAG_TOKENS
195 const color = pct === null ? undefined : pct >= HOT_AT || isBig ? 'red' : pct >= WARN_AT ? 'yellow' : 'green'
196
197 const parts: string[] = []
198 parts.push(pct === null ? 'ctx —' : `${pct}% · ${k(s.tokens ?? 0)}/${k(s.window)}`)
199 if (isBig) parts.push('over 400k: /compact to save usage')
200 if (turn) parts.push(`last turn ${usd(turn.usd)} · ${turn.seconds}s`)
201 if (s.usd !== null) parts.push(`session ${usd(s.usd)}`)
202 if (s.fiveHour !== null) parts.push(`5h ${Math.round(s.fiveHour)}%`)
203 if (s.weekly !== null) parts.push(`7d ${Math.round(s.weekly)}%`)
204
205 const mine = (
206 <Box flexDirection="row" gap={1} width={Math.max(20, e.props.bodyColumns)}>
207 <Text color={color}>{bar}</Text>
208 <Text dimColor={!isBig} color={isBig ? 'red' : undefined} wrap="truncate-end">
209 {parts.join(' · ')}
210 </Text>
211 </Box>
212 )
213 const below = await next(e)
214
215 return (
216 <Box flexDirection="column">
217 {mine}
218 {below}
219 </Box>
220 )
221 })
222}
223types/index.d.ts 17 lines1export type GaugeSnap = {
2 percent: number | null
3 tokens: number | null
4 window: number
5 usd: number | null
6 fiveHour: number | null
7 weekly: number | null
8}
9
10export type TurnCost = { usd: number; seconds: number }
11
12declare module 'claude-code' {
13 interface PluginState {
14 'context-gauge': { snap: GaugeSnap | null; lastTurn: TurnCost | null; isHidden: boolean }
15 }
16}
17