Claude Code mod: context/token band, escalation signals and per-turn effort log.

Mod per Claude Code (>= 2.1.287): banda sopra il prompt con contesto e token, segnale di escalation dopo turni "faticosi" consecutivi, registro per turno con /effort-log. Solo osservazione, non blocca nulla.
npm test, ng test, mvn, gradle, pytest, go test, cargo, dotnet, make, tsc…) che contiene un fallimento (FAIL, N failing, BUILD FAILURE…) anche se l'exit code è 0. I comandi dei sub-agent non contano.ctx N% | last turn N tok | struggling xN/soglia sopra il prompt./effort-log: ultimi 50 turni; il registro è salvato nello store del plugin e resta tra una sessione e l'altra. /effort-summary: riepilogo in una riga (turni, turni faticosi, motivo più frequente, picco di contesto).Edit fallito e lo stesso comando che fallisce due volte nello stesso turno (repeated_error) contano come fatica; il toast riporta l'ultimo comando fallito.0 failed / Failures: 0 non contano e si guarda solo la coda dell'output. Riconosciuti anche Surefire, Karma, Playwright, Cypress e nx.| Opzione | Default | Descrizione |
|---|---|---|
threshold | 3 | Turni faticosi consecutivi prima del toast (1–20). Si cambia dal menu /config del plugin. |
contextThreshold | 80 | Toast una tantum quando il contesto raggiunge questa percentuale; 0 lo disattiva. |
/plugin marketplace add stefanochieli/claude-effort-guard
/plugin install effort-guard@effort-guard
/reload-plugins
claude --plugin-dir .
claude plugin validate .
claude plugin test .
Struttura: .claude-plugin/ (manifest + marketplace), hooks/ (modulo), types/ (stato), tests/. Flusso di lavoro e release: vedi CONTRIBUTING.md.
protect-main.json (richiede il check checks, prodotto da ci.yml)RELEASE_PLEASE_TOKEN (PAT o GitHub App); senza, la CI sulla PR di release viene lanciata da release-please.yml con workflow_dispatchmain, con la versione minima di Claude Code (checks, richiesto dal ruleset); il job compat-latest prova anche l'ultima versione senza bloccare.feat:, fix:), apre la release PR, aggiorna versione in plugin.json e marketplace.json, CHANGELOG, tag e GitHub Release al merge.hooks/module.mjs 219 lines1import { atom, read, update } from 'claude-code'
2import { looksLikeTestFailure } from './detect.mjs'
3
4const DEFAULT_THRESHOLD = 3
5const DEFAULT_CONTEXT_THRESHOLD = 80
6const LOG_LIMIT = 500
7const LOG_KEY = 'log'
8
9const metrics = atom(
10 { plugin: 'effort-guard', key: 'metrics' },
11 { contextPercent: null, lastTurnTokens: null, consecutiveStruggles: 0, lastStruggleCommand: null },
12)
13const turn = atom({ plugin: 'effort-guard', key: 'turn' }, { struggled: false, reason: null, command: null })
14
15// Marks the current turn as struggling. The same command failing twice in a
16// turn is a loop, which is worth telling apart from two different failures.
17async function markStruggle($, reason, command) {
18 const current = await read($, turn)
19 const repeated = current.struggled && !!command && current.command === command
20
21 await update($, turn, () => ({ struggled: true, reason: repeated ? 'repeated_error' : reason, command: command ?? current.command }))
22}
23
24export function register(on, options) {
25 const threshold = Math.max(1, Math.floor(Number(options?.threshold)) || DEFAULT_THRESHOLD)
26 // 0 switches the context warning off.
27 const rawContext = Number(options?.contextThreshold)
28 const contextThreshold = Number.isFinite(rawContext) && options?.contextThreshold !== undefined
29 ? Math.min(100, Math.max(0, Math.floor(rawContext)))
30 : DEFAULT_CONTEXT_THRESHOLD
31
32 on('session.start', async ($, e, next) => {
33 await $.command.register({
34 name: 'effort-log',
35 description: 'Print the effort-guard per-turn context/struggle log',
36 })
37 await $.command.register({
38 name: 'effort-summary',
39 description: 'Print a one-line effort-guard summary of the logged turns',
40 })
41
42 return next(e)
43 })
44
45 on('prompt.submit', async ($, e, next) => {
46 await update($, turn, () => ({ struggled: false, reason: null, command: null }))
47
48 return next(e)
49 })
50
51 on('tool.call', { tool: 'Bash' }, async ($, e, next) => {
52 const ran = await next(e)
53
54 // A subagent's commands are not the user-visible turn's struggle.
55 if (e.agentId) {
56 return ran
57 }
58
59 if (ran.isError) {
60 await markStruggle($, 'bash_error', e.command)
61 } else if (looksLikeTestFailure(e.command, ran.text)) {
62 await markStruggle($, 'test_failure_pattern', e.command)
63 }
64
65 return ran
66 })
67
68 // A failed edit (e.g. old_string not found) means the model is working from
69 // a stale picture of the file.
70 on('tool.call', { tool: 'Edit' }, async ($, e, next) => {
71 const ran = await next(e)
72
73 if (!e.agentId && ran.isError) {
74 await markStruggle($, 'edit_error', null)
75 }
76
77 return ran
78 })
79
80 on('turn.complete', async ($, e, next) => {
81 if (e.agentId) {
82 // Subagent turn: don't count it toward the user-visible streak.
83 return next(e)
84 }
85
86 const usage = e.usage
87 const lastTurnTokens = usage
88 ? usage.input_tokens + usage.output_tokens + usage.cache_read_input_tokens + usage.cache_creation_input_tokens
89 : null
90
91 // Struggle tracking and the toast must not depend on context-usage
92 // reporting succeeding, so a failure here degrades to an unknown percent
93 // instead of skipping the rest of the hook.
94 let contextPercent = null
95 try {
96 const sessionUsage = await $.session.usage()
97 contextPercent = sessionUsage.context.percent ?? null
98 } catch {}
99
100 const { struggled, reason, command } = await read($, turn)
101 const prev = await read($, metrics)
102 const consecutiveStruggles = struggled ? prev.consecutiveStruggles + 1 : 0
103
104 await update($, metrics, () => ({
105 contextPercent,
106 lastTurnTokens,
107 consecutiveStruggles,
108 lastStruggleCommand: struggled ? (command ?? prev.lastStruggleCommand) : null,
109 }))
110 await update($, turn, () => ({ struggled: false, reason: null, command: null }))
111
112 const entry = {
113 ts: new Date().toISOString(),
114 contextPercent,
115 lastTurnTokens,
116 struggled,
117 reason,
118 consecutiveStruggles,
119 }
120
121 // The log outlives the session. A store failure must not cost the toast.
122 try {
123 const stored = await $.store.get(LOG_KEY)
124 const list = Array.isArray(stored) ? stored : []
125 await $.store.set(LOG_KEY, [...list, entry].slice(-LOG_LIMIT))
126 } catch {}
127
128 // Once per streak: fires when the streak reaches the threshold, and again
129 // only after a clean turn has reset it. Derived from $.state, so a hot
130 // reload cannot make it fire twice.
131 if (consecutiveStruggles === threshold) {
132 $.ui.toast(
133 `effort-guard: ${consecutiveStruggles} struggling turns in a row (failed commands/tests)` +
134 `${command ? `, last: ${command.slice(0, 60)}` : ''}. ` +
135 `Consider switching to a stronger model or raising effort one level.`,
136 )
137 }
138
139 // Fires once, when the context first crosses the limit.
140 if (
141 contextThreshold > 0 &&
142 contextPercent !== null &&
143 contextPercent >= contextThreshold &&
144 (prev.contextPercent ?? 0) < contextThreshold
145 ) {
146 $.ui.toast(`effort-guard: context at ${contextPercent}%. Consider /compact or starting a fresh session.`)
147 }
148
149 return next(e)
150 })
151
152 on('command.run', { command: 'effort-log' }, async $ => {
153 let list = []
154 try {
155 const stored = await $.store.get(LOG_KEY)
156 list = Array.isArray(stored) ? stored : []
157 } catch {}
158
159 if (list.length === 0) {
160 return { text: 'effort-guard: no turns logged yet.' }
161 }
162
163 const lines = list.slice(-50).map(e => {
164 const flag = e.struggled ? `STRUGGLE(${e.reason})` : 'ok'
165
166 return `${e.ts} ctx=${e.contextPercent ?? '?'}% tok=${e.lastTurnTokens ?? '?'} streak=${e.consecutiveStruggles} ${flag}`
167 })
168
169 return { text: lines.join('\n') }
170 })
171
172 on('command.run', { command: 'effort-summary' }, async $ => {
173 let list = []
174 try {
175 const stored = await $.store.get(LOG_KEY)
176 list = Array.isArray(stored) ? stored : []
177 } catch {}
178
179 if (list.length === 0) {
180 return { text: 'effort-guard: no turns logged yet.' }
181 }
182
183 const struggled = list.filter(e => e.struggled)
184 const reasons = {}
185 for (const e of struggled) {
186 reasons[e.reason] = (reasons[e.reason] ?? 0) + 1
187 }
188 const top = Object.entries(reasons).sort((a, b) => b[1] - a[1])[0]
189 const peak = Math.max(0, ...list.map(e => e.contextPercent ?? 0))
190
191 return {
192 text:
193 `effort-guard: ${list.length} turns, ${struggled.length} struggling` +
194 `${top ? ` (most common: ${top[0]})` : ''}, peak context ${peak}%.`,
195 }
196 })
197
198 on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
199 const m = await read($, metrics)
200
201 if (m.contextPercent === null && m.lastTurnTokens === null && m.consecutiveStruggles === 0) {
202 return next(e)
203 }
204
205 const { Box, Text } = $.ui.resolve(e)
206 const struggleText = m.consecutiveStruggles > 0 ? ` | struggling x${m.consecutiveStruggles}/${threshold}` : ''
207
208 return h(
209 Box,
210 null,
211 h(
212 Text,
213 { dimColor: true },
214 `ctx ${m.contextPercent ?? '?'}% | last turn ${m.lastTurnTokens ?? '?'} tok${struggleText}`,
215 ),
216 )
217 })
218}
219hooks/detect.mjs 48 lines1// Commands whose output is worth scanning for swallowed test/build failures.
2// Anything else (cat, grep, git log...) can print "FAIL" without meaning it.
3const TEST_COMMAND = new RegExp(
4 [
5 String.raw`(?:^|[\s;&|(])(?:\./)?(?:mvnw?|gradlew?|jest|vitest|karma|playwright|cypress|nx|pytest|tox|tsc|make)(?=\s|$)`,
6 String.raw`\b(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?(?:test|check|build|lint|e2e)\b`,
7 String.raw`\bng\s+(?:test|build|lint|e2e)\b`,
8 String.raw`\b(?:go|cargo|dotnet)\s+(?:test|build)\b`,
9 String.raw`\bclaude\s+plugin\s+test\b`,
10 ].join('|'),
11)
12
13// Text a runner prints when it failed but the exit code was swallowed
14// (`npm test || true`) or the failure is reported without a non-zero exit.
15const FAILURE_PATTERNS = [
16 /\bFAIL(ED|URE)?\b/,
17 /\d+\s+failing/i,
18 /tests?:\s*\d+\s*failed/i,
19 /assertionerror/i,
20 /BUILD FAILURE/i,
21 /\[ERROR\]\s+(?:Tests run:|Failed to execute goal)/,
22 /Tests run:.*(?:Failures|Errors):\s*[1-9]/,
23 /Executed \d+ of \d+.*\bFAILED\b/,
24 /[✗✖]/,
25]
26
27// Summary lines that name a failure counter but report none: "0 failed",
28// "Failures: 0", "BUILD FAILURE" is not among them.
29const ZERO_COUNT = /\b0\s+(?:failed|failing|failures?)\b|\b(?:failed|failures?):\s*0\b/gi
30
31// Only the tail of the output holds the runner's summary; scanning all of it
32// would flag a test that merely prints "FAIL" in its own log lines.
33const TAIL_CHARS = 4000
34
35export function isTestCommand(command) {
36 return typeof command === 'string' && TEST_COMMAND.test(command)
37}
38
39export function looksLikeTestFailure(command, text) {
40 if (!isTestCommand(command) || !text) {
41 return false
42 }
43
44 const tail = text.slice(-TAIL_CHARS).replace(ZERO_COUNT, '')
45
46 return FAILURE_PATTERNS.some(re => re.test(tail))
47}
48types/index.d.ts 28 lines1export type Metrics = {
2 contextPercent: number | null
3 lastTurnTokens: number | null
4 consecutiveStruggles: number
5 lastStruggleCommand: string | null
6}
7
8export type Turn = {
9 struggled: boolean
10 reason: 'bash_error' | 'test_failure_pattern' | 'repeated_error' | 'edit_error' | null
11 command: string | null
12}
13
14export type LogEntry = {
15 ts: string
16 contextPercent: number | null
17 lastTurnTokens: number | null
18 struggled: boolean
19 reason: Turn['reason']
20 consecutiveStruggles: number
21}
22
23declare module 'claude-code' {
24 interface PluginState {
25 'effort-guard': { metrics: Metrics; turn: Turn }
26 }
27}
28