Sidebar that analyzes how you use Claude Code: live warnings, cost, tips, standup and CLAUDE.md improvements. English and Japanese.

A Claude Code mod that opens a sidebar analyzing how you use Claude Code, in the spirit of GitHub Copilot CLI's /chronicle.
| Tab | What it shows |
|---|---|
| Now | Live warnings for this session: context fill, token burn pace, plan-limit windows, code changed without review, commands with outside effects |
| Cost | Late compactions, the few sessions that dominate cache reads, model mix, credit errors, very long turns |
| Tips | Up to 5 Claude Code features you underuse, with the evidence and a docs link |
| Standup | Work per project over the last 1 / 3 / 7 days: titles, recaps, git commits, files |
| Improve | Gaps between how you work and what helps (review after edits, note searches, repeated corrections, tool errors). In the open repository, commands that keep failing and corrections that keep coming back, with the transcripts behind them, and a request to Claude to draft CLAUDE.md lines |
| Settings | Every option below, changed in place (pickers and text fields) |
Details opens a finding inside the sidebar: the breakdown behind it, the recommended action, a prompt you can copy, and an optional AI explanation. Nothing is posted to your conversation unless you press Ask Claude to apply.
claude -p) /chronicle answers in text.PATH as python3 or python (standard library only; nothing is installed).allowManagedModsOnly and related managed settings). If /chronicle does not exist after installing, ask your administrator.claude plugin marketplace add m-aoki1348125/ccmod-chronicle
claude plugin install ccmod-chronicle@ccmod-chronicle
Or try it for one session from a clone: claude --plugin-dir ./ccmod-chronicle.
Before installing any mod, you can list what it does without running it: claude plugin validate ./ccmod-chronicle (see SECURITY.md).
/chronicle [now|cost|tips|standup|improve|settings|refresh|purge]
Keys: 1–6 tabs, r re-index, v show / hide charts, a AI summary, Esc closes. In a detail view: b back, c copy prompt, g generate / regenerate the explanation.
/chronicle purge deletes everything this mod stored (see PRIVACY.md).
Two views (paneStyle): simple, the list alone, is the default. rich adds a row of figures and charts above it (context and plan-limit meters on Now; output tokens by model, cache reads by session and tokens at compaction on Cost; prompts per day on Standup). Charts are cell graphics in the terminal and SVG with hover values in the desktop app; other surfaces keep the simple view. Every chart has its numbers written beside it.
The pane is drawn in the text font only: no emoji, so it looks the same in every terminal. A finding is a colored dot, its title, then the severity word (HIGH / MID / LOW) with the evidence, the next step after →, and its actions as text. Colors are Claude Code theme colors, so they follow your light or dark theme, and none carries meaning without a word beside it.
Live numbers and CLAUDE.md checks are left to Claude Code itself. This mod looks back over days and sessions of your own use.
| To see | Use |
|---|---|
| Spend, plan limits, what fills the context now | /usage, /context, the status line |
| An AI-written report of recent sessions | /insights |
| Stale or conflicting lines in CLAUDE.md and skills | /doctor prompt-audit, /skill-doctor |
| Work over 1 / 3 / 7 days, by project | this mod's Standup |
| A warning when tokens burn fast | this mod's burn alert |
| Failures and redo requests that recur in this repository; your own agents | this mod's Improve and Tips |
Only the transcripts Claude Code keeps can be analysed (cleanupPeriodDays, 30 days by default); Cost, Tips and Improve say what period and how many sessions they cover. The transcript format is internal to Claude Code, so the pane warns when many transcripts cannot be read.
Change these in the Settings tab (6 or /chronicle settings), in /config, or in /plugin → Installed → ccmod-chronicle → Configure. With --plugin-dir, they live under pluginConfigs["ccmod-chronicle@inline"] in ~/.claude/settings.json. Changing one reloads the mod; the pane comes back where it was.
| Option | Default | What it does |
|---|---|---|
language | auto | en, ja, or auto (follows Claude Code's language setting) |
paneStyle | simple | simple (the list alone) or rich (figures and charts above it); v toggles it |
aiModel | haiku | Model for explanations and AI summaries: haiku, sonnet, opus, fable. fable uses usage credits and only runs when you press g. Also switchable from the detail view |
aiEffort | low | low, medium, high. The reply cap grows with it (700 / 1200 / 2000 tokens) |
autoExplain | true | Generate the explanation as soon as Details opens. Off: press g |
cacheExplanations | true | Reuse explanations of Cost / Tips / Improve findings until their numbers change |
reviewerAgents | empty | Subagent names that count as review (e.g. code-reviewer,security-reviewer). Claude Code ships none, so the review checks stay off until you name yours |
memoryTools | empty | MCP tool prefixes or CLI names you search notes with (e.g. mcp__notes__,notes-cli). Empty turns the recall check off |
memoryCueWords | empty | Words meaning "this needs earlier context". Empty uses built-in English and Japanese words |
extraRiskyCommands | empty | Extra command substrings to flag (e.g. terraform apply) |
retentionDays | 0 | Once Claude Code has deleted a session's transcript, its summary is kept until this many days after the session ended. 0 uses Claude Code's cleanupPeriodDays (30 by default), so summaries go when their transcripts do |
excludeProjects | empty | Comma-separated project path prefixes to leave out entirely (e.g. client work) |
burnAlert | 100000 | When a turn spends tokens faster than this (tokens/min; subagents included, cache reads count a tenth), the band above the prompt and the Now tab show it in rainbow letters like ultrathink. Twice it reads "very high". 0 turns it off |
burnEffect | rainbow | rainbow (animated), still (rainbow without motion) or plain (the warning color only) |
The mod calls a model only when you press AI summary or open Details (with autoExplain). Calls use your plan or API key. Defaults keep them small: haiku, low effort, a short reply, and a cache of explanations (40 entries, 14 days, keyed by content, model, effort, language and exclusions). Each answer shows its tokens; the detail view shows this session's total.
indexer/chronicle_index.py (stdlib Python) incrementally summarizes the transcripts Claude Code keeps under ~/.claude/projects/ (or $CLAUDE_CONFIG_DIR) into ~/.claude/chronicle/digest.json. The transcript format is not a public interface; if a Claude Code release changes it, findings may go quiet until the indexer is updated.hooks/register.js) runs the indexer at session start and on r, turns the digest into findings with fixed rules (hooks/rules.js, hooks/catalog.js) and watches the live session through mod events.hooks/strings-en.js and hooks/strings-ja.js.claude plugin validate --strict .
claude plugin test
python3 -m unittest discover -s indexer
hooks/register.js 804 lines1// ccmod-chronicle: a sidebar that analyzes how you use Claude Code.
2// Heavy lifting (reading ~800MB of transcripts) runs in indexer/chronicle_index.py
3// via $.process.run; this module renders the digest plus live session signals.
4
5import { buildNow, buildCost, buildImprove, buildStandup, rankFindings, workSessions, isReviewer, riskyCommands, trackToolCall } from './rules.js'
6import { localFacts, makeCtx, resolveLang, ruleConfig } from './i18n.js'
7import { buildTips } from './catalog.js'
8import { renderBand, renderPane, TABS } from './view.js'
9import { copyText, isShareableLine, shareableFinding, stripLinks } from './privacy.js'
10import { atom, read, update } from 'claude-code'
11import { currentValues, listEntries, ownConfigKey, parseSetting, removedEntries } from './settings-spec.js'
12import { readWorkspace } from './assets.js'
13import { digestCharts, liveCharts, localDay } from './charts.js'
14import { BURN, BURN_EFFECTS, EMPTY_BURN, endTurn, isBurning, restoreLast, startTurn } from './burn.js'
15import { addUsage, CREDIT_MODELS, LIVE_FIELDS, explainCacheKey, isCacheEntry, maxTokensFor, mergeSetting, tokensOf, normalizeSettings, pruneCache, settingsField, systemPrompt } from './ai-config.js'
16
17const PANE = 'ccmod-chronicle'
18const INDEX_TIMEOUT_MS = 10 * 60 * 1000
19const GIT_TIMEOUT_MS = 5000
20const MAX_GIT_PROJECTS = 8
21const MAX_DIGEST_BYTES = 3.5 * 1024 * 1024
22const ERROR_CHARS = 200
23// Repo-local config could make `git log` launch programs (gpg, fsmonitor); turn those off.
24const GIT_SAFE = ['git', '-c', 'log.showSignature=false', '-c', 'core.fsmonitor=false', '-c', 'diff.external=']
25const AI_TIMEOUT_MS = 60000
26// Pane body width when the surface does not say, and the widest the view will draw for.
27const DEFAULT_COLS = 60
28const MAX_COLS = 512
29const STARTUP_DELAY_MS = 1500
30// Mods need 2.1.287; userConfig `options` pickers need 2.1.271. Tested with 2.1.288.
31const MIN_VERSION = '2.1.287'
32// `python3` first; Windows installs often only have `python`.
33const PYTHONS = ['python3', 'python']
34const WINDOWS_COMMAND_NOT_FOUND = 9009
35const DEFAULT_CLEANUP_DAYS = 30
36const MAX_RETENTION_DAYS = 3650
37const ABSOLUTE_PATH = /^([A-Za-z]:[\\/]|\/)/
38const TAB_IDS = new Set(TABS.map((t) => t.id))
39// Live warnings describe this session only; dismissing them must not persist.
40const isSessionOnly = (id) => id.startsWith('now-')
41const EMPTY_LIVE = Object.freeze({ context: null, rateLimits: [], unreviewed: [], risky: {}, burn: EMPTY_BURN })
42
43let excludes = []
44// Rule settings and the pane's language; ctx is rebuilt when the language is known.
45let ruleCfg = ruleConfig()
46let risky = riskyCommands(ruleCfg)
47let ctx = makeCtx('en', ruleCfg)
48let claudeSettings = {}
49// This session's working directory, Claude Code's folder and the user's agents and skills.
50let workspace = {}
51// The rich view's digest charts, recomputed only when the digest or the local date changes.
52let chartMemo = null
53// The options this activation was loaded with, shown and edited in the Settings tab.
54let rawOptions = currentValues()
55let retentionDays = 0
56// The burn alert's threshold (tokens per minute, 0 = off) and how it is drawn.
57let burnCfg = { threshold: BURN.defaultPerMin, effect: 'rainbow' }
58let digest = null
59let findings = null
60let tab = 'now'
61let days = 1
62let dismissed = []
63let sessionDismissed = []
64let gitLogs = {}
65let gitSeq = 0
66let ai = {}
67// The detail view holds an id and is re-resolved on every render, so it follows live data.
68// lastDetail is shown (marked resolved) once the finding is gone. Explanations are keyed by
69// finding id: digest findings only change on re-index (which drops their explanations), and
70// live now-* findings keep theirs while their numbers move. The epochs discard answers that
71// arrive after a re-index (digestEpoch) or /clear (sessionEpoch).
72let detailId = null
73let lastDetail = null
74let explain = {}
75let digestEpoch = 0
76let sessionEpoch = 0
77// AI settings from userConfig, kept current by config.set; usage totals for this session.
78let settings = normalizeSettings({})
79let aiUsage = { calls: 0, in: 0, out: 0 }
80let inflight = new Set()
81let saveChain = Promise.resolve()
82// Survives the reload an options change triggers (see types/index.d.ts); reset by /clear.
83const VIEW = atom({ plugin: 'ccmod-chronicle', key: 'view' }, { tab: 'now', detailId: null, days: 1, aiUsage: { calls: 0, in: 0, out: 0 }, nowExplain: {}, live: { unreviewed: [], risky: {} }, sessionDismissed: [], burn: { last: null, hidden: false } })
84// A restored digest-finding detail waits for the re-index before it is reopened (or dropped).
85let pendingDetailId = null
86let persistChain = Promise.resolve()
87let status = { indexing: false, generatedAt: null, sessions: 0, error: null }
88// Kept apart from status.error, which every index run resets.
89let versionWarning = null
90let live = EMPTY_LIVE
91
92// The options this activation runs with (an options change reloads the mod and calls this again).
93function loadOptions(options = {}) {
94 settings = normalizeSettings(options)
95 rawOptions = currentValues(options)
96 ruleCfg = ruleConfig(options)
97 risky = riskyCommands(ruleCfg)
98 ctx = makeCtx('en', ruleCfg)
99 retentionDays = clampDays(options.retentionDays)
100 // Comma or newline only: a ':' would split Windows paths such as C:\\Clients.
101 excludes = listEntries(options.excludeProjects)
102 burnCfg = burnConfig(options)
103}
104
105function burnConfig(options) {
106 const n = Math.floor(Number(options.burnAlert ?? BURN.defaultPerMin))
107 const threshold = Number.isFinite(n) && n >= 0 ? Math.min(n, BURN.maxPerMin) : BURN.defaultPerMin
108 return { threshold, effect: BURN_EFFECTS.includes(options.burnEffect) ? options.burnEffect : 'rainbow' }
109}
110
111export function register(on, options) {
112 loadOptions(options || {})
113
114 on('session.start', async ($, e, next) => {
115 await startSession($)
116 return next(e)
117 }).catch(passThrough)
118
119 // /clear, /resume and /branch end the conversation without a new session.start.
120 on('session.end', async ($, e, next) => {
121 await resetSession($)
122 return next(e)
123 }).catch(passThrough)
124
125 // /config (or this pane's model picker) changed one of our fields: use it from the next call.
126 on('config.set', async ($, e, next) => onConfigSet($, e, await next(e))).catch(passThrough)
127
128 on('command.run', { command: 'chronicle' }, async ($, e) => runCommand($, String(e.args || '').trim()))
129
130 on('session.measure', async ($, e, next) => {
131 live = { ...live, context: e.context, rateLimits: e.rateLimits || [] }
132 $.ui.invalidate('ui.render')
133 return next(e)
134 }).catch(passThrough)
135
136 on('tool.call', async ($, e, next) => {
137 onToolCall($, e)
138 return next(e)
139 }).catch(passThrough)
140
141 on('turn.start', async ($, e, next) => {
142 if (e.agentId === undefined) live = { ...live, burn: startTurn(live.burn, e.turnId, await $.clock.now()) }
143 return next(e)
144 }).catch(passThrough)
145
146 on('turn.complete', async ($, e, next) => {
147 onTurnComplete($, e, await $.clock.now())
148 return next(e)
149 }).catch(passThrough)
150
151 on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
152 if (e.props?.hasSurvey || !isBurning(live.burn) || live.burn.hidden || !burnCfg.threshold) return next(e)
153 return renderBand($.ui.resolve(e), { t: ctx.t, last: live.burn.last, effect: burnCfg.effect }, handlersFor($))
154 }).catch(passThrough)
155
156 on('agent.spawn', async ($, e, next) => {
157 if (isReviewer(e.subagentType, ruleCfg.reviewers) && live.unreviewed.length) {
158 live = { ...live, unreviewed: [] }
159 $.ui.invalidate('ui.render')
160 persistView($)
161 }
162 return next(e)
163 }).catch(passThrough)
164
165 on('ui.render', { component: 'Pane' }, async ($, e, next) => {
166 if (e.requestId !== PANE) return next(e)
167 const el = $.ui.resolve(e)
168 const view = { surface: e.surface, cols: e.props?.bodyColumns }
169 return renderPane(el, viewModel(await $.clock.now(), view), handlersFor($))
170 })
171}
172
173// These hooks only observe: if one fails, the call it watched goes ahead untouched. In a catch
174// handler next is replay-safe (an earlier call is not run again), so next(e) is always right.
175function passThrough($, e, next) {
176 return next(e)
177}
178
179function onToolCall($, e) {
180 const before = live
181 live = trackToolCall(live, e, risky)
182 if (live === before) return
183 $.ui.invalidate('ui.render')
184 persistView($)
185}
186
187function onTurnComplete($, e, now) {
188 const before = live.burn
189 const burn = endTurn(before, e, burnCfg.threshold, now)
190 if (burn === before) return
191 live = { ...live, burn }
192 if (burn.last === before.last) return
193 // A new heavy turn is news again, even where the last alert was dismissed on Now.
194 if (burn.last.level) sessionDismissed = sessionDismissed.filter((id) => id !== 'now-burn')
195 $.ui.invalidate('ui.render')
196 persistView($)
197}
198
199function onConfigSet($, e, result) {
200 const field = settingsField(e.key, $.plugin.name)
201 if (field && !result?.deny) {
202 applySetting(field, result.value)
203 $.ui.invalidate('ui.render')
204 }
205 return result
206}
207
208// Show a saved value at once. AI and language settings also apply in place; the rest take
209// effect when the engine reloads the mod with the new options.
210function applySetting(field, value) {
211 rawOptions = { ...rawOptions, [field]: value }
212 if (!LIVE_FIELDS.has(field)) return
213 settings = mergeSetting(settings, field, value)
214 if (field === 'language') applyLanguage()
215}
216
217// The conversation is gone: drop everything that described it and rewrite the $.state mirror.
218async function resetSession($) {
219 live = EMPTY_LIVE
220 sessionDismissed = []
221 aiUsage = { calls: 0, in: 0, out: 0 }
222 ai = {}
223 tab = 'now'
224 pendingDetailId = null
225 closeDetail(true)
226 await persistView($)
227}
228
229async function startSession($) {
230 claudeSettings = await readClaudeSettings($)
231 workspace = await readWorkspace($, (await indexPaths($).catch(() => ({}))).claudeDir)
232 applyLanguage()
233 dismissed = await loadDismissed($)
234 await checkVersion($)
235 const isReload = await restoreView($)
236 $.ui.invalidate('ui.render')
237 // After a reload (e.g. a model change) the startup toast would only repeat itself.
238 $.clock.after(STARTUP_DELAY_MS, () => refresh($, !isReload))
239 await $.command.register({
240 name: 'chronicle',
241 description: 'Open the usage-analysis sidebar (now | cost | tips | standup | improve | settings | refresh | purge)',
242 argumentHint: '[tab|settings|refresh|purge]',
243 immediate: true,
244 })
245}
246
247async function readClaudeSettings($) {
248 try {
249 const s = await $.settings.read()
250 return s && typeof s === 'object' ? s : {}
251 } catch {
252 return {}
253 }
254}
255
256// The pane follows the `language` option, or Claude Code's own `language` setting on auto.
257function applyLanguage() {
258 ctx = makeCtx(resolveLang(settings.language, claudeSettings.language), ruleCfg, { ...localFacts(claudeSettings), ...workspace })
259 findings = null
260}
261
262const versionParts = (v) => String(v).split(/[.-]/).slice(0, 3).map((n) => Number(n) || 0)
263const isOlder = (a, b) => {
264 const [x, y] = [versionParts(a), versionParts(b)]
265 const i = x.findIndex((n, k) => n !== y[k])
266 return i >= 0 && x[i] < y[i]
267}
268
269async function checkVersion($) {
270 try {
271 const { version } = await $.session.version()
272 versionWarning = isOlder(version, MIN_VERSION) ? { v: version, min: MIN_VERSION } : null
273 } catch {
274 // Unknown version: carry on; a missing API would have failed to load the mod anyway.
275 }
276}
277
278async function restoreView($) {
279 const v = await read($, VIEW)
280 if (TAB_IDS.has(v.tab)) tab = v.tab
281 if ([1, 3, 7].includes(v.days)) days = v.days
282 aiUsage = v.aiUsage || aiUsage
283 explain = { ...explain, ...(v.nowExplain || {}) }
284 sessionDismissed = Array.isArray(v.sessionDismissed) ? v.sessionDismissed : []
285 if (v.live) live = { ...live, unreviewed: v.live.unreviewed || [], risky: v.live.risky || {} }
286 // Judged again: the reload may have come from a burnAlert change.
287 const last = restoreLast(v.burn?.last, burnCfg.threshold)
288 if (last) live = { ...live, burn: { ...EMPTY_BURN, last, hidden: Boolean(v.burn.hidden) } }
289 restoreDetail(v.detailId)
290 return Boolean(v.detailId || v.aiUsage?.calls || v.tab !== 'now')
291}
292
293// Reopen a restored detail only if its finding still exists; digest ones wait for the re-index.
294function restoreDetail(id) {
295 if (!id) return
296 if (!isSessionOnly(id)) {
297 pendingDetailId = id
298 return
299 }
300 const current = buildNow(live, ctx).find((f) => f.id === id)
301 detailId = current ? id : null
302 lastDetail = current || null
303}
304
305// Mirror the view into $.state after each change; never called from ui.render, never throws.
306function viewSnapshot() {
307 const nowExplain = Object.fromEntries(Object.entries(explain)
308 .filter(([id, v]) => isSessionOnly(id) && v?.text)
309 .map(([id, v]) => [id, { text: v.text, model: v.model, ...(v.tokens ? { tokens: v.tokens } : {}) }]))
310 return { tab, detailId: detailId || pendingDetailId, days, aiUsage, nowExplain, live: { unreviewed: live.unreviewed, risky: live.risky }, sessionDismissed, burn: { last: live.burn.last, hidden: live.burn.hidden } }
311}
312
313// Writes are chained and each one snapshots the view when it runs, so an older snapshot can
314// never land after a newer one.
315function persistView($) {
316 persistChain = persistChain.then(() => writeView($))
317 return persistChain
318}
319
320async function writeView($) {
321 try {
322 await update($, VIEW, () => viewSnapshot())
323 } catch {
324 // Losing the mirror only matters on the next reload; the pane keeps working.
325 }
326}
327
328async function runCommand($, arg) {
329 if (arg === 'purge') return { text: await purgeAll($) }
330 // Indexing can take minutes; never hold the command hook on it.
331 if (arg === 'refresh') refresh($, false)
332 else if (TAB_IDS.has(arg)) {
333 tab = arg
334 closeDetail(false)
335 }
336 if (tab === 'standup') loadGitLogs($)
337 await persistView($)
338 await $.ui.open({ id: PANE, title: 'Chronicle', focus: true, closeOnEscape: true })
339 $.ui.invalidate('ui.render')
340 const unknown = arg && arg !== 'refresh' && !TAB_IDS.has(arg)
341 if (unknown) return { text: ctx.t('unknownTab', { arg }) }
342 return (await drawsPane($)) ? {} : { text: textSummary() }
343}
344
345// The pane shows in the terminal and the desktop app only (not VS Code, mobile or -p).
346async function drawsPane($) {
347 try {
348 return (await $.session.surfaces()).some((s) => s === 'terminal' || s === 'desktop')
349 } catch {
350 return true
351 }
352}
353
354function textSummary() {
355 const lists = { now: buildNow(live, ctx), ...digestFindings() }
356 const top = rankFindings(Object.values(lists).flat(), [...dismissed, ...sessionDismissed]).slice(0, 5)
357 return ctx.t('noPane', { lines: top.map((f) => `- ${f.title} (${f.evidence})`).join('\n') || '- ' + ctx.t('emptyList') })
358}
359
360// Digest-derived findings change only when the digest does, so compute them once.
361function digestFindings() {
362 if (!digest) return { cost: [], tips: [], improve: [] }
363 if (!findings) findings = { cost: buildCost(digest, ctx), tips: buildTips(digest, ctx), improve: buildImprove(digest, ctx) }
364 return findings
365}
366
367// nowMs comes from $.clock.now() so the standup window follows the engine's (and tests') clock.
368function viewModel(nowMs, view = {}) {
369 const lists = { now: buildNow(live, ctx), ...digestFindings() }
370 const hidden = [...dismissed, ...sessionDismissed]
371 const ranked = Object.fromEntries(Object.entries(lists).map(([k, v]) => [k, rankFindings(v, hidden)]))
372 const detail = resolveDetail(lists)
373 const raw = Math.floor(Number(view.cols))
374 const cols = Number.isFinite(raw) && raw > 0 ? Math.min(MAX_COLS, raw) : DEFAULT_COLS
375 return { t: ctx.t, nowMs, tab, days, status, versionWarning, config: rawOptions, ai, settings, aiUsage, detail, explain: detail ? explain[detail.id] : null, lists: ranked, standup: digest ? buildStandup(digest, days, nowMs, gitLogs, ctx) : [], surface: view.surface, cols, burnEffect: burnCfg.effect, coverage: coverage(), ...richView(nowMs) }
376}
377
378// What the digest covers: the first local day of its readable work sessions, and how long Claude
379// Code keeps transcripts (its cleanupPeriodDays, not this mod's retentionDays for summaries).
380function coverage() {
381 const starts = workSessions(digest).filter((s) => s.readable !== false).map((s) => Date.parse(s.start)).filter(Number.isFinite)
382 if (!starts.length) return null
383 return { since: localDay(Math.min(...starts)), n: starts.length, keepDays: clampDays(claudeSettings.cleanupPeriodDays) || DEFAULT_CLEANUP_DAYS }
384}
385
386// Charts are computed only for the rich style; the view sizes them to the pane's body.
387// The digest's charts are kept until the digest or the local date changes; meters are live.
388function richView(nowMs) {
389 if (settings.paneStyle !== 'rich') return {}
390 const day = localDay(nowMs)
391 if (!chartMemo || chartMemo.digest !== digest || chartMemo.day !== day) chartMemo = { digest, day, charts: digestCharts(digest, nowMs) }
392 return { charts: { ...chartMemo.charts, ...liveCharts(live) } }
393}
394
395function resolveDetail(lists) {
396 if (!detailId) return null
397 const current = Object.values(lists).flat().find((f) => f.id === detailId)
398 if (current) lastDetail = current
399 return lastDetail && { ...lastDetail, isResolved: !current, copyText: copyText(lastDetail, ctx.t) }
400}
401
402function closeDetail(dropExplanations) {
403 detailId = null
404 lastDetail = null
405 // The user moved on: a detail waiting to be restored after a reload must not reopen.
406 pendingDetailId = null
407 if (dropExplanations) {
408 explain = {}
409 sessionEpoch += 1
410 }
411}
412
413function handlersFor($) {
414 return {
415 onTab: (id) => {
416 tab = id
417 closeDetail(false)
418 if (id === 'standup') loadGitLogs($)
419 $.ui.invalidate('ui.render')
420 persistView($)
421 },
422 onDays: (d) => {
423 days = d
424 gitLogs = {}
425 ai = { ...ai, standup: undefined }
426 loadGitLogs($)
427 $.ui.invalidate('ui.render')
428 persistView($)
429 },
430 onRefresh: () => refresh($, false),
431 onDismiss: (f) => dismiss($, f.id),
432 onAsk: (f) => openDetail($, f),
433 onBack: () => {
434 closeDetail(false)
435 $.ui.invalidate('ui.render')
436 persistView($)
437 },
438 onExplainAgain: (f) => explainFinding($, f, { force: true, allowCall: true }),
439 onSetting: (field, value) => setSetting($, field, value),
440 onCopy: (text, press) => copyPrompt($, text, press),
441 onApply: (f) => applyViaClaude($, f),
442 onAi: (id) => summarize($, id),
443 onBurnDetail: () => openBurnDetail($),
444 onBurnHide: () => {
445 live = { ...live, burn: { ...live.burn, hidden: true } }
446 $.ui.invalidate('ui.render')
447 persistView($)
448 },
449 }
450}
451
452// The band's Details: the pane opens on Now with the burn finding's detail.
453async function openBurnDetail($) {
454 const f = buildNow(live, ctx).find((x) => x.id === 'now-burn')
455 if (!f) return
456 tab = 'now'
457 openDetail($, f)
458 await $.ui.open({ id: PANE, title: 'Chronicle', focus: true, closeOnEscape: true })
459}
460
461async function refresh($, isStartup) {
462 if (status.indexing) return
463 status = { ...status, indexing: true, error: null }
464 $.ui.invalidate('ui.render')
465 try {
466 const paths = await indexPaths($)
467 const run = await runIndexer($, indexerArgs(paths))
468 // The last lines of a traceback name the actual exception.
469 if (run.exitCode !== 0) throw new Error((run.stdout + run.stderr).trim().slice(-ERROR_CHARS) || 'exit ' + run.exitCode)
470 const raw = await $.fs.read(paths.outDir + '/digest.json')
471 adoptDigest($, raw)
472 if (isStartup) await announce($)
473 } catch (err) {
474 status = { ...status, indexing: false, error: String(err?.message || err).slice(-ERROR_CHARS) }
475 }
476 $.ui.invalidate('ui.render')
477}
478
479function adoptDigest($, raw) {
480 digest = JSON.parse(raw)
481 findings = null
482 ai = {}
483 explain = Object.fromEntries(Object.entries(explain).filter(([id]) => isSessionOnly(id)))
484 digestEpoch += 1
485 const isBig = new TextEncoder().encode(raw).length > MAX_DIGEST_BYTES
486 status = { indexing: false, generatedAt: digest.generatedAt, sessions: workSessions(digest).length, error: isBig ? ctx.t('digestBig') : null, unreadable: unreadableShare(digest) }
487 if (tab === 'standup') loadGitLogs($)
488 adoptPendingDetail($)
489 // An open detail view now shows re-indexed numbers; explain them afresh.
490 const open = resolveDetail({ now: buildNow(live, ctx), ...digestFindings() })
491 if (open && !open.isResolved) explainFinding($, open, { force: false, allowCall: autoCallAllowed() })
492}
493
494// Transcripts the indexer could not read: Claude Code may have changed their (internal) format.
495// Shown once they are a fifth of the sessions, and at least three.
496function unreadableShare(d) {
497 const n = Number(d?.stats?.unreadable) || 0
498 return n >= 3 && n >= (d.sessions?.length || 0) * 0.2 ? n : 0
499}
500
501// Where Claude Code keeps its files: CLAUDE_CONFIG_DIR when set, else ~/.claude.
502async function indexPaths($) {
503 const configDir = await $.env.get('CLAUDE_CONFIG_DIR')
504 const home = (await $.env.get('HOME')) || (await $.env.get('USERPROFILE'))
505 if (!configDir && !home) throw new Error(ctx.t('noHome'))
506 const claudeDir = configDir || home + '/.claude'
507 return { claudeDir, outDir: claudeDir + '/chronicle' }
508}
509
510// Summaries are kept as long as Claude Code keeps transcripts, unless retentionDays says otherwise.
511function retention() {
512 if (retentionDays > 0) return retentionDays
513 return clampDays(claudeSettings.cleanupPeriodDays) || DEFAULT_CLEANUP_DAYS
514}
515
516// Whole days within 0..MAX_RETENTION_DAYS, so the indexer never gets a fraction or an overflow.
517function clampDays(value) {
518 const n = Math.floor(Number(value))
519 return Number.isFinite(n) && n > 0 ? Math.min(n, MAX_RETENTION_DAYS) : 0
520}
521
522// One argv element per value, so a value starting with '-' can never become an option.
523function indexerArgs({ claudeDir, outDir }) {
524 return [
525 '--claude-dir=' + claudeDir,
526 '--out-dir=' + outDir,
527 '--retention-days=' + retention(),
528 ...excludes.map((x) => '--exclude=' + x),
529 ...ruleCfg.extraRisky.map((x) => '--risky=' + x),
530 ...ruleCfg.memoryCues.map((x) => '--memory-cue=' + x),
531 ]
532}
533
534async function runIndexer($, args) {
535 const script = $.plugin.root + '/indexer/chronicle_index.py'
536 let lastError = null
537 for (const python of PYTHONS) {
538 try {
539 const run = await $.process.run([python, script, ...args], { timeoutMs: INDEX_TIMEOUT_MS })
540 if (run.exitCode !== WINDOWS_COMMAND_NOT_FOUND) return run
541 } catch (err) {
542 lastError = err
543 }
544 }
545 throw lastError || new Error('python3 / python not found')
546}
547
548// /chronicle purge: delete the index, the explanation cache, dismissals and the saved view.
549async function purgeAll($) {
550 // A running index would write the files straight back.
551 if (status.indexing) return ctx.t('purgeBusy')
552 try {
553 const { outDir } = await indexPaths($)
554 const run = await runIndexer($, ['--purge', '--out-dir=' + outDir])
555 if (run.exitCode !== 0) throw new Error((run.stdout + run.stderr).trim().slice(-ERROR_CHARS))
556 await $.store.delete('explainCache')
557 await $.store.delete('dismissed')
558 dismissed = []
559 digest = null
560 findings = null
561 status = { indexing: false, generatedAt: null, sessions: 0, error: null }
562 await resetSession($)
563 $.ui.invalidate('ui.render')
564 return ctx.t('purged')
565 } catch (err) {
566 return ctx.t('purgeFailed', { error: String(err?.message || err).slice(-ERROR_CHARS) })
567 }
568}
569
570function adoptPendingDetail($) {
571 if (!pendingDetailId) return
572 const found = Object.values(digestFindings()).flat().find((f) => f.id === pendingDetailId)
573 if (found && !detailId) {
574 detailId = found.id
575 lastDetail = found
576 }
577 pendingDetailId = null
578 persistView($)
579}
580
581async function announce($) {
582 const model = viewModel(await $.clock.now())
583 const high = ['cost', 'improve'].reduce((n, k) => n + model.lists[k].filter((f) => f.severity === 'high').length, 0)
584 if (high) $.ui.toast(ctx.t('highFindings', { n: high }))
585}
586
587async function loadDismissed($) {
588 const saved = await $.store.get('dismissed')
589 return Array.isArray(saved) ? saved.filter((x) => typeof x === 'string') : []
590}
591
592async function dismiss($, id) {
593 if (isSessionOnly(id)) {
594 sessionDismissed = [...new Set([...sessionDismissed, id])]
595 $.ui.invalidate('ui.render')
596 await persistView($)
597 return
598 }
599 dismissed = [...new Set([...dismissed, id])]
600 $.ui.invalidate('ui.render')
601 // Re-read right before writing: another session (or a reload) may have saved more.
602 const merged = [...new Set([...(await loadDismissed($)), ...dismissed])]
603 dismissed = merged
604 await $.store.set('dismissed', merged)
605}
606
607async function loadGitLogs($) {
608 if (!digest) return
609 const mine = ++gitSeq
610 const d = days
611 const rows = buildStandup(digest, d, await $.clock.now(), {}, ctx).slice(0, MAX_GIT_PROJECTS).filter((r) => ABSOLUTE_PATH.test(r.project))
612 const results = await Promise.all(rows.map((row) => gitLog($, row.project, d)))
613 if (mine !== gitSeq) return
614 gitLogs = Object.fromEntries(rows.map((row, i) => [row.project, results[i]]).filter(([, lines]) => lines.length))
615 $.ui.invalidate('ui.render')
616}
617
618async function gitLog($, project, d) {
619 try {
620 const argv = [...GIT_SAFE, '-C', project, 'log', '--no-show-signature', '--no-ext-diff', '--no-textconv', `--since=${d} days ago`, '--pretty=%s', '-n', '10']
621 const r = await $.process.run(argv, { timeoutMs: GIT_TIMEOUT_MS })
622 return r.exitCode === 0 ? r.stdout.split('\n').map((s) => s.trim()).filter(Boolean) : []
623 } catch {
624 // Not a git repository, git missing or timed out: the standup shows no commits.
625 return []
626 }
627}
628
629// Details: show the finding in the pane itself; nothing is sent to the main conversation.
630function openDetail($, f) {
631 detailId = f.id
632 lastDetail = f
633 $.ui.invalidate('ui.render')
634 persistView($)
635 explainFinding($, f, { force: false, allowCall: autoCallAllowed() })
636}
637
638// Credit-billed models only run on an explicit press, whatever autoExplain says.
639function autoCallAllowed() {
640 return settings.autoExplain && !CREDIT_MODELS.has(settings.model)
641}
642
643// Digest findings are cached in $.store by content + model + effort, so reopening one in a
644// later session costs no tokens; live now-* findings are kept in $.state for the session.
645async function explainFinding($, f, { force, allowCall }) {
646 const key = f.id
647 // Marked before any await, so a second press or a re-index cannot start a duplicate call.
648 if (inflight.has(key) || (explain[key]?.text && !force)) return
649 inflight.add(key)
650 let retry = false
651 try {
652 retry = await explainOnce($, f, key, force, allowCall)
653 } finally {
654 inflight.delete(key)
655 }
656 // A re-index landed while we waited: explain the finding as it is now. An unchanged finding
657 // hits the cache the stale answer was just saved to, so this costs no tokens.
658 const current = retry && detailId === key ? Object.values(digestFindings()).flat().find((x) => x.id === key) : null
659 if (current) await explainFinding($, current, { force: false, allowCall })
660}
661
662async function explainOnce($, f, key, force, allowCall) {
663 const used = settings
664 const payload = shareableFinding(f, ctx.t)
665 const storeKey = isSessionOnly(key) || !used.cacheExplanations ? null : explainCacheKey(payload, used, excludes, ctx.lang)
666 const stored = storeKey && !force ? (await loadExplainCache($))[storeKey] : null
667 if (stored) {
668 explain = { ...explain, [key]: { text: stripLinks(stored.text), model: stored.model, isCached: true } }
669 $.ui.invalidate('ui.render')
670 return
671 }
672 if (!allowCall) return
673 const epochs = [digestEpoch, sessionEpoch]
674 explain = { ...explain, [key]: { loading: true, model: used.model } }
675 $.ui.invalidate('ui.render')
676 const result = await askModel($, used, systemPrompt('explain', ctx.t), { instruction: ctx.t('explainInstruction'), data: payload }, maxTokensFor(used))
677 if (epochs[1] !== sessionEpoch) return false
678 // The answer matches the content it was asked about, so it is cached even if a re-index won.
679 if (storeKey && result.text) await saveExplain($, storeKey, { text: result.text, model: used.model, at: await $.clock.now() })
680 if (!isSessionOnly(key) && epochs[0] !== digestEpoch) return true
681 explain = { ...explain, [key]: result }
682 $.ui.invalidate('ui.render')
683 await persistView($)
684 return false
685}
686
687// One model call with the given settings snapshot; records usage and never throws.
688async function askModel($, used, system, input, maxTokens) {
689 try {
690 const r = await $.model.complete({ model: used.model, effort: used.effort, system, prompt: JSON.stringify(input), maxTokens, timeoutMs: AI_TIMEOUT_MS })
691 if (!r.isAnswered) return { error: r.reason || 'no answer', model: used.model }
692 aiUsage = addUsage(aiUsage, r.usage)
693 return { text: stripLinks(r.text), model: used.model, tokens: tokensOf(r.usage) }
694 } catch (err) {
695 return { error: String(err?.message || err).slice(-ERROR_CHARS), model: used.model }
696 }
697}
698
699// Cache I/O never blocks an explanation: a failed read is a miss, a failed write is dropped.
700async function loadExplainCache($) {
701 try {
702 const saved = await $.store.get('explainCache')
703 if (!saved || typeof saved !== 'object') return {}
704 return Object.fromEntries(Object.entries(saved).filter(([, v]) => isCacheEntry(v)))
705 } catch {
706 return {}
707 }
708}
709
710// Writes are chained so two answers finishing together do not overwrite each other.
711function saveExplain($, storeKey, entry) {
712 saveChain = saveChain.then(() => writeExplain($, storeKey, entry))
713 return saveChain
714}
715
716async function writeExplain($, storeKey, entry) {
717 try {
718 // Re-read before writing: another session may have cached answers too.
719 const merged = pruneCache({ ...(await loadExplainCache($)), [storeKey]: entry }, entry.at)
720 await $.store.set('explainCache', merged)
721 } catch {
722 // The cache is an optimisation; the answer is already on screen.
723 }
724}
725
726// Saves to this plugin's /config row; the engine then reloads the plugin with the new options,
727// and restoreView brings the pane back as it was. Values are checked before anything is written.
728async function setSetting($, field, input) {
729 const parsed = parseSetting(field, input)
730 if (parsed.error) {
731 $.ui.toast(ctx.t(parsed.error, parsed.params))
732 return
733 }
734 const value = parsed.value
735 try {
736 const key = ownConfigKey(await $.config.list(), $.plugin.name, field)
737 if (!key) {
738 $.ui.toast(ctx.t('settingFailed', { reason: ctx.t('settingAmbiguous') }))
739 return
740 }
741 const r = await $.config.set({ key, value })
742 if (r?.deny) {
743 $.ui.toast(ctx.t('settingFailed', { reason: r.deny }))
744 return
745 }
746 } catch (err) {
747 $.ui.toast(ctx.t('settingFailed', { reason: String(err?.message || err).slice(-ERROR_CHARS) }))
748 return
749 }
750 const lifted = field === 'excludeProjects' ? removedEntries(rawOptions.excludeProjects, value) : 0
751 applySetting(field, value)
752 const label = ctx.t('cfg_' + field)
753 const message = lifted ? ctx.t('exclusionsLifted', { n: lifted })
754 : field === 'aiModel' && CREDIT_MODELS.has(value) ? ctx.t('creditWarn', { model: value })
755 : ctx.t(LIVE_FIELDS.has(field) ? 'settingSaved' : 'settingSavedReload', { key: label })
756 // The save usually reloads the mod; this activation may already be gone, so never let it throw.
757 try {
758 $.ui.toast(message)
759 $.ui.invalidate('ui.render')
760 } catch {
761 // The reloaded pane draws the new value itself.
762 }
763}
764
765async function copyPrompt($, text, press) {
766 const r = await $.ui.copy(press?.surface ? { text, surface: press.surface } : { text })
767 $.ui.toast(r.isCopied ? ctx.t('copied') : ctx.t('copyFailed', { reason: r.reason || '?' }))
768}
769
770async function applyViaClaude($, f) {
771 closeDetail(false)
772 await persistView($)
773 await $.ui.close({ id: PANE })
774 $.prompt.submit({ text: f.applyPrompt })
775}
776
777async function summarize($, id) {
778 if (ai[id]?.loading) return
779 ai = { ...ai, [id]: { loading: true } }
780 $.ui.invalidate('ui.render')
781 const data = aiPayload(id, await $.clock.now())
782 ai = { ...ai, [id]: await askModel($, settings, systemPrompt('summary', ctx.t), { instruction: ctx.t('summaryInstruction'), data }, maxTokensFor(settings)) }
783 $.ui.invalidate('ui.render')
784 await persistView($)
785}
786
787// What leaves the machine: findings and counts, project basenames only.
788function aiPayload(id, nowMs) {
789 const model = viewModel(nowMs)
790 if (id === 'standup') {
791 return {
792 tab: id, days,
793 projects: model.standup.map((r) => ({
794 project: String(r.project).split(/[\\/]/).filter(Boolean).pop(),
795 // Free text from transcripts and git: lines that look like paths or URLs stay here.
796 titles: r.sessions.filter((s) => !s.fromPrompt).map((s) => s.title).filter(isShareableLine).slice(-6),
797 recap: r.sessions.map((s) => s.away).filter(isShareableLine).slice(-2),
798 commits: r.commits.filter(isShareableLine).slice(0, 10),
799 })),
800 }
801 }
802 return { tab: id, findings: model.lists[id].map((f) => shareableFinding(f, ctx.t)) }
803}
804hooks/rules.js 383 lines1// Pure rule engine: digest (from the indexer) + live session data -> findings.
2// No mods API calls here, so it can be imported and unit-tested freely. Every builder takes a
3// ctx from i18n.js (language, strings, doc links, user rule settings); omitted, it is English
4// with the default rules.
5
6import { makeCtx } from './i18n.js'
7import { groundedImprove } from './grounded.js'
8
9export const THRESHOLDS = {
10 contextWarnPct: 60,
11 contextHighPct: 80,
12 rateLimitWarnPct: 80,
13 compactHighTokens: 700_000,
14 heavySessions: 3,
15 heavyShareHigh: 0.5,
16 unreviewedEdits: 3,
17 reviewerRatioLow: 0.1,
18 correctionHigh: 10,
19 correctionShare: 0.02,
20 longTurnMs: 30 * 60 * 1000,
21 toolErrorsHigh: 100,
22 toolErrorShare: 0.05,
23 cheapShareLow: 0.15,
24}
25
26// Kept in step with RISKY_PATTERNS in indexer/chronicle_index.py.
27export const RISKY_COMMANDS = [
28 [/\brm\s+-\w*r/, 'rm -r'],
29 [/git\s+push\b.*(\s-f\b|--force(?!-with-lease))/, 'force push'],
30 [/git\s+reset\s+--hard/, 'reset --hard'],
31 [/(^|[\s;&|])(ssh|scp|rsync)\s/, 'remote copy/shell'],
32 [/(^|[\s;&|])sudo\s/, 'sudo'],
33]
34const CODE_EXTS = new Set(['.ts', '.tsx', '.js', '.jsx', '.mjs', '.cjs', '.py', '.rs', '.go', '.swift', '.kt', '.java', '.c', '.cpp', '.cs', '.rb'])
35
36const sum = (xs) => xs.reduce((a, b) => a + b, 0)
37export const fmt = (n) => (n >= 1e9 ? (n / 1e9).toFixed(1) + 'B' : n >= 1e6 ? (n / 1e6).toFixed(1) + 'M' : n >= 1e3 ? (n / 1e3).toFixed(0) + 'k' : String(n))
38const finding = (f) => ({ severity: 'mid', details: [], ...f })
39const DETAIL_ROWS = 6
40export const TRIGGERS = new Set(['auto', 'manual'])
41const pct = (n, total) => (total ? Math.round((n / total) * 100) : 0)
42const basename = (p) => String(p || '?').split(/[\\/]/).filter(Boolean).pop() || '?'
43export const sessionLabel = (s) => `${basename(s.project)} ${String(s.end || '').slice(5, 10)}`
44// Sessions a person worked in: the indexer marks SDK runs and one-shot calls with no tools and
45// no title (desktop helpers, scripts) as automated, and they say nothing about how you work.
46export const workSessions = (digest) => (digest?.sessions || []).filter((s) => !s.automated)
47// Details are built from counts, model names, dates and project folder names only.
48const topSessions = (digest, score, render) => workSessions(digest)
49 .map((s) => ({ s, v: score(s) })).filter((r) => r.v > 0)
50 .sort((a, b) => b.v - a.v).slice(0, DETAIL_ROWS).map(render)
51
52export function isCodePath(path) {
53 const dot = path.lastIndexOf('.')
54 return dot >= 0 && CODE_EXTS.has(path.slice(dot).toLowerCase())
55}
56
57// A plugin-scoped agent (`my-plugin:code-reviewer`) counts by its last segment.
58export function isReviewer(agentType, reviewers) {
59 return reviewers.includes(String(agentType || '').split(':').pop())
60}
61
62// Built-in risky commands plus the user's extra substrings (labelled by the substring itself).
63export function riskyCommands(cfg) {
64 const escape = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
65 const builtIn = new Set(RISKY_COMMANDS.map(([, label]) => label))
66 // A string equal to a built-in label would count the same command twice.
67 return [...RISKY_COMMANDS, ...cfg.extraRisky.filter((s) => !builtIn.has(s)).map((s) => [new RegExp(escape(s)), s])]
68}
69
70// Fold every session into one set of totals.
71export function totals(digest) {
72 const t = { tools: {}, agents: {}, risky: {}, permModes: {}, apiErrors: {}, usage: {}, editExts: {}, bashHeads: {}, compactions: [], turns: [], sessions: 0 }
73 const add = (dst, src) => { for (const [k, v] of Object.entries(src || {})) dst[k] = (dst[k] || 0) + v }
74 const compactions = new Map()
75 for (const s of workSessions(digest)) {
76 t.sessions += 1
77 add(t.tools, s.tools); add(t.agents, s.agents); add(t.risky, s.risky); add(t.bashHeads, s.bashHeads)
78 add(t.permModes, s.permModes); add(t.apiErrors, s.apiErrors); add(t.editExts, s.editExts)
79 for (const src of [s.usageByModel, s.subUsage]) {
80 for (const [model, u] of Object.entries(src || {})) {
81 const row = (t.usage[model] ||= { in: 0, out: 0, cacheRead: 0, cacheWrite: 0 })
82 for (const k of Object.keys(row)) row[k] += u[k] || 0
83 }
84 }
85 // A transcript copied into another session file repeats its compactions; count each once.
86 for (const c of s.compactions || []) compactions.set(`${c.at}|${c.preTokens}`, c)
87 if (s.turns?.count) t.turns.push(s.turns)
88 }
89 t.compactions = [...compactions.values()]
90 return t
91}
92
93// Live state after one tool call: code files edited since the last review, risky commands run.
94export function trackToolCall(state, e, risky = RISKY_COMMANDS) {
95 let next = state
96 if ((e.tool === 'Edit' || e.tool === 'Write') && typeof e.file_path === 'string' && isCodePath(e.file_path)) {
97 if (!next.unreviewed.includes(e.file_path)) next = { ...next, unreviewed: [...next.unreviewed, e.file_path] }
98 }
99 if (e.tool === 'Bash' && typeof e.command === 'string') {
100 for (const [re, label] of risky) {
101 if (re.test(e.command)) next = { ...next, risky: { ...next.risky, [label]: (next.risky[label] || 0) + 1 } }
102 }
103 }
104 return next
105}
106
107export function buildNow(live, ctx = makeCtx()) {
108 const { t, doc, cfg } = ctx
109 const out = []
110 const used = live?.context?.percent
111 if (typeof used === 'number' && used >= THRESHOLDS.contextWarnPct) {
112 out.push(finding({
113 id: 'now-context', severity: used >= THRESHOLDS.contextHighPct ? 'high' : 'mid',
114 title: t('nowContextTitle', { pct: Math.round(used) }),
115 evidence: `${fmt(live.context.tokens || 0)} / ${fmt(live.context.window || 0)} tokens`,
116 action: t('nowContextAction'),
117 doc: doc('context-window'),
118 }))
119 }
120 out.push(...burnFindings(live, ctx))
121 for (const rl of live?.rateLimits || []) {
122 if (rl.percentUsed < THRESHOLDS.rateLimitWarnPct) continue
123 out.push(finding({
124 id: 'now-rate-' + rl.kind, severity: 'high',
125 title: t('nowRateTitle', { kind: rl.kind, pct: Math.round(rl.percentUsed) }),
126 evidence: rl.resetsAt ? t('nowRateResets', { at: rl.resetsAt }) : t('nowRateUnknown'),
127 action: t('nowRateAction'),
128 doc: doc('costs'),
129 }))
130 }
131 out.push(...unreviewedFindings(live, ctx))
132 for (const [label, n] of Object.entries(live?.risky || {})) {
133 out.push(finding({
134 id: 'now-risky-' + label, severity: 'mid',
135 title: t('nowRiskyTitle', { label, n }),
136 evidence: t('nowRiskyEvidence'),
137 action: t('nowRiskyAction'),
138 doc: doc('permissions'),
139 }))
140 }
141 return out
142}
143
144// The last main-loop turn spent tokens faster than the burnAlert threshold (burn.js).
145function burnFindings(live, { t, doc }) {
146 const last = live?.burn?.last
147 if (!last?.level) return []
148 return [finding({
149 id: 'now-burn', severity: last.level === 'blaze' ? 'high' : 'mid', rainbow: true,
150 title: t(last.level === 'blaze' ? 'nowBurnBlazeTitle' : 'nowBurnTitle', { rate: fmt(last.perMin) }),
151 evidence: t('nowBurnEvidence', { tokens: fmt(last.tokens), min: (last.ms / 60_000).toFixed(1), limit: fmt(last.threshold) }),
152 action: t('nowBurnAction'),
153 prompt: t('nowBurnPrompt'),
154 doc: doc('costs'),
155 })]
156}
157
158function unreviewedFindings(live, { t, cfg }) {
159 const pending = live?.unreviewed?.length || 0
160 // With no review agents configured there is nothing to recommend running.
161 if (pending < THRESHOLDS.unreviewedEdits || !cfg.reviewers.length) return []
162 const agents = cfg.reviewers.join(', ')
163 return [finding({
164 id: 'now-unreviewed', severity: 'high',
165 title: t('nowUnreviewedTitle', { n: pending }),
166 evidence: live.unreviewed.slice(0, 5).map(basename).join(', '),
167 action: t('nowUnreviewedAction', { agents }),
168 prompt: t('nowUnreviewedPrompt', { agents }),
169 details: live.unreviewed.map(basename),
170 // File names stay on this machine: the AI explanation is sent without these details.
171 localDetails: true,
172 })]
173}
174
175export function buildCost(digest, ctx = makeCtx()) {
176 const tot = totals(digest)
177 return [
178 ...lateCompactFindings(tot, ctx),
179 ...heavySessionFindings(digest, ctx),
180 ...modelMixFindings(tot, ctx),
181 ...creditFindings(tot, ctx),
182 ...longTurnFindings(digest, tot, ctx),
183 ]
184}
185
186function lateCompactFindings(tot, { t, doc }) {
187 const big = tot.compactions.filter((c) => (c.preTokens || 0) >= THRESHOLDS.compactHighTokens)
188 if (!big.length) return []
189 return [finding({
190 id: 'cost-late-compact', severity: 'high',
191 title: t('lateCompactTitle', { big: big.length, all: tot.compactions.length, limit: fmt(THRESHOLDS.compactHighTokens) }),
192 evidence: t('lateCompactEvidence', { max: fmt(Math.max(...big.map((c) => c.preTokens))) }),
193 action: t('lateCompactAction'),
194 doc: doc('model-config'),
195 details: big.map((c) => `${String(c.at || '').slice(0, 10)} ${TRIGGERS.has(c.trigger) ? c.trigger : '?'} ${fmt(c.preTokens)} tokens`),
196 })]
197}
198
199export const sessionCacheRead = (s) => sum([s.usageByModel, s.subUsage].flatMap((src) => Object.values(src || {}).map((u) => u.cacheRead || 0)))
200
201// A few very long sessions usually dominate cache reads; name them so they can be split.
202// Evidence uses project folder names and dates only, never transcript text.
203function heavySessionFindings(digest, { t, doc }) {
204 const rows = workSessions(digest).map((s) => ({ s, read: sessionCacheRead(s) })).filter((r) => r.read > 0)
205 const total = sum(rows.map((r) => r.read))
206 if (!total) return []
207 const top = [...rows].sort((a, b) => b.read - a.read).slice(0, THRESHOLDS.heavySessions)
208 const share = sum(top.map((r) => r.read)) / total
209 return [finding({
210 id: 'cost-heavy-sessions', severity: share >= THRESHOLDS.heavyShareHigh ? 'mid' : 'low',
211 title: t('heavyTitle', { n: top.length, pct: Math.round(share * 100) }),
212 evidence: t('heavyEvidence', { top: top.map((r) => `${sessionLabel(r.s)} ${fmt(r.read)}`).join(' · '), total: fmt(total) }),
213 action: t('heavyAction'),
214 doc: doc('costs'),
215 details: topSessions(digest, sessionCacheRead, (r) => t('heavyDetail', { label: sessionLabel(r.s), read: fmt(r.v), pct: pct(r.v, total) + '%', n: r.s.compactions?.length || 0 })),
216 })]
217}
218
219function modelMixFindings(tot, { t, doc }) {
220 const outByModel = Object.entries(tot.usage).map(([m, u]) => [m, u.out]).filter(([, n]) => n > 0)
221 const total = sum(outByModel.map(([, n]) => n))
222 if (!total) return []
223 const top = [...outByModel].sort((a, b) => b[1] - a[1]).slice(0, 4)
224 const cheap = sum(outByModel.filter(([m]) => /sonnet|haiku/.test(m)).map(([, n]) => n))
225 return [finding({
226 id: 'cost-model-mix', severity: cheap / total < THRESHOLDS.cheapShareLow ? 'mid' : 'low',
227 title: t('mixTitle', { pct: pct(cheap, total) }),
228 evidence: top.map(([m, n]) => `${m.replace('claude-', '')} ${pct(n, total)}%`).join(' · '),
229 action: t('mixAction'),
230 doc: doc('sub-agents'),
231 details: outByModel.map(([m, n]) => `${m.replace('claude-', '')}: ${fmt(n)} (${pct(n, total)}%)`),
232 })]
233}
234
235function creditFindings(tot, { t, doc }) {
236 const credits = tot.apiErrors.credits || 0
237 if (!credits) return []
238 return [finding({
239 id: 'cost-credits', severity: 'mid',
240 title: t('creditsTitle', { n: credits }),
241 evidence: t('creditsEvidence', { rate: tot.apiErrors.rateLimit || 0, auth: tot.apiErrors.auth || 0 }),
242 action: t('creditsAction'),
243 doc: doc('model-config'),
244 details: Object.entries(tot.apiErrors).map(([kind, n]) => t('errorCount', { kind, n })),
245 })]
246}
247
248function longTurnFindings(digest, tot, { t, doc }) {
249 const longTurns = tot.turns.filter((x) => x.maxMs >= THRESHOLDS.longTurnMs).length
250 if (!longTurns) return []
251 return [finding({
252 id: 'cost-long-turns', severity: 'low',
253 title: t('longTitle', { n: longTurns, min: THRESHOLDS.longTurnMs / 60000 }),
254 evidence: t('longEvidence', { min: Math.round(Math.max(...tot.turns.map((x) => x.maxMs)) / 60000) }),
255 action: t('longAction'),
256 doc: doc('workflows'),
257 details: topSessions(digest, (s) => s.turns?.maxMs || 0, (r) => t('longDetail', { label: sessionLabel(r.s), min: Math.round(r.v / 60000) })),
258 })]
259}
260
261export function buildImprove(digest, ctx = makeCtx()) {
262 const tot = totals(digest)
263 return [
264 ...reviewGateFindings(tot, ctx),
265 ...recallFindings(tot, digest?.history || {}, ctx),
266 ...correctionFindings(digest?.history || {}, ctx),
267 ...toolErrorFindings(digest, ctx),
268 ...groundedImprove(digest, ctx),
269 ]
270}
271
272function reviewGateFindings(tot, ctx) {
273 const { t, doc, cfg } = ctx
274 if (!cfg.reviewers.length) return []
275 const codeEdits = sum(Object.entries(tot.editExts).filter(([ext]) => CODE_EXTS.has(ext)).map(([, n]) => n))
276 const reviewerRows = Object.entries(tot.agents).filter(([a]) => isReviewer(a, cfg.reviewers)).sort((a, b) => b[1] - a[1])
277 const reviews = sum(reviewerRows.map(([, n]) => n))
278 if (!codeEdits || reviews / codeEdits >= THRESHOLDS.reviewerRatioLow) return []
279 const agents = cfg.reviewers.join(', ')
280 return [finding({
281 id: 'improve-review-gate', severity: 'high',
282 title: t('gateTitle', { edits: codeEdits, reviews }),
283 evidence: reviewerRows.map(([a, n]) => `${a.split(':').pop()} ${n}`).join(' · ') || t('gateNone'),
284 action: t('gateAction'),
285 doc: doc('hooks-guide'),
286 details: reviewGateDetails(tot, reviewerRows, ctx),
287 applyPrompt: t('gateApply', { agents }),
288 })]
289}
290
291function reviewGateDetails(tot, reviewerRows, { t, cfg }) {
292 const exts = Object.entries(tot.editExts).filter(([ext]) => CODE_EXTS.has(ext)).sort((a, b) => b[1] - a[1]).slice(0, DETAIL_ROWS)
293 // Only the configured reviewer names are shown; other agent names may carry customer names.
294 const others = sum(Object.entries(tot.agents).filter(([a]) => !isReviewer(a, cfg.reviewers)).map(([, n]) => n))
295 return [
296 ...exts.map(([ext, n]) => t('gateEdits', { ext, n })),
297 ...reviewerRows.map(([a, n]) => t('gateReviewer', { name: a.split(':').pop(), n })),
298 t('gateOthers', { n: others }),
299 ]
300}
301
302// Searches of the user's notes: MCP tools by name prefix, CLIs by the first word of a Bash command.
303function memorySearches(tot, memoryTools) {
304 const tools = sum(Object.entries(tot.tools).filter(([k]) => memoryTools.some((p) => k.startsWith(p))).map(([, n]) => n))
305 const clis = sum(Object.entries(tot.bashHeads).filter(([k]) => memoryTools.includes(k)).map(([, n]) => n))
306 return tools + clis
307}
308
309function recallFindings(tot, h, { t, doc, cfg }) {
310 // Without a configured note tool there is nothing to compare the cues against.
311 if (!cfg.memoryTools.length) return []
312 const searches = memorySearches(tot, cfg.memoryTools)
313 const cues = h.memoryCuePrompts || 0
314 if (cues <= searches) return []
315 return [finding({
316 id: 'improve-recall', severity: 'mid',
317 title: t('recallTitle', { cues, searches }),
318 evidence: t('recallEvidence'),
319 action: t('recallAction'),
320 doc: doc('hooks'),
321 })]
322}
323
324// Phrases like "try again" turn up in any long history, so a count alone is not a pattern: it must
325// also be a share of prompts. The Tips that cite redo prompts use the same test.
326export const isRedoPattern = (h) => {
327 const n = h?.correctionPrompts || 0
328 return n >= THRESHOLDS.correctionHigh && n >= (h?.prompts || 0) * THRESHOLDS.correctionShare
329}
330
331function correctionFindings(h, { t, doc }) {
332 if (!isRedoPattern(h)) return []
333 return [finding({
334 id: 'improve-corrections', severity: 'mid',
335 title: t('correctionsTitle', { n: h.correctionPrompts }),
336 evidence: t('correctionsEvidence'),
337 action: t('correctionsAction'),
338 doc: doc('best-practices'),
339 applyPrompt: t('correctionsApply'),
340 })]
341}
342
343// Errors are judged as a share of all tool calls: a heavy user meets 100 errors at a healthy rate.
344function toolErrorFindings(digest, { t, doc }) {
345 const sessions = workSessions(digest)
346 const denials = sum(sessions.map((s) => s.denials || 0))
347 const errors = sum(sessions.map((s) => s.toolErrors || 0))
348 const calls = sum(sessions.flatMap((s) => Object.values(s.tools || {})))
349 if (errors < THRESHOLDS.toolErrorsHigh || errors < calls * THRESHOLDS.toolErrorShare) return []
350 return [finding({
351 id: 'improve-tool-errors', severity: 'low',
352 title: t('errorsTitle', { errors, denials }),
353 evidence: t('errorsEvidence'),
354 action: t('errorsAction'),
355 doc: doc('memory'),
356 details: topSessions(digest, (s) => s.toolErrors || 0, (r) => t('errorsDetail', { label: sessionLabel(r.s), n: r.v })),
357 })]
358}
359
360export function buildStandup(digest, days, nowMs, gitLogs = {}, ctx = makeCtx()) {
361 const since = nowMs - days * 24 * 3600 * 1000
362 const byProject = new Map()
363 for (const s of workSessions(digest)) {
364 if (!s.end || Date.parse(s.end) < since) continue
365 // Sessions with neither a title nor a typed prompt (e.g. `claude -p /cmd`) carry no work to report.
366 if (!s.title && !s.firstPrompt) continue
367 const key = s.project || '(unknown)'
368 const row = byProject.get(key) || { project: key, sessions: [], files: new Set() }
369 row.sessions.push({ title: s.title || s.firstPrompt || ctx.t('untitled'), fromPrompt: !s.title, away: s.away?.at(-1) || null, end: s.end })
370 for (const f of s.editedFiles || []) row.files.add(basename(f))
371 byProject.set(key, row)
372 }
373 return [...byProject.values()]
374 .map((r) => ({ ...r, files: [...r.files].slice(0, 8), commits: gitLogs[r.project] || [] }))
375 .sort((a, b) => (b.sessions.at(-1)?.end || '').localeCompare(a.sessions.at(-1)?.end || ''))
376}
377
378export function rankFindings(list, dismissed = []) {
379 const order = { high: 0, mid: 1, low: 2 }
380 const hidden = new Set(dismissed)
381 return list.filter((f) => !hidden.has(f.id)).sort((a, b) => order[a.severity] - order[b.severity])
382}
383hooks/i18n.js 63 lines1// Language, strings and the user-tunable rule settings, bundled into the ctx every rule takes.
2// Pure functions, no mods API.
3
4import { EN } from './strings-en.js'
5import { JA } from './strings-ja.js'
6
7const DICTS = { en: EN, ja: JA }
8export const LANGUAGE_OPTIONS = ['auto', 'en', 'ja']
9
10// `auto` follows Claude Code's own `language` setting ("Japanese", "日本語", "ja", ...).
11export function resolveLang(option, settingsLanguage) {
12 if (option === 'en' || option === 'ja') return option
13 const s = String(settingsLanguage || '').toLowerCase()
14 // "ja", "ja-JP", "Japanese", "日本語" (but not "Javanese").
15 return /^ja([-_]|$)/.test(s) || s.includes('japan') || s.includes('日本') ? 'ja' : 'en'
16}
17
18export function makeT(lang) {
19 const dict = DICTS[lang] || EN
20 return (key, params = {}) => {
21 const entry = key in dict ? dict[key] : EN[key]
22 if (entry === undefined) return key
23 return typeof entry === 'function' ? entry(params) : entry
24 }
25}
26
27export const docUrl = (lang, slug) => `https://code.claude.com/docs/${lang === 'ja' ? 'ja' : 'en'}/${slug}`
28
29const list = (value) => String(value ?? '').split(',').map((s) => s.trim()).filter(Boolean)
30
31// Defaults suit anyone; people with their own agents or note tools extend them in /config.
32export const RULE_DEFAULTS = Object.freeze({
33 // Claude Code ships no review agent, so the review checks stay off until you name yours.
34 reviewerAgents: '',
35 memoryTools: '',
36 memoryCueWords: '',
37 extraRiskyCommands: '',
38})
39
40// Built-in words that mean "this needs earlier context", used when memoryCueWords is empty.
41export const DEFAULT_MEMORY_CUES = ['前回', '以前', '覚えて', 'last time', 'previously', 'remember when']
42
43export function ruleConfig(options = {}) {
44 const get = (k) => (typeof options[k] === 'string' ? options[k] : RULE_DEFAULTS[k])
45 const cues = list(get('memoryCueWords'))
46 return Object.freeze({
47 reviewers: Object.freeze(list(get('reviewerAgents'))),
48 memoryTools: Object.freeze(list(get('memoryTools'))),
49 memoryCues: Object.freeze(cues.length ? cues : DEFAULT_MEMORY_CUES),
50 extraRisky: Object.freeze(list(get('extraRiskyCommands'))),
51 })
52}
53
54// Facts from Claude Code's own settings that decide whether a tip applies.
55export function localFacts(settings = {}) {
56 const perModel = Object.values(settings?.modelSettings || {}).some((m) => m && typeof m === 'object' && m.effortLevel)
57 return Object.freeze({ effortConfigured: Boolean(settings?.effortLevel) || perModel })
58}
59
60export function makeCtx(lang = 'en', cfg = ruleConfig(), local = localFacts()) {
61 return Object.freeze({ lang, t: makeT(lang), doc: (slug) => docUrl(lang, slug), cfg, local })
62}
63hooks/catalog.js 99 lines1// Claude Code features worth knowing, each with a usage check against the digest.
2// Doc slugs were taken from https://code.claude.com/docs/llms.txt (2026-10-03); the same slug
3// exists under /docs/en/ and /docs/ja/. A check returns null when the tip does not apply, or
4// the params for its evidence string when it does.
5
6import { isRedoPattern, totals } from './rules.js'
7import { makeCtx } from './i18n.js'
8import { ownAssetTips } from './grounded.js'
9
10const slash = (d, cmd) => d?.history?.slash?.[cmd] || 0
11const tool = (tot, name) => tot.tools[name] || 0
12// null when no permission-mode records exist, so tips don't fire on missing data.
13const permRatio = (tot, mode) => {
14 const all = Object.values(tot.permModes).reduce((a, b) => a + b, 0)
15 return all ? (tot.permModes[mode] || 0) / all : null
16}
17const agents = (tot) => tool(tot, 'Agent') + tool(tot, 'Task') + tool(tot, 'Workflow')
18const prompts = (d) => d.history?.prompts || 0
19const redo = (d) => d.history?.correctionPrompts || 0
20
21// Checks take (digest, totals, local): local holds facts read from Claude Code's settings (i18n.js).
22// Ordered by expected payoff; `key` names the tipXxxTitle / Concept / Evidence strings.
23export const CATALOG = [
24 {
25 id: 'tip-loop', key: 'tipLoop', slug: 'scheduled-tasks',
26 check: (d) => ((d.history?.resumePrompts || 0) >= 10 && slash(d, '/loop') < 3 ? { n: d.history.resumePrompts, loop: slash(d, '/loop') } : null),
27 },
28 {
29 id: 'tip-context', key: 'tipContext', slug: 'context-window',
30 check: (d, tot) => (slash(d, '/context') === 0 && tot.compactions.length >= 3 ? { n: tot.compactions.length } : null),
31 },
32 {
33 id: 'tip-rewind', key: 'tipRewind', slug: 'checkpointing',
34 check: (d) => (slash(d, '/rewind') === 0 && isRedoPattern(d.history) ? { n: redo(d) } : null),
35 },
36 {
37 id: 'tip-plan-mode', key: 'tipPlan', slug: 'permission-modes',
38 check: (d, tot) => {
39 const r = permRatio(tot, 'plan')
40 return r !== null && r < 0.03 && isRedoPattern(d.history) ? { pct: Math.round(r * 100), n: redo(d) } : null
41 },
42 },
43 {
44 id: 'tip-effort', key: 'tipEffort', slug: 'model-config',
45 // Effort set in settings (effortLevel, or per model in modelSettings) is already in use.
46 check: (d, tot, local) => (!local.effortConfigured && slash(d, '/model') >= 30 && slash(d, '/effort') < 10 ? { model: slash(d, '/model'), effort: slash(d, '/effort') } : null),
47 },
48 {
49 id: 'tip-hooks-checks', key: 'tipHooks', slug: 'hooks-guide',
50 check: (d, tot) => {
51 const r = permRatio(tot, 'auto')
52 return r !== null && r >= 0.8 ? { pct: Math.round(r * 100) } : null
53 },
54 },
55 {
56 id: 'tip-worktree', key: 'tipWorktree', slug: 'worktrees',
57 check: (d, tot) => (tool(tot, 'EnterWorktree') === 0 && agents(tot) >= 30 ? { n: agents(tot) } : null),
58 },
59 {
60 id: 'tip-skills', key: 'tipSkills', slug: 'skills',
61 check: (d, tot) => (tool(tot, 'Skill') < 20 && prompts(d) >= 300 ? { n: tool(tot, 'Skill'), prompts: prompts(d) } : null),
62 },
63 {
64 id: 'tip-btw', key: 'tipBtw', slug: 'interactive-mode',
65 check: (d) => (slash(d, '/btw') < 5 && prompts(d) >= 300 ? { n: slash(d, '/btw'), prompts: prompts(d) } : null),
66 },
67 {
68 id: 'tip-output-style', key: 'tipStyle', slug: 'output-styles',
69 check: (d) => (slash(d, '/output-style') === 0 && prompts(d) >= 500 ? {} : null),
70 },
71 {
72 // Claude Code's own report, written by a model over recent sessions: the mod's counts complement
73 // it. Last, so it never takes the place of a specific tip.
74 id: 'tip-insights', key: 'tipInsights', slug: 'commands',
75 check: (d) => (slash(d, '/insights') === 0 && prompts(d) >= 300 ? { prompts: prompts(d) } : null),
76 },
77]
78
79export const MAX_TIPS = 5
80
81export function buildTips(digest, ctx = makeCtx(), catalog = CATALOG, limit = MAX_TIPS) {
82 const { t, doc } = ctx
83 const tot = totals(digest)
84 const out = []
85 for (const item of catalog) {
86 let hit = null
87 try {
88 hit = item.check(digest || {}, tot, ctx.local || {})
89 } catch {
90 // A rule that cannot read this digest simply does not apply.
91 hit = null
92 }
93 if (hit) out.push({ id: item.id, severity: 'low', title: t(item.key + 'Title'), evidence: t(item.key + 'Evidence', hit), action: t(item.key + 'Concept'), doc: doc(item.slug), details: [] })
94 }
95 // The user's own agents and skills lead, outside the limit, so dismissing them leaves the
96 // catalog's tips whole.
97 return [...(catalog === CATALOG ? ownAssetTips(digest, ctx) : []), ...out.slice(0, limit)]
98}
99hooks/view.js 388 lines1// Pane rendering. Receives the element functions from $.ui.resolve(e), plain callbacks from
2// register.js and the strings function `model.t`, so this file never touches the mods API.
3// One visual language for both pane styles: `rich` adds stats and charts (rich-view.js) above
4// the same list; nothing else changes between them.
5
6import { CREDIT_MODELS, EFFORT_OPTIONS, MODEL_OPTIONS } from './ai-config.js'
7import { SETTINGS_SPEC } from './settings-spec.js'
8import { richCharts } from './rich-view.js'
9import { fmt } from './rules.js'
10import { GLYPH, glyphLine, heading, labelled, meta, rainbowText, rule, severityOf, textButton } from './theme.js'
11
12export const TABS = Object.freeze([
13 { id: 'now', label: 'Now', hotkey: '1' },
14 { id: 'cost', label: 'Cost', hotkey: '2' },
15 { id: 'tips', label: 'Tips', hotkey: '3' },
16 { id: 'standup', label: 'Standup', hotkey: '4' },
17 { id: 'improve', label: 'Improve', hotkey: '5' },
18 { id: 'settings', label: 'Settings', hotkey: '6' },
19])
20
21// The Settings tab's groups, in order; together they hold every option once (tests check).
22export const SETTING_GROUPS = Object.freeze([
23 { id: 'display', keys: ['language', 'paneStyle'] },
24 { id: 'ai', keys: ['aiModel', 'aiEffort', 'autoExplain', 'cacheExplanations'] },
25 { id: 'burn', keys: ['burnAlert', 'burnEffect'] },
26 { id: 'rules', keys: ['reviewerAgents', 'memoryTools', 'memoryCueWords', 'extraRiskyCommands'] },
27 { id: 'data', keys: ['excludeProjects', 'retentionDays'] },
28])
29
30const AI_TABS = new Set(['cost', 'tips', 'standup', 'improve'])
31// Titles, recaps, commit subjects and file names come from transcripts: drop control characters.
32// Bidi overrides and line/paragraph separators can disguise text, so they go too.
33const CONTROL_CHARS = /[\u0000-\u0008\u000b-\u001f\u007f-\u009f\u2028\u2029\u202a-\u202e\u2066-\u2069]/g
34const DETAIL_MAX = 12
35const INDENT = 2
36const LABEL_COLS = 8
37const MINUTE_MS = 60_000
38const HOUR_MS = 60 * MINUTE_MS
39const DAY_MS = 24 * HOUR_MS
40const clean = (text) => String(text ?? '').replace(CONTROL_CHARS, '')
41const folder = (p) => String(p || '').split(/[\\/]/).filter(Boolean).slice(-2).join('/')
42const isRich = (model) => model.settings.paneStyle === 'rich'
43const indent = (el, children) => el.Box({ flexDirection: 'column', paddingLeft: INDENT, children })
44// A hairline is cell graphics: only the terminal draws it true to the pane's width; elsewhere the
45// row gap alone separates the sections.
46const hairline = (el, model) => (model.surface === 'terminal' ? rule(el, model.cols) : null)
47
48export function renderPane(el, model, h) {
49 const { Box } = el
50 if (model.detail) return renderDetail(el, model, h)
51 return Box({
52 flexDirection: 'column',
53 rowGap: 1,
54 children: [header(el, model, h), ...charts(el, model), ...body(el, model, h), aiBlock(el, model, h)].filter(Boolean),
55 })
56}
57
58// The band above the prompt: the burn pace in rainbow letters, its figures, and two actions.
59export function renderBand(el, { t, last, effect }, h) {
60 const { Box } = el
61 return Box({
62 flexDirection: 'row',
63 columnGap: 2,
64 flexWrap: 'wrap',
65 children: [
66 rainbowText(el, { key: 'burn-band', text: t(last.level === 'blaze' ? 'bandBlaze' : 'bandHot'), effect }),
67 meta(el, t('bandEvidence', { rate: fmt(last.perMin), limit: fmt(last.threshold) }), { wrap: 'truncate-end' }),
68 textButton(el, { key: 'burn-detail', label: t('bandDetail'), onPress: () => h.onBurnDetail() }),
69 textButton(el, { key: 'burn-hide', label: t('bandHide'), tone: 'dim', onPress: () => h.onBurnHide() }),
70 ],
71 })
72}
73
74function charts(el, model) {
75 return isRich(model) ? richCharts(el, { ...model, clean }) : []
76}
77
78// Tabs, the index status with its two controls, and a rule under them.
79function header(el, model, h) {
80 const { Box } = el
81 return Box({ flexDirection: 'column', children: [tabRow(el, model, h), statusLine(el, model, h), hairline(el, model)].filter(Boolean) })
82}
83
84// The open tab reads bold at full strength; the others dim. A count follows a tab that has items.
85function tabRow(el, model, h) {
86 const { Box, Button, Text } = el
87 return Box({
88 flexDirection: 'row',
89 columnGap: 2,
90 flexWrap: 'wrap',
91 children: TABS.map((tab) => {
92 const active = model.tab === tab.id
93 const n = model.lists[tab.id]?.length
94 return Button({
95 key: 'tab-' + tab.id,
96 hotkey: tab.hotkey,
97 plain: true,
98 ...(active ? {} : { dimColor: true }),
99 onPress: () => h.onTab(tab.id),
100 children: [Text({ bold: active, children: [tab.label] }), ...(n ? [Text({ dimColor: true, children: [` ${n}`] })] : [])],
101 })
102 }),
103 })
104}
105
106// "5 min ago" for a recent index, the date and time for an older one.
107export function ago(t, nowMs, at) {
108 const iso = String(at ?? '')
109 const ms = nowMs - Date.parse(iso)
110 // A stamp up to a minute ahead is clock skew between the indexer and the engine, not the future.
111 if (!Number.isFinite(ms) || ms < -MINUTE_MS) return iso.slice(0, 16).replace('T', ' ')
112 if (ms < MINUTE_MS) return t('agoNow')
113 if (ms < HOUR_MS) return t('agoMin', { n: Math.floor(ms / MINUTE_MS) })
114 if (ms < DAY_MS) return t('agoHour', { n: Math.floor(ms / HOUR_MS) })
115 return iso.slice(0, 16).replace('T', ' ')
116}
117
118function statusText(model) {
119 const { t, status: s } = model
120 if (s.error) return [t('indexError', { error: s.error }), 'error']
121 if (s.indexing) return [t('indexing'), 'warning']
122 if (s.generatedAt) return [t('indexed', { at: ago(t, model.nowMs, s.generatedAt), n: s.sessions }), null]
123 return [t('notIndexed'), null]
124}
125
126function statusLine(el, model, h) {
127 const { Box, Text } = el
128 const { t } = model
129 const [text, color] = statusText(model)
130 const rich = isRich(model)
131 return Box({
132 flexDirection: 'row',
133 columnGap: 2,
134 flexWrap: 'wrap',
135 justifyContent: 'space-between',
136 children: [
137 Box({
138 flexDirection: 'column',
139 children: [
140 Text({ ...(color ? { color } : { dimColor: true }), wrap: 'truncate-end', children: [clean(text)] }),
141 model.versionWarning ? Text({ color: 'warning', wrap: 'truncate-end', children: [t('oldVersion', model.versionWarning)] }) : null,
142 model.status.unreadable ? Text({ color: 'warning', children: [t('formatWarning', { n: model.status.unreadable })] }) : null,
143 ].filter(Boolean),
144 }),
145 Box({
146 flexDirection: 'row',
147 columnGap: 2,
148 children: [
149 textButton(el, { key: 'refresh', label: t('refresh'), hotkey: 'r', tone: 'dim', onPress: () => h.onRefresh() }),
150 textButton(el, { key: 'pane-style', label: t(rich ? 'styleSimple' : 'styleRich'), hotkey: 'v', tone: 'dim', onPress: () => h.onSetting('paneStyle', rich ? 'simple' : 'rich') }),
151 ],
152 }),
153 ],
154 })
155}
156
157function body(el, model, h) {
158 if (model.tab === 'standup') return standup(el, model, h)
159 if (model.tab === 'settings') return settingsTab(el, model, h)
160 const list = model.lists[model.tab] || []
161 const cards = list.length ? list.map((f) => findingCard(el, model.t, f, h, model.burnEffect)) : [emptyState(el, model)]
162 const head = isRich(model) && list.length ? [heading(el, model.t('findingsHead'), model.t('findingsCount', { n: list.length }))] : []
163 return [...scopeNote(el, model), ...head, ...cards, ...officialNote(el, model)]
164}
165
166// The history tabs say what they cover; Claude Code keeps transcripts for cleanupPeriodDays.
167function scopeNote(el, model) {
168 if (!['cost', 'tips', 'improve'].includes(model.tab) || !model.coverage) return []
169 return [meta(el, model.t('coverage', model.coverage))]
170}
171
172// Live numbers are Claude Code's own: Now points to them rather than repeating them.
173function officialNote(el, model) {
174 return model.tab === 'now' ? [meta(el, model.t('officialNow'))] : []
175}
176
177function emptyState(el, model) {
178 const { t } = model
179 if (model.tab === 'now') return glyphLine(el, GLYPH.check, t('emptyNow'), { color: 'success' }, { color: 'success' })
180 return meta(el, t('emptyList'))
181}
182
183// A finding: a severity dot and the title, then the severity word with the evidence, the next
184// step, and its actions. The dot carries the color; the word carries the meaning. A rainbow
185// finding (the burn pace) draws its title in the burnEffect.
186function findingHead(el, t, f, effect) {
187 const { Box, Text } = el
188 const sev = severityOf(f)
189 const title = f.rainbow ? rainbowText(el, { key: 'rainbow-' + f.id, text: clean(f.title), effect }) : Text({ bold: true, children: [clean(f.title)] })
190 return Box({
191 flexDirection: 'column',
192 children: [
193 Box({ flexDirection: 'row', columnGap: 1, children: [Text({ color: sev.color, children: [sev.glyph] }), title] }),
194 indent(el, [meta(el, [t(sev.word), clean(f.evidence)])]),
195 ],
196 })
197}
198
199function docsLink(el, t, f) {
200 return f.doc ? el.Link({ href: f.doc, label: `${t('docs')} ${GLYPH.external}` }) : null
201}
202
203function findingCard(el, t, f, h, effect) {
204 const { Box } = el
205 const actions = [
206 textButton(el, { key: 'ask-' + f.id, label: t('ask'), onPress: () => h.onAsk(f) }),
207 f.applyPrompt ? textButton(el, { key: 'apply-' + f.id, label: t('apply'), onPress: () => h.onApply(f) }) : null,
208 textButton(el, { key: 'hide-' + f.id, label: t('dismiss'), tone: 'dim', onPress: () => h.onDismiss(f) }),
209 docsLink(el, t, f),
210 ].filter(Boolean)
211 return Box({
212 key: 'card-' + f.id,
213 flexDirection: 'column',
214 children: [
215 findingHead(el, t, f, effect),
216 indent(el, [glyphLine(el, GLYPH.arrow, clean(f.action), {}, { dimColor: true }), Box({ flexDirection: 'row', columnGap: 2, flexWrap: 'wrap', children: actions })]),
217 ],
218 })
219}
220
221function standupHeader(el, model, h) {
222 const { Box } = el
223 return Box({
224 flexDirection: 'row',
225 columnGap: 2,
226 children: [1, 3, 7].map((d) => textButton(el, { key: 'days-' + d, label: model.t('days', { d }), tone: model.days === d ? 'plain' : 'dim', onPress: () => h.onDays(d) })),
227 })
228}
229
230function standupRow(el, model, row) {
231 const { Box } = el
232 const { t } = model
233 const lines = [
234 ...row.sessions.slice(-4).map((s) => glyphLine(el, GLYPH.sep, clean(s.title), {}, { dimColor: true })),
235 ...row.sessions.filter((s) => s.away).slice(-1).map((s) => labelled(el, t('recap'), clean(s.away), LABEL_COLS, { dimColor: true })),
236 row.commits.length ? labelled(el, t('commits'), clean(row.commits.slice(0, 5).join(' / ')), LABEL_COLS, { dimColor: true }) : null,
237 row.files.length ? labelled(el, t('files'), clean(row.files.join(', ')), LABEL_COLS, { dimColor: true, wrap: 'truncate-end' }) : null,
238 ].filter(Boolean)
239 const head = heading(el, clean(folder(row.project)), t('sessionCount', { n: row.sessions.length }))
240 return Box({ key: 'su-' + row.project, flexDirection: 'column', children: [head, indent(el, lines)] })
241}
242
243function standup(el, model, h) {
244 const header = standupHeader(el, model, h)
245 if (!model.standup.length) return [header, meta(el, model.t('noSessions', { d: model.days }))]
246 return [header, ...model.standup.map((row) => standupRow(el, model, row))]
247}
248
249function aiBlock(el, model, h) {
250 if (!AI_TABS.has(model.tab)) return null
251 const { Box, Markdown, Text } = el
252 const { t } = model
253 const ai = model.ai[model.tab]
254 const children = [
255 hairline(el, model),
256 textButton(el, { key: 'ai-' + model.tab, label: ai?.loading ? t('summarizing') : t('summarize', { model: model.settings.model }), hotkey: 'a', onPress: () => h.onAi(model.tab) }),
257 ]
258 if (ai?.text) children.push(Markdown({ key: 'ai-text-' + model.tab, text: clean(ai.text).slice(0, 9000) }))
259 if (ai?.error) children.push(Text({ color: 'error', children: [clean(t('summaryFailed', { error: ai.error }))] }))
260 children.push(meta(el, t('summaryNote')))
261 return Box({ flexDirection: 'column', children: children.filter(Boolean) })
262}
263
264// Details: the finding's numbers, the rule's breakdown and an AI explanation, all inside the pane.
265function renderDetail(el, model, h) {
266 const { Box, Code } = el
267 const { t } = model
268 const f = model.detail
269 const details = f.details || []
270 const shown = details.slice(0, DETAIL_MAX).map((d) => glyphLine(el, GLYPH.sep, clean(d), {}, { dimColor: true }))
271 if (details.length > DETAIL_MAX) shown.push(meta(el, t('more', { n: details.length - DETAIL_MAX })))
272 return Box({
273 flexDirection: 'column',
274 rowGap: 1,
275 children: [
276 Box({ flexDirection: 'column', children: [detailActions(el, t, f, h), hairline(el, model)].filter(Boolean) }),
277 findingHead(el, t, f, model.burnEffect),
278 f.isResolved ? glyphLine(el, GLYPH.check, t('resolved'), { color: 'success' }, { color: 'success' }) : null,
279 shown.length ? Box({ flexDirection: 'column', children: [heading(el, t('breakdown')), indent(el, shown)] }) : null,
280 Box({ flexDirection: 'column', children: [heading(el, t('actionHead')), indent(el, [glyphLine(el, GLYPH.arrow, clean(f.action), { bold: true }, { dimColor: true })])] }),
281 Box({ flexDirection: 'column', children: [heading(el, t('promptHead'), t('promptHint')), Code({ source: clean(f.copyText) })] }),
282 explainBlock(el, model, h),
283 ].filter(Boolean),
284 })
285}
286
287function detailActions(el, t, f, h) {
288 const { Box } = el
289 return Box({
290 flexDirection: 'row',
291 columnGap: 2,
292 flexWrap: 'wrap',
293 children: [
294 textButton(el, { key: 'back', label: t('back'), hotkey: 'b', tone: 'plain', onPress: () => h.onBack() }),
295 textButton(el, { key: 'copy-' + f.id, label: t('copy'), hotkey: 'c', tone: 'dim', onPress: (press) => h.onCopy(f.copyText, press) }),
296 f.applyPrompt ? textButton(el, { key: 'apply-' + f.id, label: t('applyChat'), onPress: () => h.onApply(f) }) : null,
297 docsLink(el, t, f),
298 ].filter(Boolean),
299 })
300}
301
302function explainBody(el, model) {
303 const { Text, Markdown } = el
304 const { t } = model
305 const ex = model.explain
306 if (ex?.loading) return [meta(el, t('explaining', { model: ex.model }))]
307 if (ex?.error) return [Text({ color: 'error', children: [clean(t('explainFailed', { error: ex.error }))] })]
308 if (ex?.text) return [Markdown({ key: 'explain-' + model.detail.id, text: clean(ex.text).slice(0, 9000) }), meta(el, usageLine(t, ex))]
309 return [meta(el, generateHint(t, model.settings))]
310}
311
312function explainBlock(el, model, h) {
313 const { Box } = el
314 const { t } = model
315 const f = model.detail
316 const again = textButton(el, { key: 'explain-again', label: t(model.explain?.text ? 'regenerate' : 'generate'), hotkey: 'g', tone: 'dim', onPress: () => h.onExplainAgain(f) })
317 return Box({
318 flexDirection: 'column',
319 children: [heading(el, t('explainHead'), [again]), indent(el, [...explainBody(el, model), settingsRow(el, model, h), meta(el, t(f.localDetails ? 'sendLocal' : 'sendDetail'))])],
320 })
321}
322
323// Why there is no explanation yet, so the hint never claims a setting that is not in effect.
324function generateHint(t, settings) {
325 if (!settings.autoExplain) return t('hintOff')
326 if (CREDIT_MODELS.has(settings.model)) return t('hintCredit', { model: settings.model })
327 return t('hint')
328}
329
330function usageLine(t, ex) {
331 if (ex.isCached) return t('cached', { model: ex.model })
332 return ex.tokens ? t('usage', { model: ex.model, in: ex.tokens.in, out: ex.tokens.out }) : ex.model || ''
333}
334
335// Model and effort pickers; a change is saved to this plugin's /config fields.
336function settingsRow(el, model, h) {
337 const { Box, Select } = el
338 const { t, settings, aiUsage } = model
339 return Box({
340 flexDirection: 'column',
341 children: [
342 Box({
343 flexDirection: 'row',
344 columnGap: 2,
345 flexWrap: 'wrap',
346 children: [
347 Select({ key: 'ai-model', label: t('modelLabel'), value: settings.model, options: MODEL_OPTIONS.map((m) => ({ value: m, label: CREDIT_MODELS.has(m) ? t('creditLabel', { model: m }) : m })), onSelect: (v) => h.onSetting('aiModel', v) }),
348 Select({ key: 'ai-effort', label: t('effortLabel'), value: settings.effort, options: EFFORT_OPTIONS.map((x) => ({ value: x, label: x })), onSelect: (v) => h.onSetting('aiEffort', v) }),
349 ],
350 }),
351 meta(el, t('sessionUsage', aiUsage)),
352 ],
353 })
354}
355
356// Settings tab: the options in four groups, one control each; a change is saved through h.onSetting.
357const SPEC_BY_KEY = Object.fromEntries(SETTINGS_SPEC.map((s) => [s.key, s]))
358
359function settingsTab(el, model, h) {
360 const { Box } = el
361 const { t } = model
362 return [
363 meta(el, t('settingsIntro')),
364 ...SETTING_GROUPS.map((g) => Box({
365 key: 'group-' + g.id,
366 flexDirection: 'column',
367 children: [
368 heading(el, t('group_' + g.id)),
369 ...g.keys.map((key) => indent(el, [settingControl(el, t, SPEC_BY_KEY[key], model.config[key], h), indent(el, [meta(el, t('cfgHelp_' + key))])])),
370 ],
371 })),
372 ]
373}
374
375function settingControl(el, t, spec, value, h) {
376 const { Select, Input } = el
377 const key = 'set-' + spec.key
378 const label = t('cfg_' + spec.key)
379 const save = (v) => h.onSetting(spec.key, v)
380 if (spec.kind === 'select') {
381 return Select({ key, label, value: String(value), options: spec.options.map((o) => ({ value: o, label: CREDIT_MODELS.has(o) ? t('creditLabel', { model: o }) : o })), onSelect: save })
382 }
383 if (spec.kind === 'bool') {
384 return Select({ key, label, value: value ? 'on' : 'off', options: [{ value: 'on', label: t('settingOn') }, { value: 'off', label: t('settingOff') }], onSelect: save })
385 }
386 return Input({ key, label, value: clean(value), submitLabel: t('settingSave'), onSubmit: save })
387}
388hooks/privacy.js 49 lines1// What may leave the machine, in one place. Pure functions, no mods API.
2// Contract: model payloads carry counts, model names, dates and project folder basenames —
3// never prompt text, paths or file names. Builders only emit counts and fixed wording; this
4// filter is a backstop that withholds anything that looks like a path, URL or control text.
5
6import { makeT } from './i18n.js'
7
8const MAX_SHARED_LINE = 160
9// A shareable line has no path-like token, no control characters and a bounded length.
10const CONTROL = /[\u0000-\u001f\u007f-\u009f\u2028\u2029\u202a-\u202e\u2066-\u2069]/
11// Path-like: a token with two or more "/", one starting with ~/ ./ ../ or /x/, a slash token
12// ending in a file extension (src/a.py, /x.txt), a URL scheme, a fullwidth slash or any backslash.
13const PATH_LIKE = /(^|\s)(~|\.{1,2})?\/[^\s/]+\/|[^\s/]+\/[^\s/]+\/|(^|\s)(~|\.{1,2})\/|\S*\/[^\s/]+\.[A-Za-z0-9]{1,6}(?=\s|$)|:\/\/|\uff0f|\\/
14const isSafeText = (s) => typeof s === 'string' && !CONTROL.test(s) && !PATH_LIKE.test(s)
15export const isShareableLine = (s) => isSafeText(s) && s.length <= MAX_SHARED_LINE
16
17// The finding as the model may see it. localDetails findings name files: send only a count.
18export function shareableFinding(f, t = makeT('en')) {
19 const details = Array.isArray(f.details) ? f.details : []
20 const local = f.localDetails === true
21 // A finding that names local things (a command, the user's own agents) supplies its own wording
22 // for the model: sharedTitle and sharedAction.
23 const title = f.sharedTitle ?? f.title
24 const action = f.sharedAction ?? f.action
25 return {
26 title: isShareableLine(title) ? title : t('withheld'),
27 evidence: local ? t('localEvidence', { n: details.length }) : isShareableLine(f.evidence) ? f.evidence : t('withheld'),
28 // Actions are fixed wording and may run long; they get the same path and control check.
29 action: isSafeText(action) ? action : t('withheld'),
30 severity: f.severity,
31 topic: typeof f.doc === 'string' ? f.doc.split('/').filter(Boolean).pop() : null,
32 details: local ? [] : details.filter(isShareableLine),
33 }
34}
35
36// Every finding offers a prompt to copy; rule-specific prompts win.
37export function copyText(f, t = makeT('en')) {
38 return f.prompt || t('copyFallback', { title: f.title, evidence: f.evidence, doc: f.doc || t('none') })
39}
40
41// Model output is shown as Markdown; drop links of any scheme and reference-style links.
42export function stripLinks(text) {
43 return String(text)
44 .replace(/^\s*\[[^\]]+\]:\s*\S+.*$/gm, '')
45 .replace(/!?\[([^\]]*)\]\([^)]*\)/g, '$1')
46 .replace(/!?\[([^\]]*)\]\[[^\]]*\]/g, '$1')
47 .replace(/<?\b(?:[a-z][a-z0-9+.-]*:\/\/|mailto:|javascript:|data:|file:)[^\s>)]*>?/gi, '[link removed]')
48}
49hooks/settings-spec.js 89 lines1// The Settings tab: every userConfig option, its control, and how a typed value is checked.
2// Pure functions, no mods API. Keys and defaults must match .claude-plugin/plugin.json.
3
4import { EFFORT_OPTIONS, MODEL_OPTIONS, PANE_STYLES, settingsField } from './ai-config.js'
5import { LANGUAGE_OPTIONS } from './i18n.js'
6import { BURN, BURN_EFFECTS } from './burn.js'
7
8const MAX_RETENTION_DAYS = 3650
9const MAX_TEXT = 2000
10// Same characters view.js strips for display: controls, line/paragraph separators, bidi overrides.
11const CONTROL = /[\u0000-\u001f\u007f-\u009f\u2028\u2029\u202a-\u202e\u2066-\u2069]/
12
13// kind: 'select' (fixed options) | 'bool' | 'list' (comma-separated text) | 'number'
14export const SETTINGS_SPEC = Object.freeze([
15 { key: 'language', kind: 'select', options: LANGUAGE_OPTIONS, default: 'auto' },
16 { key: 'paneStyle', kind: 'select', options: PANE_STYLES, default: 'simple' },
17 { key: 'aiModel', kind: 'select', options: MODEL_OPTIONS, default: 'haiku' },
18 { key: 'aiEffort', kind: 'select', options: EFFORT_OPTIONS, default: 'low' },
19 { key: 'autoExplain', kind: 'bool', default: true },
20 { key: 'cacheExplanations', kind: 'bool', default: true },
21 { key: 'reviewerAgents', kind: 'list', default: '' },
22 { key: 'memoryTools', kind: 'list', default: '' },
23 { key: 'memoryCueWords', kind: 'list', default: '' },
24 { key: 'extraRiskyCommands', kind: 'list', default: '' },
25 { key: 'excludeProjects', kind: 'list', default: '' },
26 { key: 'retentionDays', kind: 'number', default: 0, min: 0, max: MAX_RETENTION_DAYS },
27 { key: 'burnAlert', kind: 'number', default: BURN.defaultPerMin, min: 0, max: BURN.maxPerMin },
28 { key: 'burnEffect', kind: 'select', options: BURN_EFFECTS, default: 'rainbow' },
29])
30
31export const SETTING_KEYS = Object.freeze(SETTINGS_SPEC.map((s) => s.key))
32
33// A comma- or newline-separated option as entries, the way the mod reads it everywhere.
34export const listEntries = (v) => String(v ?? '').split(/[,\n]/).map((s) => s.trim()).filter(Boolean)
35const byKey = Object.fromEntries(SETTINGS_SPEC.map((s) => [s.key, s]))
36
37// The options the mod was loaded with, defaults filled in for anything unset or unusable
38// (a hand-edited settings.json may hold a model that is not offered, or "false" as a string).
39export function currentValues(options = {}) {
40 return Object.freeze(Object.fromEntries(SETTINGS_SPEC.map((s) => [s.key, normalized(s, options[s.key])])))
41}
42
43function normalized(spec, v) {
44 if (v === undefined || v === null) return spec.default
45 if (spec.kind === 'select') return spec.options.includes(v) ? v : spec.default
46 if (spec.kind === 'bool') return v === true || v === 'true' ? true : v === false || v === 'false' ? false : spec.default
47 // Whole days, rounded down like the mod applies them (register.js clampDays).
48 if (spec.kind === 'number') {
49 const n = Math.floor(Number(v))
50 return Number.isFinite(n) && n >= spec.min && n <= spec.max ? n : spec.default
51 }
52 return String(v)
53}
54
55// What the user picked or typed -> the value /config stores, or an error key for the strings.
56export function parseSetting(key, raw) {
57 const spec = byKey[key]
58 if (!spec) return { error: 'settingUnknown' }
59 if (spec.kind === 'select') return spec.options.includes(raw) ? { value: raw } : { error: 'settingInvalid' }
60 if (spec.kind === 'bool') return raw === 'on' || raw === true ? { value: true } : raw === 'off' || raw === false ? { value: false } : { error: 'settingInvalid' }
61 if (spec.kind === 'number') {
62 // NFKC turns full-width digits typed through an IME (30) into 30.
63 const text = String(raw ?? '').normalize('NFKC').trim()
64 const n = Number(text)
65 if (!/^\d+$/.test(text) || n < spec.min || n > spec.max) return { error: 'settingRange', params: { min: spec.min, max: spec.max } }
66 return { value: n }
67 }
68 // list: comma or newline separated; trimmed, empty entries dropped, no control characters.
69 // Newlines (including Windows \r\n) separate entries like commas do.
70 const text = String(raw ?? '').replace(/\r\n?/g, '\n')
71 if (text.length > MAX_TEXT || CONTROL.test(text.replace(/\n/g, ''))) return { error: 'settingInvalid' }
72 return { value: listEntries(text).join(',') }
73}
74
75// This plugin's own /config row for a field. Rows from another plugin with the same name (a fork
76// from another marketplace) are skipped; if ours is still ambiguous, nothing is written.
77export function ownConfigKey(rows, name, field) {
78 const mine = rows.filter((r) => settingsField(r.key, name) === field && (!r.provider || r.provider.plugin === name))
79 // Two rows of our name (e.g. an installed copy and a --plugin-dir copy) cannot be told apart.
80 if (mine.length > 1) return null
81 return mine.length === 1 ? mine[0].key : name + '.' + field
82}
83
84// How many entries of a comma-separated list a new value drops.
85export function removedEntries(before, after) {
86 const next = new Set(listEntries(after))
87 return [...new Set(listEntries(before))].filter((x) => !next.has(x)).length
88}
89hooks/assets.js 46 lines1// What the user already has: their agents and skills, from Claude Code's folder and this
2// repository's .claude folder. Reads names only; any failure leaves the list empty.
3
4const MAX_ASSETS = 60
5// A name, not a hidden folder (.git) or a readme.
6const NAME = /^(?!\.)(?!README$)[\w.-]{1,64}$/i
7
8async function names($, dir, kind) {
9 try {
10 const entries = await $.fs.list(dir)
11 return entries
12 .filter((e) => (kind === 'agent' ? e.kind !== 'dir' && e.name.endsWith('.md') : e.kind !== 'file'))
13 .map((e) => (kind === 'agent' ? e.name.slice(0, -3) : e.name))
14 .filter((n) => NAME.test(n))
15 } catch {
16 return []
17 }
18}
19
20async function list($, dirs, kind) {
21 const found = await Promise.all(dirs.map((d) => names($, d, kind)))
22 return [...new Set(found.flat())].slice(0, MAX_ASSETS).map((name) => ({ name }))
23}
24
25async function exists($, path) {
26 try {
27 return Boolean(await $.fs.exists(path))
28 } catch {
29 return false
30 }
31}
32
33// The working directory, Claude Code's folder and the user's agents and skills (user + project).
34export async function readWorkspace($, claudeDir) {
35 let cwd = ''
36 try {
37 cwd = String((await $.session.cwd()) || '')
38 } catch {
39 // No working directory: repository-scoped findings stay off.
40 }
41 const isRepo = Boolean(cwd) && (await exists($, cwd + '/.git'))
42 const roots = [claudeDir, cwd && cwd + '/.claude'].filter(Boolean)
43 const [agents, skills] = await Promise.all([list($, roots.map((r) => r + '/agents'), 'agent'), list($, roots.map((r) => r + '/skills'), 'skill')])
44 return Object.freeze({ cwd, isRepo, claudeDir, agents, skills })
45}
46hooks/charts.js 220 lines1// Rich pane charts: the data each chart shows, and the two ways to draw it — Raster cells for the
2// terminal, SVG for the desktop app. Pure functions, no mods API. Colors and forms follow the
3// dataviz method: categorical slots in fixed order (validated light and dark), one blue for
4// magnitude, status colors only for state and always beside an icon and a word.
5
6import { THRESHOLDS, TRIGGERS, sessionCacheRead, sessionLabel, totals, workSessions } from './rules.js'
7
8// Dark-surface steps: the terminal's background is unknown, and most are dark.
9export const SERIES = Object.freeze(['#3987e5', '#d95926', '#199e70', '#c98500'])
10const SERIES_LIGHT = Object.freeze(['#2a78d6', '#eb6834', '#1baf7a', '#eda100'])
11export const OTHER = '#8a8983'
12export const SEQUENTIAL = '#3987e5'
13export const STATUS = Object.freeze({ good: '#0ca30c', warning: '#fab219', critical: '#d03b3b' })
14const TRACK = '#4a4a46'
15const MAX_SERIES = 4
16const TOP_ROWS = 5
17const SPARK_DAYS = 30
18const COMPACT_ROWS = 8
19
20const hex = (c) => parseInt(c.slice(1), 16)
21const DEFAULT_COLOR = 0x01000000
22
23// ---------- data ----------
24
25const finitePct = (v) => (Number.isFinite(v) ? Math.min(100, Math.max(0, v)) : null)
26
27// Context warns from 60% and is high from 80%; a plan limit warns from 80%, as the Now rules do.
28export function statusOf(pct, kind = 'context') {
29 if (kind === 'rate') return pct >= THRESHOLDS.rateLimitWarnPct ? 'warning' : 'good'
30 if (pct >= THRESHOLDS.contextHighPct) return 'critical'
31 if (pct >= THRESHOLDS.contextWarnPct) return 'warning'
32 return 'good'
33}
34
35// Part-to-whole: the top models by output tokens, the rest folded into "Other" (never a 5th hue).
36function modelMix(tot) {
37 const rows = Object.entries(tot.usage).map(([m, u]) => ({ label: m.replace('claude-', ''), value: u.out })).filter((r) => r.value > 0)
38 rows.sort((a, b) => b.value - a.value)
39 const top = rows.slice(0, MAX_SERIES).map((r, i) => ({ ...r, color: SERIES[i] }))
40 const rest = rows.slice(MAX_SERIES).reduce((n, r) => n + r.value, 0)
41 return rest ? [...top, { label: 'other', value: rest, color: OTHER }] : top
42}
43
44// The indexer keys byDay by local date, so the last days are local dates too (stepped by calendar
45// day, not 24 h, so a DST change never skips or repeats one).
46export const localDay = (ms) => {
47 const d = new Date(ms)
48 return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`
49}
50
51function lastDays(byDay = {}, nowMs) {
52 return Array.from({ length: SPARK_DAYS }, (_, k) => {
53 const d = new Date(nowMs)
54 d.setDate(d.getDate() - (SPARK_DAYS - 1 - k))
55 const day = localDay(d.getTime())
56 return { label: day, value: byDay[day] || 0 }
57 })
58}
59
60// The digest's charts; they change only with the digest and the local date, so callers memoize them.
61export function digestCharts(digest, nowMs) {
62 const tot = totals(digest)
63 const heavy = workSessions(digest).map((s) => ({ label: sessionLabel(s), value: sessionCacheRead(s) })).filter((r) => r.value > 0)
64 heavy.sort((a, b) => b.value - a.value)
65 const compactions = tot.compactions.filter((c) => c.preTokens).slice(-COMPACT_ROWS)
66 const usage = Object.values(tot.usage)
67 const summary = {
68 sessions: tot.sessions,
69 out: usage.reduce((n, u) => n + u.out, 0),
70 cacheRead: usage.reduce((n, u) => n + u.cacheRead, 0),
71 compactions: tot.compactions.length,
72 }
73 return Object.freeze({
74 summary,
75 modelMix: modelMix(tot),
76 heavy: heavy.slice(0, TOP_ROWS),
77 compactions: compactions.map((c) => ({ label: `${String(c.at || '').slice(5, 10)} ${TRIGGERS.has(c.trigger) ? c.trigger : '?'}`, value: c.preTokens })),
78 perDay: lastDays(digest?.history?.byDay, nowMs),
79 })
80}
81
82// The live session's meters, rebuilt on every draw.
83export function liveCharts(live) {
84 const context = finitePct(live?.context?.percent)
85 const rates = (live?.rateLimits || []).map((r) => ({ kind: String(r.kind ?? ''), pct: finitePct(r.percentUsed) })).filter((r) => r.pct !== null)
86 return Object.freeze({ context: context === null ? null : { pct: context }, rates, unreviewed: (live?.unreviewed || []).length })
87}
88
89export const chartData = (digest, live, nowMs) => Object.freeze({ ...digestCharts(digest, nowMs), ...liveCharts(live) })
90
91// ---------- terminal: Raster cells ----------
92
93const B64 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
94
95// Standard padded base64, written out so it does not depend on Uint8Array.prototype.toBase64.
96function base64(bytes) {
97 let out = ''
98 for (let i = 0; i < bytes.length; i += 3) {
99 const n = (bytes[i] << 16) | ((bytes[i + 1] ?? 0) << 8) | (bytes[i + 2] ?? 0)
100 out += B64[(n >> 18) & 63] + B64[(n >> 12) & 63]
101 out += i + 1 < bytes.length ? B64[(n >> 6) & 63] : '='
102 out += i + 2 < bytes.length ? B64[n & 63] : '='
103 }
104 return out
105}
106
107// cells: one row of [char, '#rrggbb' | null] -> RasterProps for that row.
108// Written through a DataView so the bytes are little-endian whatever the host's byte order.
109export function rasterRow(key, cells) {
110 const view = new DataView(new ArrayBuffer(cells.length * 12))
111 cells.forEach(([ch, fg], i) => {
112 view.setUint32(i * 12, ch.codePointAt(0), true)
113 view.setUint32(i * 12 + 4, fg ? hex(fg) : DEFAULT_COLOR, true)
114 view.setUint32(i * 12 + 8, DEFAULT_COLOR, true)
115 })
116 return { key, columns: cells.length, rows: 1, cells: base64(new Uint8Array(view.buffer)) }
117}
118
119const widthOf = (value, max, cols) => (max > 0 ? Math.max(value > 0 ? 1 : 0, Math.round((value / max) * cols)) : 0)
120
121export function meterCells(pct, cols, color) {
122 const filled = widthOf(Math.min(100, Math.max(0, pct)), 100, cols)
123 return Array.from({ length: cols }, (_, i) => (i < filled ? ['█', color] : ['░', TRACK]))
124}
125
126// Widths that sum to exactly `room`, every segment at least one cell (largest remainder; the
127// cells a tiny segment borrows come from the widest one).
128export function allocate(values, room) {
129 const total = values.reduce((a, b) => a + b, 0) || 1
130 const exact = values.map((v) => (v / total) * room)
131 const out = exact.map((x) => Math.max(1, Math.floor(x)))
132 let left = room - out.reduce((a, b) => a + b, 0)
133 const byRemainder = exact.map((x, i) => [x % 1, i]).sort((a, b) => b[0] - a[0])
134 for (const [, i] of byRemainder) {
135 if (left <= 0) break
136 out[i] += 1
137 left -= 1
138 }
139 while (left < 0) {
140 const i = out.indexOf(Math.max(...out))
141 out[i] -= 1
142 left += 1
143 }
144 return out
145}
146
147// Segments side by side with a one-cell gap between them (the surface gap between fills). Where
148// the columns cannot hold a cell and a gap for each, the smallest segments fold away.
149export function stackedCells(segments, cols) {
150 const shown = segments.slice(0, Math.max(1, Math.floor((cols + 1) / 2)))
151 const widths = allocate(shown.map((s) => s.value), Math.max(shown.length, cols - (shown.length - 1)))
152 return shown.flatMap((s, i) => [...(i > 0 ? [[' ', null]] : []), ...Array.from({ length: widths[i] }, () => ['█', s.color])])
153}
154
155export function barCells(value, max, cols, color) {
156 return Array.from({ length: widthOf(value, max, cols) }, () => ['█', color])
157}
158
159const LEVELS = ['▁', '▂', '▃', '▄', '▅', '▆', '▇', '█']
160
161export function sparkCells(values, color) {
162 const max = Math.max(1, ...values)
163 return values.map((v) => (v > 0 ? [LEVELS[Math.min(7, Math.floor((v / max) * 7.999))], color] : ['▁', TRACK]))
164}
165
166// ---------- desktop: SVG ----------
167
168// Characters XML 1.0 does not allow (C0 controls, U+FFFE/FFFF, lone surrogates) would make the SVG
169// fail to parse, so they are dropped before escaping.
170const XML_INVALID = /[^\u0009\u000a\u000d\u0020-\ud7ff\ue000-\ufffd\u{10000}-\u{10ffff}]/gu
171const esc = (s) => String(s).replace(XML_INVALID, '').replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[c])
172const BAR_H = 10
173
174// Light steps by default, dark steps under the desktop's dark scheme; each mark carries a tooltip.
175function svgDoc(width, height, body, colors) {
176 const light = colors.map((c, i) => `.c${i}{fill:${c.light}}`).join('')
177 const dark = colors.map((c, i) => `.c${i}{fill:${c.dark}}`).join('')
178 return `<svg xmlns="http://www.w3.org/2000/svg" width="${width}" height="${height}" viewBox="0 0 ${width} ${height}">`
179 + `<style>.t{fill:#d6d5cf}${light}@media (prefers-color-scheme: dark){.t{fill:#4a4a46}${dark}}</style>${body}</svg>`
180}
181
182const pair = (c) => ({ light: SERIES_LIGHT[SERIES.indexOf(c)] || c, dark: c })
183
184export function svgMeter(pct, width, color) {
185 const w = Math.round((Math.min(100, Math.max(0, pct)) / 100) * width)
186 const body = `<rect class="t" x="0" y="0" width="${width}" height="${BAR_H}" rx="4"/>`
187 + `<rect class="c0" x="0" y="0" width="${w}" height="${BAR_H}" rx="4"><title>${esc(Math.round(pct) + '%')}</title></rect>`
188 return svgDoc(width, BAR_H, body, [pair(color)])
189}
190
191export function svgStacked(segments, width) {
192 const total = segments.reduce((n, s) => n + s.value, 0) || 1
193 // Same allocation as the terminal: widths sum to the room left after the 2px gaps.
194 const widths = allocate(segments.map((s) => s.value), Math.max(segments.length, width - 2 * (segments.length - 1)))
195 let x = 0
196 const body = segments.map((s, i) => {
197 const w = widths[i]
198 const rect = `<rect class="c${i}" x="${x}" y="0" width="${w}" height="${BAR_H}" rx="2"><title>${esc(s.label + ' ' + Math.round((s.value / total) * 100) + '%')}</title></rect>`
199 x += w + 2
200 return rect
201 }).join('')
202 return svgDoc(width, BAR_H, body, segments.map((s) => pair(s.color)))
203}
204
205export function svgBar(value, max, width, color, title) {
206 const w = Math.max(value > 0 ? 2 : 0, Math.round((value / (max || 1)) * width))
207 return svgDoc(width, BAR_H, `<rect class="c0" x="0" y="0" width="${w}" height="${BAR_H}" rx="4"><title>${esc(title)}</title></rect>`, [pair(color)])
208}
209
210export function svgSpark(points, width, height, color) {
211 const max = Math.max(1, ...points.map((p) => p.value))
212 const step = width / points.length
213 const body = points.map((p, i) => {
214 const h = Math.max(1, Math.round((p.value / max) * height))
215 return `<rect class="c0" x="${(i * step).toFixed(1)}" y="${height - h}" width="${Math.max(1, step - 2).toFixed(1)}" height="${h}" rx="1"><title>${esc(p.label + ': ' + p.value)}</title></rect>`
216 }).join('')
217 return svgDoc(width, height, body, [pair(color)])
218}
219
220hooks/burn.js 68 lines1// Token burn pace: the tokens one main-loop turn spent (its subagents' included) per minute of
2// the turn's wall time. Cache reads are billed at a tenth of fresh input, so they count a tenth
3// here too. Pure functions, no mods API.
4
5export const BURN = Object.freeze({
6 // Tokens per minute that count as heavy; about the 90th percentile of past sessions.
7 defaultPerMin: 100_000,
8 // At this many times the threshold the pace is "very high".
9 blazeFactor: 2,
10 // Short or small turns swing the pace on one cache write; they are measured but never flagged.
11 minTurnTokens: 20_000,
12 minTurnMs: 5_000,
13 cacheReadWeight: 0.1,
14 maxPerMin: 10_000_000,
15})
16
17export const BURN_EFFECTS = ['rainbow', 'still', 'plain']
18export const EMPTY_BURN = Object.freeze({ turn: null, last: null, hidden: false })
19
20const MINUTE_MS = 60_000
21const count = (n) => (Number.isFinite(n) && n > 0 ? n : 0)
22
23export function weightedTokens(usage) {
24 if (!usage) return 0
25 return Math.round(count(usage.input_tokens) + count(usage.output_tokens) + count(usage.cache_creation_input_tokens) + BURN.cacheReadWeight * count(usage.cache_read_input_tokens))
26}
27
28// null below the threshold (or with the alert off), else 'hot' or 'blaze'.
29export function burnLevel(perMin, threshold) {
30 if (!(threshold > 0) || !(perMin >= threshold)) return null
31 return perMin >= threshold * BURN.blazeFactor ? 'blaze' : 'hot'
32}
33
34// A main-loop turn began: tokens from now on count toward it.
35export function startTurn(burn, turnId, at) {
36 return { ...burn, turn: { id: turnId, startedAt: at, tokens: 0 } }
37}
38
39// Any turn ended, the main loop's or a subagent's, at `now`. A subagent run that began inside the
40// open main turn adds its tokens to it; one that began earlier would swell a short turn, so it is
41// left out. When the main turn itself ends, its pace becomes `last`; a new heavy turn shows the
42// alert again.
43export function endTurn(burn, e, threshold, now) {
44 const open = burn.turn
45 if (!open) return burn
46 if (e.agentId !== undefined || e.turnId !== open.id) {
47 if (count(e.durationMs) > now - open.startedAt) return burn
48 return { ...burn, turn: { ...open, tokens: open.tokens + weightedTokens(e.usage) } }
49 }
50 const tokens = open.tokens + weightedTokens(e.usage)
51 const ms = count(e.durationMs)
52 const isMeasurable = tokens >= BURN.minTurnTokens && ms >= BURN.minTurnMs
53 const perMin = ms ? Math.round(tokens / (ms / MINUTE_MS)) : 0
54 const level = isMeasurable ? burnLevel(perMin, threshold) : null
55 return { turn: null, last: { tokens, ms, perMin, level, threshold }, hidden: level ? false : burn.hidden }
56}
57
58// A saved `last` (from $.state, after a reload) judged again by the threshold in effect now.
59export function restoreLast(saved, threshold) {
60 const n = (k) => (Number.isFinite(saved?.[k]) && saved[k] >= 0 ? saved[k] : null)
61 const [tokens, ms, perMin] = [n('tokens'), n('ms'), n('perMin')]
62 if (tokens === null || ms === null || perMin === null) return null
63 const isMeasurable = tokens >= BURN.minTurnTokens && ms >= BURN.minTurnMs
64 return { tokens, ms, perMin, level: isMeasurable ? burnLevel(perMin, threshold) : null, threshold }
65}
66
67export const isBurning = (burn) => Boolean(burn?.last?.level)
68hooks/ai-config.js 100 lines1// Model settings, prompts and the persistent explanation cache. Pure functions, no mods API.
2
3import { LANGUAGE_OPTIONS } from './i18n.js'
4
5export const MODEL_OPTIONS = ['haiku', 'sonnet', 'opus', 'fable']
6export const EFFORT_OPTIONS = ['low', 'medium', 'high']
7export const PANE_STYLES = ['simple', 'rich']
8export const DEFAULT_SETTINGS = Object.freeze({ model: 'haiku', effort: 'low', autoExplain: true, cacheExplanations: true, language: 'auto', paneStyle: 'simple' })
9// Models billed to usage credits: never called without an explicit press.
10export const CREDIT_MODELS = new Set(['fable'])
11const CACHE_TEXT_MAX = 9000
12// Short answers keep output tokens bounded; the prompts ask for the same length. Higher effort
13// may spend part of the cap on thinking, so the cap grows with it rather than cutting the reply.
14const MAX_TOKENS_BY_EFFORT = Object.freeze({ low: 700, medium: 1200, high: 2000 })
15export const maxTokensFor = (settings) => MAX_TOKENS_BY_EFFORT[settings.effort] || MAX_TOKENS_BY_EFFORT.low
16const CACHE_MAX_ENTRIES = 40
17const CACHE_TTL_MS = 14 * 24 * 3600 * 1000
18// Bump when the prompts change so cached answers from old prompts are not reused.
19const PROMPT_VERSION = 3
20
21// System prompts in the pane's language; the untrusted-data rule is always appended.
22export function systemPrompt(kind, t) {
23 return [t(kind === 'explain' ? 'explainSystem' : 'summarySystem'), t('untrusted')].join('\n')
24}
25
26// userConfig values (or a /config change) -> settings; unknown values fall back to defaults.
27export function normalizeSettings(options = {}) {
28 const pick = (value, allowed, fallback) => (allowed.includes(value) ? value : fallback)
29 return Object.freeze({
30 model: pick(options.aiModel, MODEL_OPTIONS, DEFAULT_SETTINGS.model),
31 effort: pick(options.aiEffort, EFFORT_OPTIONS, DEFAULT_SETTINGS.effort),
32 autoExplain: typeof options.autoExplain === 'boolean' ? options.autoExplain : DEFAULT_SETTINGS.autoExplain,
33 cacheExplanations: typeof options.cacheExplanations === 'boolean' ? options.cacheExplanations : DEFAULT_SETTINGS.cacheExplanations,
34 language: pick(options.language, LANGUAGE_OPTIONS, DEFAULT_SETTINGS.language),
35 paneStyle: pick(options.paneStyle, PANE_STYLES, DEFAULT_SETTINGS.paneStyle),
36 })
37}
38
39// Settings with one userConfig field replaced (aiModel | aiEffort | autoExplain).
40export function mergeSetting(settings, field, value) {
41 const current = { aiModel: settings.model, aiEffort: settings.effort, autoExplain: settings.autoExplain, cacheExplanations: settings.cacheExplanations, language: settings.language, paneStyle: settings.paneStyle }
42 return normalizeSettings({ ...current, [field]: value })
43}
44
45// Every userConfig field, as the Settings tab can change them (tests keep this equal to SETTING_KEYS).
46export const FIELDS = ['language', 'paneStyle', 'aiModel', 'aiEffort', 'autoExplain', 'cacheExplanations', 'reviewerAgents', 'memoryTools', 'memoryCueWords', 'extraRiskyCommands', 'excludeProjects', 'retentionDays', 'burnAlert', 'burnEffect']
47// The fields applied in place; the others take effect when the options change reloads the mod.
48export const LIVE_FIELDS = new Set(['language', 'paneStyle', 'aiModel', 'aiEffort', 'autoExplain', 'cacheExplanations'])
49
50// The userConfig field a /config key names, when it is one of ours. A --plugin-dir load may key
51// the plugin as `<name>` or `<name>@inline`, so both `<name>.<field>` and `<name>@x.<field>` match.
52export function settingsField(key, pluginName) {
53 if (typeof key !== 'string' || typeof pluginName !== 'string') return null
54 const head = key.slice(0, key.lastIndexOf('.'))
55 const field = key.slice(key.lastIndexOf('.') + 1)
56 const isOurs = head === pluginName || head.startsWith(pluginName + '@')
57 return isOurs && FIELDS.includes(field) ? field : null
58}
59
60// Two FNV-1a passes with different offsets: a stable 64-bit key, dependency-free (not for security).
61function fnv1a(text, seed) {
62 let h = seed
63 for (let i = 0; i < text.length; i += 1) {
64 h ^= text.charCodeAt(i)
65 h = Math.imul(h, 0x01000193) >>> 0
66 }
67 return h.toString(16).padStart(8, '0')
68}
69
70// Same finding content + model/effort + language + prompt version + exclusions -> same answer.
71// Exclusions are part of the key so changing excludeProjects never surfaces older answers.
72export function explainCacheKey(payload, settings, excludes = [], lang = 'en') {
73 const text = JSON.stringify([PROMPT_VERSION, lang, settings.model, settings.effort, [...excludes].sort(), payload])
74 return fnv1a(text, 0x811c9dc5) + fnv1a(text, 0x050c5d1f)
75}
76
77// The store is a shared JSON file: accept only well-formed entries from it.
78export function isCacheEntry(v) {
79 return Boolean(v) && typeof v.text === 'string' && v.text.length <= CACHE_TEXT_MAX && MODEL_OPTIONS.includes(v.model) && Number.isFinite(v.at)
80}
81
82// Drop expired entries and keep the newest CACHE_MAX_ENTRIES, so $.store stays small.
83export function pruneCache(cache, nowMs) {
84 const live = Object.entries(cache || {}).filter(([, v]) => isCacheEntry(v) && nowMs - v.at < CACHE_TTL_MS)
85 return Object.fromEntries(live.sort((a, b) => b[1].at - a[1].at).slice(0, CACHE_MAX_ENTRIES))
86}
87
88// One definition for every token figure shown: input counts cached and cache-written tokens too.
89export function tokensOf(usage) {
90 return {
91 in: (usage?.input_tokens || 0) + (usage?.cache_read_input_tokens || 0) + (usage?.cache_creation_input_tokens || 0),
92 out: usage?.output_tokens || 0,
93 }
94}
95
96export function addUsage(total, usage) {
97 const t = tokensOf(usage)
98 return { calls: total.calls + 1, in: total.in + t.in, out: total.out + t.out }
99}
100hooks/grounded.js 136 lines1// Findings grounded in what happened in this repository and in what the user already has: commands
2// that keep failing, corrections that keep coming back, and their own agents and skills. A pattern
3// must recur across sessions, so one bad afternoon does not become advice. Pure functions, no mods
4// API; ctx.local carries the working directory, Claude Code's folder and the asset lists (assets.js).
5
6import { fmt, sessionLabel, totals, workSessions } from './rules.js'
7
8export const GROUNDED = Object.freeze({
9 frictionFailures: 3,
10 minSessions: 2,
11 maxFriction: 3,
12 repoCorrections: 4,
13 maxSources: 5,
14})
15// Everyday shell utilities fail for generic reasons while exploring (a path that is not there);
16// they say nothing a CLAUDE.md line could fix. (The indexer keeps only Bash programs and MCP tools.)
17const GENERIC_TOOLS = new Set([
18 'Bash', 'ls', 'cat', 'head', 'tail', 'grep', 'rg', 'find', 'wc', 'sed', 'awk', 'sort', 'cut', 'xargs', 'test', 'diff', 'stat', 'file',
19 'du', 'df', 'pwd', 'which', 'mkdir', 'rm', 'cp', 'mv', 'touch', 'chmod', 'open', 'sleep', 'kill', 'pkill', 'ps',
20])
21const REVIEWER_NAME = /review|eye|audit|verif/i
22const sum = (xs) => xs.reduce((a, b) => a + b, 0)
23const lastSegment = (name) => String(name).split(':').pop()
24
25// Sessions of this repository: in a git repository, those started in it or below it; anywhere
26// else (a home folder holds every project) only those started in that very folder.
27export function repoSessions(digest, cwd, isRepo = false) {
28 const root = normalizePath(cwd)
29 if (!root) return []
30 return workSessions(digest).filter((s) => {
31 const p = normalizePath(s.project)
32 return p === root || (isRepo && p.startsWith(root + '/'))
33 })
34}
35
36// Windows paths compare with forward slashes and without letter case.
37function normalizePath(p) {
38 const s = String(p || '').replace(/\\/g, '/').replace(/\/+$/, '')
39 return /^[A-Za-z]:\//.test(s) ? s.toLowerCase() : s
40}
41
42// A short stable tag of the repository, so dismissing a finding in one repository leaves others.
43function repoTag(cwd) {
44 let h = 5381
45 for (const c of normalizePath(cwd)) h = ((h * 33) ^ c.charCodeAt(0)) >>> 0
46 return h.toString(36)
47}
48
49const transcript = (local, s) => (local.claudeDir && s.dir ? `${local.claudeDir}/projects/${s.dir}/${s.id}.jsonl` : null)
50const sources = (local, sessions) => sessions.slice(-GROUNDED.maxSources).map((s) => transcript(local, s)).filter(Boolean)
51
52export function groundedImprove(digest, ctx) {
53 const local = ctx.local || {}
54 const sessions = repoSessions(digest, local.cwd, local.isRepo)
55 const tag = repoTag(local.cwd)
56 return [...frictionFindings(sessions, tag, ctx), ...repoCorrectionFindings(sessions, tag, ctx), ...reviewerSetupFindings(digest, ctx)]
57}
58
59function frictionFindings(sessions, tag, { t, doc, local }) {
60 const byKey = new Map()
61 for (const s of sessions) {
62 for (const [key, n] of Object.entries(s.friction || {})) {
63 if (GENERIC_TOOLS.has(key) || !(n > 0)) continue
64 const row = byKey.get(key) || { key, failures: 0, sessions: [] }
65 row.failures += n
66 row.sessions.push(s)
67 byKey.set(key, row)
68 }
69 }
70 return [...byKey.values()]
71 .filter((r) => r.failures >= GROUNDED.frictionFailures && r.sessions.length >= GROUNDED.minSessions)
72 .sort((a, b) => b.failures - a.failures)
73 .slice(0, GROUNDED.maxFriction)
74 .map((r) => ({
75 id: `improve-friction-${tag}-${r.key}`, severity: r.failures >= 10 ? 'mid' : 'low', details: r.sessions.map(sessionLabel),
76 title: t('frictionTitle', { key: r.key, n: r.failures, sessions: r.sessions.length }),
77 // The command name stays on this machine; the model reads "a command".
78 sharedTitle: t('frictionTitleShared', { n: r.failures, sessions: r.sessions.length }),
79 sharedAction: t('frictionActionShared'),
80 evidence: t('frictionEvidence', { dates: r.sessions.slice(-3).map((s) => String(s.end || '').slice(5, 10)).join(', ') }),
81 action: t('frictionAction', { key: r.key }),
82 doc: doc('memory'),
83 applyPrompt: t('frictionApply', { key: r.key, files: sources(local, r.sessions).join('\n') }),
84 }))
85}
86
87function repoCorrectionFindings(sessions, tag, { t, doc, local }) {
88 const hit = sessions.filter((s) => s.corrections > 0)
89 const n = sum(hit.map((s) => s.corrections))
90 if (n < GROUNDED.repoCorrections || hit.length < GROUNDED.minSessions) return []
91 // About one correction a session is ordinary; several in the same sessions is a habit to write down.
92 return [{
93 id: 'improve-repo-corrections-' + tag, severity: n >= hit.length * 1.5 ? 'mid' : 'low', details: hit.map((s) => `${sessionLabel(s)} · ${s.corrections}`),
94 title: t('repoCorrTitle', { n, sessions: hit.length }),
95 evidence: t('repoCorrEvidence'),
96 action: t('repoCorrAction'),
97 doc: doc('memory'),
98 applyPrompt: t('repoCorrApply', { files: sources(local, hit).join('\n') }),
99 }]
100}
101
102// The review checks are off until reviewerAgents names an agent; point at the user's own ones.
103function reviewerSetupFindings(digest, { t, doc, cfg, local }) {
104 if (cfg.reviewers.length) return []
105 const names = (local.agents || []).map((a) => a.name).filter((n) => REVIEWER_NAME.test(n))
106 if (!names.length) return []
107 return [{
108 id: 'improve-setup-reviewers', severity: 'mid', localDetails: true, details: names,
109 title: t('setupReviewersTitle', { n: names.length }),
110 evidence: names.join(', '),
111 action: t('setupReviewersAction', { names: names.join(',') }),
112 sharedAction: t('setupReviewersAction', { names: t('theirNames') }),
113 doc: doc('sub-agents'),
114 }]
115}
116
117// Tips about the user's own agents and skills that sat unused in the analysed sessions.
118export function ownAssetTips(digest, ctx) {
119 const local = ctx.local || {}
120 if (!workSessions(digest).length) return []
121 const tot = totals(digest)
122 const usedAgents = new Set(Object.keys(tot.agents).map(lastSegment))
123 const usedSkills = new Set([...Object.keys(tot.skills || {}).map(lastSegment), ...Object.keys(digest?.history?.slash || {}).map((c) => lastSegment(c.slice(1)))])
124 const idle = (list, used) => (list || []).map((a) => a.name).filter((n) => !used.has(n))
125 return [
126 assetTip('tip-own-agents', 'tipOwnAgents', idle(local.agents, usedAgents), (local.agents || []).length, 'sub-agents', ctx),
127 assetTip('tip-own-skills', 'tipOwnSkills', idle(local.skills, usedSkills), (local.skills || []).length, 'skills', ctx),
128 ].filter(Boolean)
129}
130
131function assetTip(id, key, idle, total, slug, { t, doc }) {
132 if (!idle.length) return null
133 // Names stay on this machine: localDetails sends the AI explanation a count instead.
134 return { id, severity: 'low', localDetails: true, details: idle, title: t(key + 'Title', { n: idle.length, total }), evidence: idle.slice(0, 6).join(', ') + (idle.length > 6 ? ` +${fmt(idle.length - 6)}` : ''), action: t(key + 'Concept'), doc: doc(slug) }
135}
136