Difficulty-based routing for Claude Code. You pick the main model and effort; Claude decides what to do itself and what to hand to tiered Haiku, Sonnet, and…

Difficulty-based subagent routing for Claude Code. You pick the main session's model and effort. Claude then decides, task by task, what to do itself and what to hand to a cheaper or stronger subagent, at the right effort. It escalates when a tier gets stuck and follows your overrides.
you ──▶ main session (your model/effort) ──┬─ does interactive, coupled, quick work itself
├─▶ scanner haiku / low lookups, noisy logs
├─▶ deep-reader sonnet / medium multi-file analysis, web research
├─▶ implementer sonnet / medium well-specified edits
├─▶ implementer-hard opus / high hard, multi-module work
├─▶ ui-smoke haiku / low quick read-only UI check
├─▶ ui-tester sonnet / medium browser/emulator flows
└─▶ reviewer opus / high independent review
Out of the box, every subagent runs on whatever model and effort it was given, no matter how easy or hard the job is. Claude Code now lets the main session set model and effort per subagent call (2.1.292+), but something has to decide when to use them. Crew Chief is that decision layer, plus the tiers it routes to:
/clear or compaction), so it is always active.implementer → implementer-hard → main session, instead of retrying the same tier.ui-smoke for a quick read-only check and ui-tester for multi-step browser, emulator, or simulator flows, so screenshots stay out of the main context./crew-chief:crew-mode solo.ui-tester sonnet-5.5 · medium · 41.2k Checking the login flow. Claude Code reads a subagentStatusLine from a plugin's settings.json but does not apply it to the panel (checked on 2.1.296), so on your first session after install or update crew-chief copies the row script to ~/.claude/ and adds the key to your settings.json (needs jq; see the row installer).continue: a toast when a limit you were close to resets, and, when a limit stops Claude, an offer to send "continue" at the reset. See Limit resets./crew-tidy and /crew-report: what in your context is oversized, stale or repeated (nothing changes, except an archive move you confirm), and tokens and cost by model and by main or subagent. See Context audit and report./advisor is off, it explains the benefit and offers to turn it on. See Advisor offer./crew-chief:crew-mode solo is enforced by a hook that blocks the Agent tool, not just requested in the prompt.routing skill) for when one subagent is the wrong tool: forks, Monitor, /loop, /goal, dynamic workflows, agent teams, routines.Claude Code plugin (full: agents, hooks, skills):
claude plugin marketplace add aykyusuf/crew-chief
claude plugin install crew-chief@crew-chief
Or inside a session: /plugin install crew-chief --marketplace aykyusuf/crew-chief.
Skills only, any agent tool (npx skills):
npx skills add aykyusuf/crew-chief
This installs the skills but not the agents or hooks. In Claude Code, run /crew-chief:crew-setup (or /crew-setup when installed with npx) once per project to copy the agents, the guard, and the policy into .claude/ and CLAUDE.md. Restart Claude Code afterwards if .claude/agents/ did not exist before.
Pick one route per machine. Installing both the plugin and the npx skills lists each skill twice (/crew-chief:crew-routing and /crew-routing), which only wastes context. /crew-setup detects the plugin and skips the agents and guard, and the plugin's session hook stays quiet when the policy is already in CLAUDE.md.
Requirements: Claude Code 2.1.292 or later for per-call effort (older versions still work, routing by tier defaults); 2.1.287 or later for the token saver. The guard parses its input with jq when installed and with sed otherwise.
Third-party marketplaces do not auto-update by default, so turn it on once: /plugin → Marketplaces → crew-chief → Enable auto-update. Claude Code then refreshes the plugin shortly after your first message in a session. Or update by hand: claude plugin update crew-chief@crew-chief.
An update does not change the session that is already running:
Plugin updated: crew-chief · Run /reload-plugins to apply. Run /reload-plugins to switch the hooks in that session (a new session loads the new version by itself).claude plugin update in a shell, other open sessions get no message from Claude Code. Crew Chief fills that gap: on your next prompt it says once per session that this session still runs the old copy and to run /reload-plugins. After an auto-update you may see both messages, since the old copy is marked in that case too.CREW_CHIEF_WHATS_NEW=off.Both notices are printed by a UserPromptSubmit hook (systemMessage) under your prompt, not written by the model. A SessionStart hook's systemMessage is not shown by Claude Code 2.1.295, which is why the notice waits for your first prompt.
Plan limits are eaten mostly by long sessions and big contexts, then by subagents on Opus. The saver is a small mod (hooks/register.js) that watches your limits from inside Claude Code and asks before it changes anything.
xhigh or max); Haiku and your main session are never touched. It changes the effort of each subagent request, not the model./clear, and /resume starts with the saver off. No saver state is saved; what is remembered between sessions is the language and the advisor-offer answer (see below)./saver on|off|status switches it by hand and shows your limits, their reset times, and the context size.Language. Questions, toasts, /saver, and the update notices speak English or Turkish, whichever you write in. Order of precedence: CREW_CHIEF_LANG=tr|en, then Claude Code's language setting (turkish or english), then your recent prompts (Turkish letters and common Turkish words; the majority of the last five prompts, so one stray English sentence changes nothing; slash commands and code count for nothing), then the language last detected (so the first question of a new session already speaks it), then the LANG locale, then English. Kept between sessions in the plugin's store: that one word, tr or en, and the answer to the advisor offer. Other languages fall back to English; adding one means adding an object to hooks/saver-i18n.mjs (a test checks that its keys match English). Update notes come from CHANGELOG.tr.md when it has the version, otherwise from CHANGELOG.md.
| Environment variable | Effect |
|---|---|
CREW_CHIEF_SAVER=off | No saver questions and no toasts (/saver still works; the one-time advisor offer has its own switch below) |
CREW_CHIEF_SAVER_FIVE_HOUR=60,85 | Your own 5-hour thresholds |
CREW_CHIEF_SAVER_SEVEN_DAY=50,90 | Your own weekly thresholds |
CREW_CHIEF_LANG=tr or en | Force the language of every message |
CREW_CHIEF_ADVISOR_OFFER=off | Never offer the advisor |
Needs: Claude Code 2.1.287 or later (older versions never load the mod; the first prompt after install tells you), and a Pro or Max plan for the limit data (with an API key the mod stays quiet; the context and age toasts still work). The questions need an interactive session; claude -p never asks.
Measured on Claude Code 2.1.295: the limits are available right when a session starts, and match /usage and the status line. For a hard cap that needs no questions, set "maxEffortLevel": "medium" in your settings.
A long conversation costs more with every request and answers worse. /compact helps, but it replaces the conversation with a summary, and details, especially rules you stated early, can fall out of it. This flow makes compaction a decision you take at a good moment, with safeguards.
crew_compact_checkpoint at the next natural phase boundary (a task finished, tests green; never in the middle of work). Claude decides when a phase is over.$.agent.list(): pending or running; a subagent waiting on a server it started, on a plan's approval or on another agent is shown but not waited for): a subagent always finishes and brings a result back, so it must not be cut in half. The tool then tells Claude to call again when they are done, and the between-turns question waits for the next finished turn. Only a turn that ended with an answer counts (not an interrupt, an error or a refusal). A dev server or watcher left open in the background is never waited for, because it never ends and a compaction does not touch it; the question shows it instead (Now: subagents running: 0, background processes: 2 (npm run dev, uvicorn app:app), uncommitted files: 3) and the summarizer is told to keep its task id and command, because after a compaction Claude no longer remembers the handles of background tasks it started (anthropics/claude-code#29193). The background processes come from the Stop event's task list, which a mod receives only where the settings-hook events reach it; the other numbers do not depend on that.STATUS.md (including Constraints: your rules, copied verbatim), tasks.json, PROGRESS.md. Compaction waits until STATUS.md has changed. If it did not, you are asked: Compact anyway, Ask Claude to update first, or Cancel. In a project without handoff files, Claude first offers to set them up (the crew-handoff skill shows a preview and needs its own yes; its Constraints start with the rules you gave in the conversation), because without them nothing can put your rules back after the compaction; if you decline, it compacts without them and only the brief, the saved summary and the transcript path protect you.UNCONFIRMED, never as completed. The same brief is added to a /compact you type and to an automatic compaction, after your own words.compact-summaries/, last 5, readable only by you). The summary is checked, by plain string matching and not by a model, for your pinned constraints and the open tasks; a toast says how many were missing. scripts/compact-restore.sh (SessionStart, compact) then prints your Constraints, Now, Next, Decisions, the latest failed attempts and the open tasks from the files, not from the summary, with the path of the full transcript. Claude Code keeps the lines from before a compaction in that transcript, so a missing detail can be searched; if a compaction ever loses lines, the next ones copy the transcript first (last 3, readable only by you)./crew-compact starts the proposal by hand. Environment: CREW_CHIEF_COMPACT=off turns the whole flow off; CREW_CHIEF_COMPACT_FOCUS=off only stops the brief being added; CREW_CHIEF_COMPACT_ARM=300k and CREW_CHIEF_COMPACT_ASK=500k set the two sizes; CREW_CHIEF_RESTORE=off stops the restore block.
Why these numbers, and what is checked. Anthropic gives no recommended compaction point (only the default, about 967k on a 1M model). Reports put the drop in quality at 300-400k tokens, "highly dependent on the task", so the sizes are absolute tokens and yours to change. Checked on Claude Code 2.1.300 in an interactive session: instructions from a session.compact hook are honored and added to the default summary prompt (the documented API replaces it, so the brief is written to stand on its own either way); the classic PreCompact, PostCompact and SessionStart (compact) hooks fire for a compaction a plugin starts; the SessionStart output reaches the model; the transcript keeps its pre-compaction lines. A plugin cannot start a compaction in claude -p or from a command; it runs from a timer after the turn, and is retried a few times if a turn is still running. Constraints pinned in STATUS.md are re-injected after every compaction because rules that exist only in the conversation are the ones research found to decay most.
StopFailure event with error rate_limit, not the 100 % mark: with usage credits you keep working past it), you are asked whether to send "continue" at the reset. Only on a yes, only for a reset within 6 hours, and nothing is sent if you typed something in the meantime. The message says it comes from crew-chief; it is not sent as your own words. CREW_CHIEF_RESET=off turns both off./crew-tidy reads what Claude Code actually loaded (the same list /context shows) and reports, changing nothing: instruction and memory files over Anthropic's limits (CLAUDE.md under about 200 lines; MEMORY.md loads only its first 200 lines or 25 KB, the rest is dropped silently), paths a file mentions that no longer exist, MEMORY.md entries pointing at missing files, lines repeated across files, a STATUS.md over 6 KB (read at every start), PROGRESS.md entries older than 60 days, MCP servers by token cost, the largest parts of the context. Files under ~/.claude are only reported. /crew-tidy archive moves PROGRESS.md entries older than 60 days to PROGRESS-archive.md after asking: the archive is written and read back before the source is rewritten, an entry whose date is unclear stays, nothing is deleted.
/crew-report shows tokens (exact) and cost (approximate) by main or subagent and model, and how much of the output came from subagents and from Sonnet or Haiku. Claude Code reports one session total, so each request is credited with what the total grew by since the previous one ended. A toast on your next prompt also warns when the prompt cache has probably gone cold during an idle gap (the cache lifetime is learned from the usage numbers; nothing is warned until an expiry has been seen; CREW_CHIEF_CACHE_HINT=off).
For reviewers and for you. Everything below happens inside Claude Code on your machine; the mod has no network access and sends nothing anywhere.
| What | Where | Why |
|---|---|---|
Reads files ($.fs.read, exists, list, stat) | The project's STATUS.md, tasks.json, PROGRESS.md; the instruction and memory files Claude Code loaded (the list /context shows), only for /crew-tidy; file times for the compact gate | To check the summary against your pinned rules and open tasks, to audit context, to wait until STATUS.md was updated |
Reads settings ($.settings.read) | Only the language and advisorModel keys | To speak your language and to know whether the advisor offer applies. It never reads API keys, tokens or any credential |
Reads environment ($.env.get) | HOME, TMPDIR, LANG, the CREW_CHIEF_* switches, and a few CLAUDE_CODE_USE_* flags | Paths, language, switches, and whether a cloud provider route is in use |
Runs programs ($.process.run) | wc -l <transcript> (count lines before and after a compaction); git status --porcelain (count uncommitted files, shown in the compact question); chmod 600 <file> (make its own backups private); rm -f <old backup> (delete only its own backups beyond the newest 5 or 3); mkdir -p, cp -p <transcript> <backup> (only if a compaction ever lost transcript lines). The arguments are paths the mod computes, not text from the conversation | Backups and the transcript check |
| Runs a slash command | /advisor, once, only after you said yes to the advisor offer | To turn the advisor on for you |
Submits prompts ($.prompt.submit) | Two fixed texts, framed as coming from crew-chief (never as your own words): "update the handoff files" after you approved a compaction, and "continue where you left off" at a limit reset you approved. They contain no file contents and no conversation text | To carry out what you approved |
Writes files ($.fs.write) | Its own data folder (compact-summaries/); and, only when you confirm /crew-tidy archive, PROGRESS.md (shortened) and PROGRESS-archive.md (the old entries). It never writes your instruction files, settings, or build files | Backups; the archive you asked for |
| Registers a tool | crew_compact_checkpoint, which only asks you whether to compact and returns instructions to Claude | The phase-boundary proposal |
| Compaction hooks | Adds a summarizer brief to a compaction (session.compact), and starts a compaction only after your yes | Nothing important lost |
/advisor (experimental, Anthropic API only) lets Claude ask a stronger model for advice at hard moments: before choosing an approach, when stuck, before finishing. Subagents inherit it, so a Sonnet implementer can consult Opus instead of stopping and being re-run as implementer-hard. In Anthropic's own benchmark a Sonnet and Opus pair finished tasks about 12% cheaper and slightly better; each consultation is billed at the advisor's rates.
When the advisor is off, the saver mod offers it once, after the first finished turn of a session (never at startup, never over a saver question):
/advisor opus (/advisor fable for Fable) for you, which saves advisorModel in your user settings exactly as if you had typed it, and says so in a toast. If the setting does not appear (a policy, Fable usage credits not enabled), the toast tells you to run /advisor yourself to see why, and the offer is not repeated. Remind me in a week and Don't ask again are remembered in the plugin's store. Dismissing the dialog remembers nothing.advisorModel is already set, on Bedrock, Vertex, Foundry or the other cloud routes, when CLAUDE_CODE_DISABLE_ADVISOR_TOOL is set, when this Claude Code has no /advisor, when the main model is unknown, in claude -p, or after you said yes (turn it off later with /advisor off; it will not come back). It also waits for a turn that ended normally, not one you interrupted.CREW_CHIEF_ADVISOR_OFFER=off switches the offer off for good.Nothing to do: start a session, pick your model and effort as usual, and work. Crew Chief's policy tells Claude when to delegate.
| You say | What happens | |||
|---|---|---|---|---|
| (nothing) | auto mode: routed by difficulty | |||
| "do it yourself", "no subagents" | solo: everything stays in the main session (/crew-chief:crew-mode solo also blocks the Agent tool with a hook until you switch back) | |||
| "use agents", "delegate this" | delegate: independent pieces go to tiers in parallel | |||
| "do the UI directly with Opus" | That part stays in the main session; the rest is routed | |||
| "give the tests to Haiku", "Sonnet at medium for this" | The subagent runs with exactly that model/effort | |||
@agent-crew-chief:implementer-hard fix the race in sync.go | That agent, guaranteed | |||
| `/crew-chief:crew-mode auto\ | solo\ | delegate\ | status` | Switch or show the mode |
Change a tier's model or effort: create .claude/agents/<name>.md in your project with the same name (
hooks/register.js 1617 lines1// GENERATED by tools/build_mod.py from hooks/src/*.js. Edit those files, not this one.
2// (The directory that reviews plugins reads this file alone and follows `$` and `on` only into functions
3// declared here, so every part that touches `$` is joined into this one readable file. Pure helpers that
4// never see `$` stay in their own files and are imported below.)
5import {
6 PROGRESS_ARCHIVE_DAYS,
7 backgroundNote,
8 backupName,
9 backupsToPrune,
10 checkSummary,
11 compactThresholds,
12 openTasks,
13 parseStatus,
14 parseTokens,
15 pluginDataDir,
16 projectDirName,
17 splitProgress,
18 withFocus,
19} from './compact-logic.mjs'
20import {
21 open,
22} from './coord.mjs'
23import {
24 addStep,
25 classifyGap,
26 fmtTokens,
27 fmtUsd,
28 newStats,
29 nextHint,
30 parseHint,
31 routingShare,
32 shouldWarnCold,
33 statsRows,
34} from './report-logic.mjs'
35import {
36 classifyText,
37 pickLanguage,
38 t,
39 unitsFor,
40 windowName,
41} from './saver-i18n.mjs'
42import {
43 ADVISOR_LATER_MS,
44 FIVE_HOUR_DEFAULT,
45 SESSION_AGE_TOAST_MS,
46 SEVEN_DAY_DEFAULT,
47 advisorOfferAllowed,
48 advisorPlan,
49 agentCallEffort,
50 capEffort,
51 crossing,
52 formatDuration,
53 isEnvFlag,
54 modelFamily,
55 parseThresholds,
56 tokensLabel,
57} from './saver-logic.mjs'
58import {
59 INSTRUCTION_LINES,
60 MCP_NOTABLE_TOKENS,
61 MEMORY_BYTES,
62 MEMORY_LINES,
63 STATUS_BYTES,
64 extractPathRefs,
65 findDuplicateLines,
66 isGlobalPath,
67 kb,
68 measure,
69 memoryIndexLinks,
70 summarizeMcp,
71} from './tidy-logic.mjs'
72
73// ===== lang ==================================================================
74// Which language the mod's messages are in, shared by hooks/register.js and hooks/compact-flow.mjs.
75// The state lives here (one set per Claude Code session, put back by resetLang) so both files speak
76// the same language. A mod's analyser follows `$` only into function declarations, so these are
77// declarations, not injected callbacks.
78const VOTES_KEPT = 5
79const votes = []
80let settingPromise
81let storedPromise
82let storedLang
83
84function resetLang() {
85 settingPromise = undefined
86 storedPromise = undefined
87 storedLang = undefined
88 votes.length = 0
89}
90
91// The language of one typed prompt ('tr', 'en'); the last few decide the session's language.
92function addLanguageVote(verdict) {
93 votes.push(verdict)
94 if (votes.length > VOTES_KEPT) votes.shift()
95}
96
97async function loadLanguageSetting($) {
98 try {
99 const settings = await $.settings.read()
100 return typeof settings.language === 'string' ? settings.language : undefined
101 } catch (err) {
102 // No settings to read: the other signals still decide.
103 return undefined
104 }
105}
106
107async function loadStoredLanguage($) {
108 try {
109 const value = await $.store.get('lang')
110 return value === 'tr' || value === 'en' ? value : undefined
111 } catch (err) {
112 // No store: the language is simply not remembered.
113 return undefined
114 }
115}
116
117// The language of the messages. Cheap to call: the settings and the stored language are read once
118// per session (the promises are kept, so two overlapping calls share one read), and a language
119// read off the prompts is remembered (that one word, "tr" or "en") so the next session can ask its
120// first question in it, before any prompt has been typed.
121async function resolveLang($) {
122 const override = await $.env.get('CREW_CHIEF_LANG')
123 const locale = await $.env.get('LANG')
124 if (settingPromise === undefined) settingPromise = loadLanguageSetting($)
125 if (storedPromise === undefined) storedPromise = loadStoredLanguage($)
126 const setting = await settingPromise
127 if (storedLang === undefined) storedLang = await storedPromise
128 const pick = pickLanguage({ override, setting, votes, stored: storedLang, locale })
129 if (pick.source === 'prompts' && pick.lang !== storedLang) {
130 storedLang = pick.lang
131 try {
132 await $.store.set('lang', pick.lang)
133 } catch (err) {
134 // Not remembered; it is detected again next time.
135 }
136 }
137 return pick.lang
138}
139
140// ===== handoff ===============================================================
141// Finds the project's handoff files (see skills/crew-handoff) for the compact flow and /crew-tidy.
142// The lookup order matches scripts/compact-restore.sh: STATUS.md (or durum.md) next to the working
143// directory, then at the repository root, then one level down. A mod's analyser follows `$` only into
144// function declarations, so this is one, shared by the files that need it.
145
146// Shared by every part of the bundle: a call that may throw, with a fallback value.
147async function safe(fn, fallback) {
148 try {
149 return await fn()
150 } catch (err) {
151 return fallback
152 }
153}
154
155async function findHandoff($) {
156 const cwd = await safe(() => $.session.cwd(), undefined)
157 if (!cwd) return undefined
158 const root = (await safe(() => $.session.root(), cwd)) || cwd
159 const dirs = [...new Set([cwd, root])]
160 const names = ['STATUS.md', 'durum.md']
161 let dir
162 let status
163 for (const d of dirs) {
164 for (const n of names) {
165 if (!status && (await safe(() => $.fs.exists(`${d}/${n}`), false))) {
166 dir = d
167 status = `${d}/${n}`
168 }
169 }
170 }
171 if (!status) {
172 const entries = await safe(() => $.fs.list(root), [])
173 for (const entry of entries) {
174 if (status || entry.kind !== 'dir' || entry.name.startsWith('.') || entry.name === 'node_modules') continue
175 for (const n of names) {
176 if (!status && (await safe(() => $.fs.exists(`${root}/${entry.name}/${n}`), false))) {
177 dir = `${root}/${entry.name}`
178 status = `${dir}/${n}`
179 }
180 }
181 }
182 }
183 let tasks
184 for (const d of [dir, cwd, root]) {
185 if (!tasks && d && (await safe(() => $.fs.exists(`${d}/tasks.json`), false))) tasks = `${d}/tasks.json`
186 }
187 let progress
188 if (dir) {
189 for (const n of ['PROGRESS.md', 'ilerleme.md']) {
190 if (!progress && (await safe(() => $.fs.exists(`${dir}/${n}`), false))) progress = `${dir}/${n}`
191 }
192 }
193 if (!status && !tasks) return undefined
194 return { dir, status, tasks, progress }
195}
196
197// ===== stats-flow ============================================================
198// /crew-report and the cache-cooling hint. Part of the mod in hooks/register.js (Claude Code 2.1.287+).
199//
200// /crew-report tokens (exact) and cost (approximate) by role (main or subagent) and model, plus how
201// much of the output came from subagents and from Sonnet or Haiku: whether the routing
202// is moving work to cheaper tiers. Claude Code reports one session total, so each
203// request is credited with what the total grew by since the previous one ended.
204// cache hint a toast on your next prompt when the prompt cache has probably gone cold during an
205// idle gap and the context is big, because that message re-reads it at the full price.
206// The cache lifetime is learned from the usage numbers (see report-logic.mjs); until an
207// expiry has been seen nothing is warned. CREW_CHIEF_CACHE_HINT=off turns it off.
208// Nothing is written outside the plugin's store (the learned gap lengths). Nothing leaves the machine.
209function freshStats() {
210 return { stats: newStats(), lastCost: undefined, lastMainEndAt: undefined, lastMainContext: 0, stepGap: undefined, hint: undefined, warnedFor: undefined }
211}
212
213let sf = freshStats()
214
215async function loadHint($) {
216 if (sf.hint !== undefined) return sf.hint
217 const text = await safe(() => $.store.get('cache_hint'), undefined)
218 sf.hint = typeof text === 'string' ? parseHint(text) : {}
219 return sf.hint
220}
221
222async function statsSessionStart($) {
223 sf = freshStats()
224 try {
225 await $.command.register({
226 name: 'crew-report',
227 description: t(await resolveLang($), 'cmd_report_description'),
228 argumentHint: '',
229 })
230 } catch (err) {
231 // The name is taken: the rest still works.
232 }
233}
234
235function statsReset() {
236 sf = freshStats()
237}
238
239// A compaction (or any change of conversation) guarantees a cache miss on the next request: that gap
240// must not be mistaken for the cache's lifetime.
241function statsNoteBoundary() {
242 sf.lastMainEndAt = undefined
243 sf.stepGap = undefined
244}
245
246// Before a request goes out: how long the main conversation sat idle since its last one.
247async function statsStepStart($, e) {
248 if (e.agentId !== undefined) return
249 const now = await $.clock.now()
250 sf.stepGap = sf.lastMainEndAt === undefined ? undefined : now - sf.lastMainEndAt
251}
252
253// After a request: add it to the tallies, and learn from it how long the cache lives.
254async function statsStepEnd($, e, result) {
255 try {
256 const main = e.agentId === undefined
257 const usage = result?.usage ?? undefined
258 const family = modelFamily(usage?.model ?? e.model)
259 const now = await $.clock.now()
260 const cost = await safe(() => $.session.usage(), undefined)
261 const usd = cost?.cost?.usd
262 // The total starts at 0 and falls back to 0 after /clear: a drop means a freshStats total, all of it new.
263 let grew
264 if (typeof usd === 'number') {
265 const base = sf.lastCost ?? 0
266 grew = usd >= base ? usd - base : usd
267 sf.lastCost = usd
268 }
269 addStep(sf.stats, { role: main ? 'main' : 'subagent', family, usage, usd: grew })
270 if (main && usage) {
271 const input = Number(usage.input_tokens) || 0
272 const cacheRead = Number(usage.cache_read_input_tokens) || 0
273 const cacheWrite = Number(usage.cache_creation_input_tokens) || 0
274 const verdict = classifyGap({ gapMs: sf.stepGap, input, cacheRead, cacheWrite })
275 if (verdict !== undefined) {
276 const hint = nextHint(await loadHint($), sf.stepGap, verdict)
277 sf.hint = hint
278 await safe(() => $.store.set('cache_hint', JSON.stringify(hint)), undefined)
279 }
280 sf.lastMainContext = input + cacheRead + cacheWrite
281 }
282 if (main) sf.lastMainEndAt = now
283 } catch (err) {
284 // The tallies are a convenience; never get in the way of a request.
285 }
286}
287
288// On a typed prompt: warn once per idle gap if the cache has probably gone cold.
289async function cacheOnPrompt($) {
290 try {
291 if ((await safe(() => $.env.get('CREW_CHIEF_CACHE_HINT'), undefined)) === 'off') return
292 if (sf.lastMainEndAt === undefined || sf.warnedFor === sf.lastMainEndAt) return
293 const now = await $.clock.now()
294 const gap = now - sf.lastMainEndAt
295 if (!shouldWarnCold(await loadHint($), gap, sf.lastMainContext)) return
296 sf.warnedFor = sf.lastMainEndAt
297 const lang = await resolveLang($)
298 $.ui.toast(t(lang, 'cache_cold', { idle: formatDuration(gap, unitsFor(lang)), tokens: fmtTokens(sf.lastMainContext) }), { timeoutMs: 12000 })
299 } catch (err) {
300 // A missing hint is better than a broken prompt.
301 }
302}
303
304async function buildStatsReport($) {
305 const lang = await resolveLang($)
306 const rows = statsRows(sf.stats)
307 if (rows.length === 0) return t(lang, 'report_none')
308 const out = [t(lang, 'report_title')]
309 for (const r of rows) {
310 out.push(
311 '- ' +
312 t(lang, 'report_row', {
313 role: t(lang, r.role === 'main' ? 'role_main' : 'role_subagent'),
314 model: r.family,
315 requests: r.requests,
316 input: fmtTokens(r.input),
317 cacheRead: fmtTokens(r.cacheRead),
318 cacheWrite: fmtTokens(r.cacheWrite),
319 output: fmtTokens(r.output),
320 usd: fmtUsd(r.usd),
321 }),
322 )
323 }
324 const total = await safe(() => $.session.usage(), undefined)
325 if (typeof total?.cost?.usd === 'number') out.push(t(lang, 'report_total', { usd: fmtUsd(total.cost.usd) }))
326 const share = routingShare(rows)
327 if (share.total > 0) out.push(t(lang, 'report_share', { sub: share.subagent, cheaper: share.cheaper }))
328 out.push(t(lang, 'report_note'))
329 return out.join('\n')
330}
331
332function registerStats(on) {
333 on('command.run', { command: 'crew-report' }, async ($) => ({ text: await buildStatsReport($) }))
334}
335
336// ===== reset-flow ============================================================
337// crew-chief reset flow: tells you when a plan limit you were close to has reset, and, when a limit
338// actually stops Claude, offers to send "continue" for you at the moment it resets. Part of the mod in
339// hooks/register.js.
340//
341// - Measurements only arrive after a response, so nothing would wake an idle session when a window
342// rolls over. A timer is set for each window that was close to full (90 % or more) and is due to
343// reset within 12 hours; it fires a toast at the reset time.
344// - A limit that really stops a turn arrives as the StopFailure event with error "rate_limit" (not the
345// 100 % mark: with usage credits you keep working past it). Then the person is asked whether to
346// send "continue" at the reset. Only on a yes, only for a reset within 6 hours, and never if the
347// person typed something in the meantime. The message says who sent it (it is not sent as the
348// person's own words).
349// CREW_CHIEF_RESET=off turns both off. Timers last as long as the session does.
350const NEAR_FULL_PERCENT = 90
351const TOAST_HORIZON_MS = 12 * 60 * 60 * 1000
352const CONTINUE_HORIZON_MS = 6 * 60 * 60 * 1000
353const BUFFER_MS = 15_000
354
355const CONTINUE_TEXT =
356 'crew-chief: the usage limit has reset, as the user asked in advance. Continue where you left off, with the same task.'
357
358let generation = 0
359
360function freshReset() {
361 return { scheduled: new Set(), planned: new Set(), never: false, asking: false, lastPromptAt: 0 }
362}
363
364let rf = freshReset()
365
366// A timer set before /clear or a new session must not act in the next one: each carries the generation
367// it was set in.
368function resetResetFlow() {
369 rf = freshReset()
370 generation += 1
371 open.reset = false
372}
373
374function resetNotePrompt(now) {
375 rf.lastPromptAt = now
376}
377
378async function off($) {
379 try {
380 return (await $.env.get('CREW_CHIEF_RESET')) === 'off'
381 } catch (err) {
382 return false
383 }
384}
385
386function resetMs(window) {
387 const at = typeof window.resetsAt === 'string' ? Date.parse(window.resetsAt) : NaN
388 return Number.isFinite(at) ? at : undefined
389}
390
391// Called with each usage reading. Sets one timer per (window, reset time) for a window that is close
392// to full and resets soon; the toast comes when the window rolls over, even if the session is idle.
393async function resetOnUsage($, usage) {
394 if (await off($)) return
395 const now = await $.clock.now()
396 for (const w of usage?.rateLimits ?? []) {
397 if (w.kind !== 'five_hour' && w.kind !== 'seven_day') continue
398 const at = resetMs(w)
399 if (at === undefined || w.percentUsed < NEAR_FULL_PERCENT) continue
400 const wait = at - now
401 const key = w.kind + '|' + at
402 if (wait <= 0 || wait > TOAST_HORIZON_MS || rf.scheduled.has(key)) continue
403 rf.scheduled.add(key)
404 const born = generation
405 $.clock.after(wait + BUFFER_MS, () => (born === generation ? announceReset($, w.kind) : undefined))
406 }
407}
408
409async function announceReset($, kind) {
410 if (await off($)) return
411 const lang = await resolveLang($)
412 $.ui.toast(t(lang, 'reset_toast', { window: windowName(lang, kind) }), { timeoutMs: 15000 })
413}
414
415// The window that stopped the turn: the fullest one that has a reset time in the future.
416function blockingWindow(usage, now) {
417 let best
418 for (const w of usage?.rateLimits ?? []) {
419 const at = resetMs(w)
420 if (at === undefined || at <= now) continue
421 if (best === undefined || w.percentUsed > best.window.percentUsed) best = { window: w, at }
422 }
423 return best
424}
425
426async function offerContinue($) {
427 if (rf.asking || open.saver || open.compact || open.reset) return
428 const now = await $.clock.now()
429 const usage = await $.session.usage()
430 const hit = blockingWindow(usage, now)
431 if (!hit) return
432 const wait = hit.at - now
433 const key = hit.window.kind + '|' + hit.at
434 if (wait > CONTINUE_HORIZON_MS || rf.planned.has(key) || rf.never) return
435 rf.asking = true
436 open.reset = true
437 try {
438 const lang = await resolveLang($)
439 const answers = [t(lang, 'limit_yes'), t(lang, 'limit_no'), t(lang, 'limit_never')]
440 let answer
441 try {
442 answer = await $.ui.ask(
443 t(lang, 'limit_ask', { window: windowName(lang, hit.window.kind), duration: formatDuration(wait, unitsFor(lang)) }),
444 answers,
445 )
446 } catch (err) {
447 return
448 }
449 if (answer === answers[2]) {
450 rf.never = true
451 } else if (answer === answers[0]) {
452 rf.planned.add(key)
453 const askedAt = now
454 const born = generation
455 $.clock.after(wait + BUFFER_MS, () => (born === generation ? sendContinue($, askedAt, hit.window.kind) : undefined))
456 }
457 } finally {
458 rf.asking = false
459 open.reset = false
460 }
461}
462
463async function sendContinue($, askedAt, kind) {
464 if (await off($)) return
465 if (rf.lastPromptAt > askedAt) return // the person is back and typing: leave it to them
466 try {
467 $.prompt.submit({ text: CONTINUE_TEXT }).catch(() => {})
468 const lang = await resolveLang($)
469 $.ui.toast(t(lang, 'limit_continue_toast', { window: windowName(lang, kind) }), { timeoutMs: 10000 })
470 } catch (err) {
471 // The session cannot take a prompt right now; nothing more to do.
472 }
473}
474
475function registerReset(on) {
476 // StopFailure: a turn ended on an error. Only a rate limit matters here. (Settings-hook events do not
477 // reach a mod where an organization manages Claude Code; then the offer simply never comes.)
478 on('classic.StopFailure', async ($, e, next) => {
479 if (e.error === 'rate_limit' && !(await off($))) offerContinue($) // not awaited: the hook must not wait
480 return next(e)
481 })
482}
483
484// ===== compact-flow ==========================================================
485// crew-chief compact flow: gets a long conversation compacted at a good moment, with nothing important
486// lost, and only after the person says yes. Part of the mod in hooks/register.js (Claude Code 2.1.287+).
487//
488// How it works (every step below was checked live on Claude Code 2.1.300, see CHANGELOG 0.6.0):
489// 1. Past the "arm" size (250k tokens on a 1M window, 60 % of a small one) the next prompt carries a
490// one-time note telling Claude to call the tool crew_compact_checkpoint at the next natural phase
491// boundary (never mid-task). Claude decides when a phase is over.
492// 2. The tool asks the person. If Claude never calls it, the person is asked between turns once the
493// "ask" size is passed (400k, 85 % of a small window). Nothing is compacted without a yes.
494// 3. On yes, Claude updates STATUS.md / tasks.json / PROGRESS.md (the handoff files, when the project
495// has them). Compaction waits until STATUS.md has changed (the gate) or the person overrides.
496// 4. The compaction runs between turns with a detailed brief for the summarizer (compact-logic.mjs).
497// The same brief is added to a /compact the person types and to an automatic compaction.
498// 5. After any compaction: the raw summary is saved, the summary is checked for the person's pinned
499// constraints and the open tasks, a toast says what was missing, and the transcript is checked for
500// lost lines. scripts/compact-restore.sh (SessionStart, compact) puts the pinned lines back.
501// Environment: CREW_CHIEF_COMPACT=off turns the whole flow off; CREW_CHIEF_COMPACT_FOCUS=off only stops
502// the brief being added to compactions; CREW_CHIEF_COMPACT_ARM / CREW_CHIEF_COMPACT_ASK set the sizes
503// ("250k", "400k"). Nothing leaves the machine.
504const TOOL_NAME = 'crew_compact_checkpoint'
505const TOOL_MATCH = /^mcp__.+__crew_compact_checkpoint$/
506const REARM_GROWTH_TOKENS = 100_000
507const COMPACT_DELAY_MS = 1200
508const RETRY_MS = 3000
509const MAX_RETRIES = 3
510const SUMMARIES_KEPT = 5
511const TRANSCRIPTS_KEPT = 3
512const MAX_UPDATE_RETRIES = 2
513const AGENT_WAIT_MS = 5000
514const MAX_AGENT_WAITS = 36
515// `waiting` is a subagent held on background work it owns (a server it started), on a plan's approval or
516// on another agent: none of these is work that a compaction would cut in half, and a subagent that left a
517// dev server running stays `waiting` for as long as the server lives, so it must never hold a compaction back.
518const RUNNING_STATES = ['pending', 'running']
519
520const TOOL_DESCRIPTION =
521 'Propose compacting the conversation. Call it once, and only when a note from crew-chief says the context is large AND you have just finished a phase (a task done, tests passing, before an unrelated area). Never call it in the middle of work. It asks the user; if they decline, do not call it again.'
522
523const UPDATE_TEXT =
524 'Update the handoff files of this project now, for those that exist: STATUS.md (Now, Next, Constraints = every rule the user gave, copied verbatim; keep the lines already there and only add new ones, Decisions, Failed attempts), tasks.json (only status and evidence change), PROGRESS.md (one dated line). If STATUS.md has no Constraints section, do not invent one; say so in your reply. Do not start any new work. Finish with one short line; the conversation is compacted right after your turn ends.'
525
526// A project with no handoff files has nowhere to pin the user's rules, so the person is offered them first
527// (the crew-handoff skill shows a preview and creates only what is missing; it needs a yes of its own).
528const SETUP_TEXT =
529 'This project has no handoff files (STATUS.md, tasks.json, PROGRESS.md), so nothing would put the user\'s rules back after the compaction. Before it runs, ask the user once (AskUserQuestion) whether to set them up now: run the crew-chief:crew-handoff skill, which shows a preview and creates only what is missing. If they agree, run it, then copy every rule the user gave in this conversation, verbatim, under Constraints in STATUS.md. If they decline, do nothing more about it. Do not start any new work. Finish with one short line; the conversation is compacted right after your turn ends.'
530
531async function updateText($) {
532 return (await findHandoff($)) ? UPDATE_TEXT : SETUP_TEXT
533}
534
535const RESULTS = {
536 declined: 'The user declined for now. Carry on with the work and do not call this tool again until you are told the context has grown.',
537 never: 'The user does not want compaction proposals for the rest of this session. Carry on and do not call this tool again.',
538 unavailable: 'The user cannot be asked right now. Carry on with the work.',
539 notNeeded: 'Not needed yet. Keep working; crew-chief will say when to propose a compaction.',
540 subagents: 'Subagents are still running. Call this tool again after they have finished and their results are in.',
541 busy: 'A compaction is already being arranged. Nothing more to do about it.',
542}
543
544function freshCompact(toolReady = false) {
545 return {
546 armed: false,
547 nudged: false,
548 never: false,
549 asking: false,
550 askedFallback: false,
551 rearmAt: 0,
552 plan: null,
553 compacting: false,
554 toolReady,
555 bgTasks: [],
556 }
557}
558
559let ck = freshCompact()
560
561// session.start does not fire after /clear, so the tool registered at the start is still there: keep
562// toolReady across a reset, and let compactSessionStart (a real start) decide it afresh.
563function resetCompact() {
564 ck = freshCompact(ck.toolReady)
565 open.compact = false
566}
567
568// Each compaction starts a freshCompact cycle: arm again at the arm size, note again, ask again, and no plan
569// left over from before it.
570function cycleDone() {
571 ck.armed = false
572 ck.nudged = false
573 ck.askedFallback = false
574 ck.rearmAt = 0
575 ck.plan = null
576 statsNoteBoundary()
577}
578
579// A mod must spell environment variable names as literals in $.env.get, so each switch is written out.
580async function disabled($) {
581 return (await safe(() => $.env.get('CREW_CHIEF_COMPACT'), undefined)) === 'off'
582}
583
584async function focusOff($) {
585 return (await disabled($)) || (await safe(() => $.env.get('CREW_CHIEF_COMPACT_FOCUS'), undefined)) === 'off'
586}
587
588// ---- the project's handoff files ------------------------------------------------------------
589
590async function mtimeOf($, path) {
591 if (!path) return undefined
592 const stat = await safe(() => $.fs.stat(path), undefined)
593 return stat ? stat.mtimeMs : undefined
594}
595
596// The gate: the main handoff file has been written since the person approved. A project without
597// handoff files has nothing to wait for.
598async function gateSatisfied($, plan) {
599 const h = await findHandoff($)
600 if (!h) return true
601 const main = h.status ?? h.tasks
602 const changed = await mtimeOf($, main)
603 return changed !== undefined && changed > plan.approvedAt
604}
605
606// ---- thresholds and the one-time note -------------------------------------------------------
607
608async function limits($, usage) {
609 const arm = parseTokens(await safe(() => $.env.get('CREW_CHIEF_COMPACT_ARM'), undefined))
610 const ask = parseTokens(await safe(() => $.env.get('CREW_CHIEF_COMPACT_ASK'), undefined))
611 return compactThresholds(usage?.context?.window, { arm, ask })
612}
613
614// Called after every measurement and finished turn. Arms the flow at the arm size; after a "not now"
615// it arms again only once the context has grown by another 100k.
616async function compactUpdate($, usage) {
617 if (await disabled($)) return
618 const tokens = usage?.context?.tokens
619 if (typeof tokens !== 'number' || ck.never || ck.plan || ck.compacting) return
620 const lim = await limits($, usage)
621 if (!ck.armed && tokens >= Math.max(lim.arm, ck.rearmAt)) {
622 ck.armed = true
623 ck.nudged = false
624 ck.askedFallback = false
625 }
626}
627
628// The text added (once per arming) to the next prompt, or undefined.
629async function compactNudge($) {
630 if (!ck.armed || ck.nudged || ck.never || ck.plan || ck.compacting || !ck.toolReady) return undefined
631 if (await disabled($)) return undefined
632 ck.nudged = true
633 const usage = await safe(() => $.session.usage(), undefined)
634 const tokens = usage?.context?.tokens
635 const name = `mcp__${$.plugin.name}__${TOOL_NAME}`
636 return `[crew-chief] The context is about ${tokensLabel(tokens)} tokens; quality and cost both get worse from here. At the next natural phase boundary (a task finished, tests passing, before starting an unrelated area; never in the middle of work) call the tool ${name} once with a one-line phase summary. It asks the user whether to compact. If they decline, carry on and do not call it again.`
637}
638
639// ---- asking and planning --------------------------------------------------------------------
640
641// ---- what is running right now ---------------------------------------------------------------
642// Subagents always end and bring a result back, so a compaction waits for them. A dev server or watcher
643// left open in the background never ends and compaction does not touch it, so those only get shown (and
644// named to the summarizer), never waited for. The processes come from the Stop event's background_tasks.
645
646async function agentCounts($) {
647 const list = await safe(() => $.agent.list(), [])
648 return {
649 running: list.filter((a) => RUNNING_STATES.includes(a.status)).length,
650 waiting: list.filter((a) => a.status === 'waiting').length,
651 }
652}
653
654async function runningAgents($) {
655 return (await agentCounts($)).running
656}
657
658async function dirtyFiles($) {
659 const r = await safe(() => $.process.run(['git', 'status', '--porcelain']), undefined)
660 if (!r || r.exitCode !== 0) return undefined
661 return r.stdout.split('\n').filter((line) => line.trim() !== '').length
662}
663
664function processNames() {
665 return ck.bgTasks.map((task) => task.command || task.description || task.id).filter(Boolean)
666}
667
668// With the task id: after a compaction Claude no longer remembers the handles of background tasks it started
669// (anthropics/claude-code#29193), so the summary should keep them.
670function processHandles() {
671 return ck.bgTasks.map((task) => (task.id ? task.id + ': ' : '') + (task.command || task.description || '')).filter(Boolean)
672}
673
674async function stateLine($, lang, agents, waiting) {
675 const parts = [t(lang, 'ck_state_agents', { n: agents })]
676 if (waiting > 0) parts.push(t(lang, 'ck_state_waiting', { n: waiting }))
677 const names = processNames()
678 if (names.length > 0) parts.push(t(lang, 'ck_state_shells', { n: names.length, list: names.slice(0, 3).map((n) => n.slice(0, 40)).join(', ') }))
679 const dirty = await dirtyFiles($)
680 if (dirty !== undefined) parts.push(t(lang, 'ck_state_dirty', { n: dirty }))
681 return t(lang, 'ck_state', { parts: parts.join(', ') })
682}
683
684async function askAndPlan($, why) {
685 if (ck.asking || open.saver || open.reset) return 'busy'
686 const { running: agents, waiting } = await agentCounts($)
687 if (agents > 0) return 'subagents'
688 ck.asking = true
689 open.compact = true
690 try {
691 const lang = await resolveLang($)
692 const usage = await safe(() => $.session.usage(), undefined)
693 const tokens = usage?.context?.tokens
694 const answers = [t(lang, 'ck_yes'), t(lang, 'ck_later'), t(lang, 'ck_never')]
695 const phase = why.phase ? t(lang, 'ck_phase', { phase: why.phase }) : ''
696 const state = await stateLine($, lang, agents, waiting)
697 let answer
698 try {
699 answer = await $.ui.ask(t(lang, 'ck_ask', { tokens: tokensLabel(tokens), phase, state }), answers)
700 } catch (err) {
701 return 'unavailable'
702 }
703 if (answer === answers[0]) {
704 ck.plan = { approvedAt: await $.clock.now(), retries: 0 }
705 return 'approved'
706 }
707 if (answer === answers[2]) {
708 ck.never = true
709 return 'never'
710 }
711 ck.armed = false
712 ck.rearmAt = (typeof tokens === 'number' ? tokens : 0) + REARM_GROWTH_TOKENS
713 return 'declined'
714 } finally {
715 ck.asking = false
716 open.compact = false
717 }
718}
719
720// Asks Claude, in a new turn, to update the handoff files (the path with no tool call to answer).
721async function requestStateUpdate($) {
722 const text = 'crew-chief: the user approved compacting this conversation. ' + (await updateText($))
723 $.prompt.submit({ text }).catch(() => {})
724}
725
726async function askFallback($) {
727 const outcome = await askAndPlan($, {})
728 if (outcome === 'approved') requestStateUpdate($)
729 else if (outcome === 'busy' || outcome === 'subagents') ck.askedFallback = false
730}
731
732async function advancePlan($) {
733 const plan = ck.plan
734 if (!plan || ck.asking || open.saver || open.reset) return
735 if (await gateSatisfied($, plan)) {
736 scheduleCompaction($)
737 return
738 }
739 const lang = await resolveLang($)
740 const answers = [t(lang, 'ck_gate_anyway'), t(lang, 'ck_gate_retry'), t(lang, 'ck_gate_cancel')]
741 ck.asking = true
742 open.compact = true
743 let answer
744 try {
745 answer = await $.ui.ask(t(lang, 'ck_gate_ask'), answers)
746 } catch (err) {
747 answer = answers[2]
748 } finally {
749 ck.asking = false
750 open.compact = false
751 }
752 if (answer === answers[0]) {
753 scheduleCompaction($)
754 } else if (answer === answers[1] && plan.retries < MAX_UPDATE_RETRIES) {
755 plan.retries += 1
756 requestStateUpdate($)
757 } else {
758 const usage = await safe(() => $.session.usage(), undefined)
759 const tokens = usage?.context?.tokens
760 ck.plan = null
761 ck.armed = false
762 ck.rearmAt = (typeof tokens === 'number' ? tokens : 0) + REARM_GROWTH_TOKENS
763 }
764}
765
766// Called after each finished main turn.
767// `reason` is how the turn ended. Only a turn that ended with an answer counts as a phase boundary: after an
768// interrupt (Esc) the update may be half done, and after an error or a refusal nothing was finished.
769async function compactTurnComplete($, usage, reason) {
770 if (await disabled($)) return
771 await compactUpdate($, usage)
772 const clean = reason === undefined || reason === 'answer'
773 if (ck.plan) {
774 if (clean) await advancePlan($)
775 return
776 }
777 if (!clean) return
778 const tokens = usage?.context?.tokens
779 if (!ck.armed || ck.never || ck.compacting || ck.asking || ck.askedFallback || typeof tokens !== 'number') return
780 const lim = await limits($, usage)
781 if (tokens >= lim.ask) {
782 ck.askedFallback = true
783 askFallback($) // not awaited: the hook must not wait for the person
784 }
785}
786
787// ---- running the compaction -----------------------------------------------------------------
788
789function scheduleCompaction($) {
790 ck.plan = null
791 ck.compacting = true
792 $.clock.after(COMPACT_DELAY_MS, () => runCompaction($, 0))
793}
794
795async function runCompaction($, attempt, waited = 0) {
796 let retry = false
797 // Subagents started since the approval would lose their place in a summary: wait until they are done.
798 if ((await runningAgents($)) > 0) {
799 if (waited < MAX_AGENT_WAITS) {
800 $.clock.after(AGENT_WAIT_MS, () => runCompaction($, attempt, waited + 1))
801 } else {
802 ck.compacting = false
803 await failed($, t(await resolveLang($), 'ck_agents_still'))
804 }
805 return
806 }
807 try {
808 const before = await transcriptLines($)
809 await copyTranscriptIfNeeded($)
810 const args = (await focusOff($)) ? {} : { instructions: withFocus('', backgroundNote(processHandles())) }
811 const result = await $.session.compact(args)
812 if (result && result.skip) {
813 await failed($, String(result.skip))
814 } else if (result && result.messages) {
815 cycleDone()
816 await afterCompaction($, result, before)
817 }
818 } catch (err) {
819 const message = String(err && err.message ? err.message : err)
820 // Mostly "a turn is running" (compaction waits for a gap between turns); a headless run can never do it.
821 if (attempt < MAX_RETRIES && !/headless|not available/i.test(message)) {
822 retry = true
823 $.clock.after(RETRY_MS, () => runCompaction($, attempt + 1))
824 } else {
825 await failed($, message)
826 }
827 } finally {
828 if (!retry) ck.compacting = false
829 }
830}
831
832async function failed($, reason) {
833 const lang = await resolveLang($)
834 $.ui.toast(t(lang, 'toast_compact_failed', { reason: reason.slice(0, 160) }), { timeoutMs: 12000 })
835}
836
837// ---- after a compaction ---------------------------------------------------------------------
838
839async function dataDir($) {
840 const fromEnv = await safe(() => $.env.get('CLAUDE_PLUGIN_DATA'), undefined)
841 if (fromEnv) return fromEnv
842 const home = await safe(() => $.env.get('HOME'), undefined)
843 const derived = pluginDataDir($.plugin.root, home)
844 if (derived) return derived
845 const tmp = (await safe(() => $.env.get('TMPDIR'), undefined)) || '/tmp'
846 return `${tmp.replace(/\/+$/, '')}/crew-chief-compact`
847}
848
849async function prune($, dir, prefix, keep) {
850 const entries = await safe(() => $.fs.list(dir), [])
851 for (const name of backupsToPrune(entries.map((e) => e.name), prefix, keep)) {
852 await safe(() => $.process.run(['rm', '-f', `${dir}/${name}`]), undefined)
853 }
854}
855
856async function backupSummary($, summary) {
857 const dir = `${await dataDir($)}/compact-summaries`
858 const path = `${dir}/${backupName('compact', await $.clock.now())}`
859 await $.fs.write(path, summary + '\n')
860 await safe(() => $.process.run(['chmod', '600', path]), undefined)
861 await prune($, dir, 'compact', SUMMARIES_KEPT)
862 return path
863}
864
865async function transcriptPath($) {
866 const home = await safe(() => $.env.get('HOME'), undefined)
867 const cwd = await safe(() => $.session.cwd(), undefined)
868 const id = await safe(() => $.session.id(), undefined)
869 if (!home || !cwd || !id) return undefined
870 const path = `${home}/.claude/projects/${projectDirName(cwd)}/${id}.jsonl`
871 return (await safe(() => $.fs.exists(path), false)) ? path : undefined
872}
873
874async function transcriptLines($) {
875 const path = await transcriptPath($)
876 if (!path) return undefined
877 const r = await safe(() => $.process.run(['wc', '-l', path]), undefined)
878 const n = r && r.exitCode === 0 ? Number(r.stdout.trim().split(/\s+/)[0]) : NaN
879 return Number.isFinite(n) ? n : undefined
880}
881
882// Claude Code appends to the transcript across a compaction, so the lines from before it stay
883// searchable (checked live on 2.1.300). If that ever stops being true the first compaction shows it,
884// and every later one copies the file first.
885async function copyTranscriptIfNeeded($) {
886 const kept = await safe(() => $.store.get('transcript_kept'), undefined)
887 if (kept !== 'false') return
888 const path = await transcriptPath($)
889 if (!path) return
890 const dir = `${await dataDir($)}/transcripts`
891 const copy = `${dir}/${backupName('session', await $.clock.now(), 'jsonl')}`
892 await safe(async () => {
893 await $.process.run(['mkdir', '-p', dir])
894 await $.process.run(['cp', '-p', path, copy])
895 await $.process.run(['chmod', '600', copy])
896 await prune($, dir, 'session', TRANSCRIPTS_KEPT)
897 }, undefined)
898}
899
900async function verifyTranscript($, before) {
901 if (before === undefined) return
902 const after = await transcriptLines($)
903 if (after === undefined) return
904 const lost = after < before
905 await safe(() => $.store.set('transcript_kept', lost ? 'false' : 'true'), undefined)
906 if (lost) {
907 const lang = await resolveLang($)
908 $.ui.toast(t(lang, 'toast_transcript_lost'), { timeoutMs: 12000 })
909 }
910}
911
912// What the person's files say should survive, checked against the summary Claude Code wrote.
913async function pinnedItems($) {
914 const h = await findHandoff($)
915 if (!h) return { constraints: [], tasks: [] }
916 const status = h.status ? await safe(() => $.fs.read(h.status), '') : ''
917 const tasks = h.tasks ? await safe(() => $.fs.read(h.tasks), '') : ''
918 return { constraints: parseStatus(typeof status === 'string' ? status : '').constraints, tasks: openTasks(typeof tasks === 'string' ? tasks : '') }
919}
920
921async function afterCompaction($, result, linesBefore) {
922 try {
923 const lang = await resolveLang($)
924 const summary = result.messages.map((m) => m.text).join('\n')
925 const path = await safe(() => backupSummary($, summary), undefined)
926 const found = checkSummary(summary, await pinnedItems($))
927 const missing = found.missingConstraints.length + found.missingTasks.length
928 if (missing > 0) $.ui.toast(t(lang, 'toast_compact_missing', { n: missing }), { timeoutMs: 15000 })
929 else $.ui.toast(path ? t(lang, 'toast_compact_done', { path }) : t(lang, 'toast_compact_done_plain'), { timeoutMs: 10000 })
930 await verifyTranscript($, linesBefore)
931 } catch (err) {
932 // The compaction itself succeeded; the extras are best effort.
933 }
934}
935
936// ---- registration ---------------------------------------------------------------------------
937
938// Called from the mod's session.start hook (a module may register each event only once).
939async function compactSessionStart($) {
940 resetCompact()
941 ck.toolReady = false
942 if (await disabled($)) return
943 try {
944 await $.tool.register({
945 name: TOOL_NAME,
946 description: TOOL_DESCRIPTION,
947 inputSchema: {
948 type: 'object',
949 properties: {
950 phase: { type: 'string', description: 'One line: the phase that was just finished.' },
951 next: { type: 'string', description: 'One line: what comes next.' },
952 },
953 },
954 isDeferred: false,
955 })
956 ck.toolReady = true
957 } catch (err) {
958 // An older Claude Code, or the name is taken: the fallback question still works.
959 }
960 try {
961 await $.command.register({
962 name: 'crew-compact',
963 description: t(await resolveLang($), 'cmd_compact_description'),
964 argumentHint: '',
965 })
966 } catch (err) {
967 // The name is taken: the tool and the fallback question still work.
968 }
969}
970
971const clip = (s) => (typeof s === 'string' ? s.replace(/\s+/g, ' ').trim().slice(0, 200) : '')
972
973function registerCompact(on) {
974 // The Stop event carries the session's background tasks; the processes among them are remembered for the
975 // question and for the summarizer. (Settings-hook events do not reach a mod where an organization manages
976 // Claude Code; the list then stays empty and only subagents are waited for.)
977 on('classic.Stop', async ($, e, next) => {
978 const tasks = Array.isArray(e.background_tasks) ? e.background_tasks : []
979 ck.bgTasks = tasks.filter((task) => task && typeof task.command === 'string' && task.command !== '' && !task.agent_type)
980 return next(e)
981 })
982
983 on('tool.call', { tool: TOOL_MATCH }, async ($, e) => {
984 if (e.agentId !== undefined) return { deny: 'Only the main conversation can propose a compaction.' }
985 if (!ck.armed || ck.never) return { result: RESULTS.notNeeded }
986 if (ck.plan || ck.compacting) return { result: RESULTS.busy }
987 const outcome = await askAndPlan($, { phase: clip(e.phase) })
988 if (outcome === 'approved') return { result: 'The user approved compaction. ' + (await updateText($)) }
989 return { result: RESULTS[outcome] ?? RESULTS.busy }
990 })
991
992 // Every compaction a person, the engine or another plugin starts passes here. (One this plugin starts
993 // does not: the call "runs through every hook but the calling one", so runCompaction passes the brief
994 // itself.)
995 on('session.compact', async ($, e, next) => {
996 if (e.agentId !== undefined || (await focusOff($))) return next(e)
997 const before = e.trigger === 'precompute' ? undefined : await transcriptLines($)
998 if (e.trigger !== 'precompute') await copyTranscriptIfNeeded($)
999 // The engine always sends the transcript with the event; a call without it is passed on without one.
1000 const input = e.messages === undefined ? (({ messages, ...rest }) => rest)(e) : e
1001 const result = await next({ ...input, instructions: withFocus(e.instructions, backgroundNote(processHandles())) })
1002 if (e.trigger !== 'precompute' && result && result.messages) {
1003 cycleDone()
1004 await afterCompaction($, result, before)
1005 }
1006 return result
1007 })
1008
1009 on('command.run', { command: 'crew-compact' }, async ($) => {
1010 const lang = await resolveLang($)
1011 if (await disabled($)) return { text: t(lang, 'cmd_compact_off') }
1012 if (ck.plan || ck.compacting || ck.asking) return { text: t(lang, 'cmd_compact_busy') }
1013 ck.never = false
1014 // A command must not hold the turn while the person answers; ask when the loop is free.
1015 $.clock.after(300, async () => {
1016 const outcome = await askAndPlan($, {})
1017 if (outcome === 'approved') requestStateUpdate($)
1018 else if (outcome === 'subagents') $.ui.toast(t(await resolveLang($), 'ck_wait_agents'), { timeoutMs: 10000 })
1019 })
1020 return { text: t(lang, 'cmd_compact_ok') }
1021 })
1022}
1023
1024// ===== tidy-flow =============================================================
1025// /crew-tidy: what in your context is oversized, repeated, or points at something that is gone.
1026// Part of the mod in hooks/register.js (Claude Code 2.1.287+).
1027//
1028// /crew-tidy a report (nothing is changed): the instruction and memory files Claude Code
1029// actually loaded (read from /context), measured against Anthropic's own limits;
1030// paths they mention that no longer exist; lines repeated across files; the
1031// handoff files' size and age; MCP servers and skills by token cost.
1032// /crew-tidy archive moves PROGRESS.md entries older than 60 days to PROGRESS-archive.md. It shows
1033// the count and asks first; the archive is written and read back before the
1034// source is rewritten; nothing is deleted; an entry whose date is unclear stays.
1035// Files under ~/.claude (your global ones) are only ever reported. Memory files are never rewritten.
1036const NAMES_SHOWN = 5
1037
1038function dirOf(path) {
1039 const at = path.lastIndexOf('/')
1040 return at > 0 ? path.slice(0, at) : '/'
1041}
1042
1043function baseOf(path) {
1044 return path.slice(path.lastIndexOf('/') + 1)
1045}
1046
1047function shown(list) {
1048 return list.slice(0, NAMES_SHOWN).join(', ') + (list.length > NAMES_SHOWN ? ', …' : '')
1049}
1050
1051// The instruction and memory files this session loaded, with their text. The context breakdown names
1052// exactly those; without it (an older build) the usual project files are looked at instead.
1053async function loadedFiles($, breakdown, root, cwd) {
1054 let paths = (breakdown?.memoryFiles ?? []).map((f) => f.path)
1055 if (paths.length === 0) {
1056 paths = [`${root}/CLAUDE.md`, `${root}/CLAUDE.local.md`, `${cwd}/CLAUDE.md`]
1057 const rules = await safe(() => $.fs.list(`${root}/.claude/rules`), [])
1058 for (const r of rules) if (r.kind === 'file' && r.name.endsWith('.md')) paths.push(`${root}/.claude/rules/${r.name}`)
1059 }
1060 const files = []
1061 for (const path of [...new Set(paths)]) {
1062 if (!(await safe(() => $.fs.exists(path), false))) continue
1063 const text = await safe(() => $.fs.read(path), undefined)
1064 if (typeof text === 'string') files.push({ path, text })
1065 }
1066 return files
1067}
1068
1069async function pathExists($, ref, root, cwd) {
1070 const candidates = ref.startsWith('/') ? [ref] : [`${root}/${ref}`, `${cwd}/${ref}`]
1071 for (const c of candidates) {
1072 if (await safe(() => $.fs.exists(c.replace(/\/+$/, '')), false)) return true
1073 }
1074 return false
1075}
1076
1077async function buildTidyReport($) {
1078 const lang = await resolveLang($)
1079 const home = await safe(() => $.env.get('HOME'), '')
1080 const cwd = (await safe(() => $.session.cwd(), '')) || ''
1081 const root = (await safe(() => $.session.root(), cwd)) || cwd
1082 const now = await $.clock.now()
1083 const usage = await safe(() => $.session.usage({ breakdown: 'summary' }), undefined)
1084 const breakdown = usage?.context?.breakdown
1085 const findings = []
1086 const globals = []
1087
1088 const files = await loadedFiles($, breakdown, root, cwd)
1089 for (const file of files) {
1090 const global = isGlobalPath(file.path, home)
1091 if (global) globals.push(file.path)
1092 const size = measure(file.text)
1093 const memoryIndex = baseOf(file.path) === 'MEMORY.md'
1094 if (memoryIndex) {
1095 if (size.lines > MEMORY_LINES || size.bytes > MEMORY_BYTES) {
1096 findings.push(t(lang, 'tidy_memory_long', { path: file.path, lines: size.lines, kb: kb(size.bytes) }))
1097 }
1098 const gone = []
1099 for (const link of memoryIndexLinks(file.text)) {
1100 if (!(await safe(() => $.fs.exists(`${dirOf(file.path)}/${link}`), false))) gone.push(link)
1101 }
1102 if (gone.length > 0) findings.push(t(lang, 'tidy_memory_missing', { path: file.path, n: gone.length, list: shown(gone) }))
1103 continue
1104 }
1105 if (size.lines > INSTRUCTION_LINES) {
1106 findings.push(t(lang, 'tidy_file_long', { path: file.path, lines: size.lines }))
1107 }
1108 const missing = []
1109 for (const ref of extractPathRefs(file.text)) {
1110 if (!(await pathExists($, ref, root, cwd))) missing.push(ref)
1111 }
1112 if (missing.length > 0) findings.push(t(lang, 'tidy_paths_missing', { path: file.path, n: missing.length, list: shown(missing) }))
1113 }
1114
1115 const dupes = findDuplicateLines(files.filter((f) => baseOf(f.path) !== 'MEMORY.md'))
1116 if (dupes.length > 0) findings.push(t(lang, 'tidy_dupes', { n: dupes.length, sample: dupes[0].line.slice(0, 80) }))
1117
1118 const handoff = await findHandoff($)
1119 if (handoff?.status) {
1120 const text = await safe(() => $.fs.read(handoff.status), '')
1121 const size = measure(text)
1122 if (size.bytes > STATUS_BYTES) findings.push(t(lang, 'tidy_status_big', { path: handoff.status, kb: kb(size.bytes) }))
1123 }
1124 if (handoff?.progress) {
1125 const text = await safe(() => $.fs.read(handoff.progress), '')
1126 const old = splitProgress(text, now, PROGRESS_ARCHIVE_DAYS).count
1127 if (old > 0) findings.push(t(lang, 'tidy_progress_old', { path: handoff.progress, n: old, days: PROGRESS_ARCHIVE_DAYS }))
1128 }
1129
1130 const mcp = summarizeMcp(breakdown?.mcpTools).filter((r) => r.tokens >= MCP_NOTABLE_TOKENS)
1131 for (const row of mcp) findings.push(t(lang, 'tidy_mcp', { server: row.server, count: row.count, tokens: row.tokens, loaded: row.loaded }))
1132
1133 const out = [t(lang, 'tidy_head')]
1134 out.push(...(findings.length > 0 ? findings.map((f) => '- ' + f) : [t(lang, 'tidy_none')]))
1135 if (breakdown) {
1136 const top = (breakdown.categories ?? [])
1137 .filter((c) => c.tokens > 0 && !/free|buffer/i.test(c.name))
1138 .sort((a, b) => b.tokens - a.tokens)
1139 .slice(0, NAMES_SHOWN)
1140 .map((c) => `${c.name} ${c.tokens}`)
1141 if (top.length > 0) out.push(t(lang, 'tidy_categories', { list: top.join(' · ') }))
1142 if (breakdown.skills) out.push(t(lang, 'tidy_skills', { n: breakdown.skills.totalSkills, tokens: breakdown.skills.tokens }))
1143 }
1144 if (globals.length > 0) out.push(t(lang, 'tidy_global', { list: shown(globals) }))
1145 return out.join('\n')
1146}
1147
1148async function archiveProgress($) {
1149 const lang = await resolveLang($)
1150 const handoff = await findHandoff($)
1151 if (!handoff?.progress) return t(lang, 'tidy_archive_nofile')
1152 const source = handoff.progress
1153 const original = await safe(() => $.fs.read(source), undefined)
1154 if (typeof original !== 'string') return t(lang, 'tidy_archive_failed', { reason: source })
1155 const now = await $.clock.now()
1156 const split = splitProgress(original, now, PROGRESS_ARCHIVE_DAYS)
1157 if (split.count === 0) return t(lang, 'tidy_archive_none', { days: PROGRESS_ARCHIVE_DAYS })
1158 const archive = source.replace(/\.md$/i, '') + '-archive.md'
1159 const yes = t(lang, 'tidy_archive_yes')
1160 const answers = [yes, t(lang, 'tidy_archive_no')]
1161 let answer
1162 try {
1163 answer = await $.ui.ask(t(lang, 'tidy_archive_ask', { n: split.count, days: PROGRESS_ARCHIVE_DAYS, path: baseOf(source), archive: baseOf(archive) }), answers)
1164 } catch (err) {
1165 return t(lang, 'tidy_archive_cancelled')
1166 }
1167 if (answer !== yes) return t(lang, 'tidy_archive_cancelled')
1168
1169 try {
1170 // The file may have changed while the question was open (another session, an editor): look again.
1171 const current = await $.fs.read(source)
1172 if (current !== original) return t(lang, 'tidy_archive_changed')
1173 const existing = (await $.fs.exists(archive)) ? await $.fs.read(archive) : ''
1174 const header = `# Archived from ${baseOf(source)}\n\nMoved by crew-chief when older than ${PROGRESS_ARCHIVE_DAYS} days. Nothing was deleted.\n\n`
1175 const next = (existing === '' ? header : existing.replace(/\n*$/, '\n\n')) + split.archived
1176 await $.fs.write(archive, next)
1177 const back = await $.fs.read(archive)
1178 if (!back.includes(split.archived.trim())) throw new Error('the archive did not read back as written')
1179 // Only now is the source rewritten. If that fails the entries are in both files: nothing is lost.
1180 await $.fs.write(source, split.keep)
1181 const kept = await $.fs.read(source)
1182 if (kept.trim() !== split.keep.trim()) {
1183 await $.fs.write(source, original)
1184 throw new Error('the source did not read back as written; it was restored')
1185 }
1186 } catch (err) {
1187 return t(lang, 'tidy_archive_failed', { reason: String(err && err.message ? err.message : err).slice(0, 160) })
1188 }
1189 return t(lang, 'tidy_archive_done', { n: split.count, archive })
1190}
1191
1192async function tidySessionStart($) {
1193 try {
1194 await $.command.register({
1195 name: 'crew-tidy',
1196 description: t(await resolveLang($), 'tidy_description'),
1197 argumentHint: '[archive]',
1198 })
1199 } catch (err) {
1200 // The name is taken: everything else still works.hooks/compact-logic.mjs 240 lines1// Pure helpers for the compact flow (hooks/compact-flow.mjs). No Claude Code API in here, so
2// tests/compact-logic.test.mjs can run them with plain Node.
3
4// ---- thresholds ----------------------------------------------------------------------------
5
6// Official docs give no recommended compaction point (only the default, about 967k on a 1M model).
7// Third-party reports put the drop in quality at 300-400k tokens, "highly task dependent", or at
8// 60-80 % of a 200k window. So the thresholds are absolute tokens, scaled down on small windows.
9export const ARM_TOKENS = 250_000
10export const ASK_TOKENS = 400_000
11export const ARM_FRACTION = 0.6
12export const ASK_FRACTION = 0.85
13
14// "250k" -> 250000, "1m" -> 1000000, "300000" -> 300000, anything else -> undefined.
15export function parseTokens(text) {
16 if (typeof text !== 'string') return undefined
17 const m = /^\s*(\d+(?:\.\d+)?)\s*([km]?)\s*$/i.exec(text)
18 if (!m) return undefined
19 const n = Number(m[1]) * (m[2].toLowerCase() === 'm' ? 1_000_000 : m[2].toLowerCase() === 'k' ? 1_000 : 1)
20 return Number.isFinite(n) && n >= 10_000 ? Math.round(n) : undefined
21}
22
23// The two points: `arm` (tell Claude to propose a checkpoint at a phase boundary) and `ask` (Claude
24// did not, so ask the person between turns). `ask` is always above `arm`.
25export function compactThresholds(windowTokens, overrides = {}) {
26 const win = typeof windowTokens === 'number' && windowTokens > 0 ? windowTokens : undefined
27 let arm = overrides.arm ?? (win ? Math.min(ARM_TOKENS, Math.round(win * ARM_FRACTION)) : ARM_TOKENS)
28 let ask = overrides.ask ?? (win ? Math.min(ASK_TOKENS, Math.round(win * ASK_FRACTION)) : ASK_TOKENS)
29 if (ask <= arm) ask = Math.round(arm * 1.25)
30 return { arm, ask }
31}
32
33// ---- the brief for the summarizer -----------------------------------------------------------
34
35export const FOCUS_MARKER = '[crew-chief compaction brief]'
36
37// Written to stand on its own. The documented API replaces the default summary prompt with
38// `instructions`; Claude Code's own /compact keeps it (checked live on 2.1.300: the default sections
39// were still in the summary). Either way nothing may be missing, so every default section is named.
40// The verification rules follow the one documented failure of compaction in Claude Code: output of a
41// killed process written into a summary as a finished result.
42export const FOCUS_BLOCK = [
43 FOCUS_MARKER,
44 'Write the summary as a working state that lets the next turn continue without asking anything again. It must be complete on its own: cover every section below even if no other instructions exist. Prefer completeness over brevity; drop repeated tool output, never facts.',
45 'Sections, in this order:',
46 '1. Primary request and intent: what the user wants overall and what they asked most recently, in their own words where the wording matters.',
47 '2. Constraints and rules the user stated (do not modify X, no commits, language or style, "ask before ..."): copy each one VERBATIM with its scope. Never merge, shorten or drop one. If a rule was later changed or withdrawn, say that.',
48 '3. Decisions and why: every choice made, the reason, and the options ruled out.',
49 '4. Key technical concepts and facts needed later.',
50 '5. Files and code: exact paths and names touched or in play, what changed in each, and the short snippets still needed.',
51 '6. Errors and fixes: what failed, the cause, what fixed it.',
52 '7. Verification status: for every command, test or process give its exit code and what was actually observed. Mark a result CONFIRMED only when it was read back from a file or store after the process ended (name it). Anything seen only in terminal output, or from a non-zero exit, a timeout or a killed process, is UNCONFIRMED; never write it as completed.',
53 '8. All user messages that carry instructions (not tool output), in order.',
54 '9. Done, in progress and not started: task ids or names from STATUS.md or tasks.json when the project has them. Refer to those files by path instead of copying them.',
55 '10. Pending tasks and the immediate next step, tied to the latest request.',
56 'Do not call tools; answer with the summary text only.',
57].join('\n')
58
59// The person's own /compact text (if any) stays first and untouched; the brief follows it. Adding it
60// twice is a no-op, so a second hook or a retry cannot double it.
61export function withFocus(userText, extra = '') {
62 const own = typeof userText === 'string' ? userText.trim() : ''
63 if (own.includes(FOCUS_MARKER)) return own
64 const block = extra === '' ? FOCUS_BLOCK : FOCUS_BLOCK + '\n' + extra
65 return own === '' ? block : own + '\n\n' + block
66}
67
68// What a process list says to the summarizer: dev servers and watchers keep running through a compaction,
69// and the only risk is that nobody remembers them and starts a second one.
70export function backgroundNote(tasks) {
71 const list = (Array.isArray(tasks) ? tasks : []).slice(0, 5).map((t) => String(t).slice(0, 100))
72 if (list.length === 0) return ''
73 return 'Background processes running right now (dev servers, watchers, long jobs): ' + list.join('; ') + '. Say in the summary that they are running, with their ids and commands, so nobody starts them a second time.'
74}
75
76// ---- STATUS.md and tasks.json ---------------------------------------------------------------
77
78const SECTION_KEYS = [
79 ['constraints', /^(constraints?|k[ıi]s[ıi]tlar|k[ıi]s[ıi]tlamalar)\b/i],
80 ['now', /^(now|[şs]u an|[şs]imdi)\b/i],
81 ['next', /^(next|s[ıi]rada|s[ıi]radaki)\b/i],
82 ['decisions', /^(decisions?|kararlar)\b/i],
83 ['failed', /^(failed|ba[şs]ar[ıi]s[ıi]z)\b/i],
84]
85
86// { constraints: [...], now: [...], ... }: the non-empty lines under each known `##` heading. A
87// template placeholder (`...`, `<what>`) or a table header row is not content.
88export function parseStatus(md) {
89 const out = { constraints: [], now: [], next: [], decisions: [], failed: [] }
90 if (typeof md !== 'string') return out
91 let current
92 for (const raw of md.split(/\r?\n/)) {
93 const heading = /^#{1,6}\s+(.*)$/.exec(raw)
94 if (heading) {
95 const title = heading[1].trim()
96 const hit = SECTION_KEYS.find(([, re]) => re.test(title))
97 current = hit ? hit[0] : undefined
98 continue
99 }
100 if (!current) continue
101 const line = raw.trim()
102 if (line === '' || /^\|?[\s:|-]+\|?$/.test(line)) continue
103 if (/^[-*]?\s*(\.\.\.|…)\s*$/.test(line) || /^[-*\d.\s]*<[^>]*>/.test(line)) continue
104 if (/^\|\s*topic\s*\|/i.test(line) || /^\|\s*konu\s*\|/i.test(line)) continue
105 out[current].push(line)
106 }
107 return out
108}
109
110// tasks.json -> the tasks that are not finished: { id, title, status, doneWhen }. Anything that does
111// not parse gives an empty list (the caller says nothing rather than guess).
112export function openTasks(jsonText) {
113 let data
114 try {
115 data = JSON.parse(jsonText)
116 } catch (err) {
117 return []
118 }
119 const list = Array.isArray(data) ? data : Array.isArray(data?.tasks) ? data.tasks : []
120 return list
121 .filter((t) => t && typeof t === 'object' && ['todo', 'in_progress', 'blocked'].includes(t.status))
122 .map((t) => ({ id: String(t.id ?? ''), title: String(t.title ?? ''), status: t.status, doneWhen: String(t.done_when ?? '') }))
123}
124
125// Strings that identify a line without needing the same wording: `code`, "quoted", ids like AUTH-01,
126// paths. When a line has none, its longest words are used (and half of them must appear).
127export function anchorsOf(line) {
128 const text = String(line)
129 const strong = []
130 for (const m of text.matchAll(/`([^`]{2,})`/g)) strong.push(m[1])
131 for (const m of text.matchAll(/["“”]([^"“”]{3,})["“”]/g)) strong.push(m[1])
132 for (const m of text.matchAll(/\b[A-Z][A-Z0-9]{1,}[-_]\d+\b/g)) strong.push(m[0])
133 for (const m of text.matchAll(/[\w.~-]+\/[\w./~-]+/g)) strong.push(m[0])
134 if (strong.length > 0) return { kind: 'strong', items: [...new Set(strong.map((s) => s.trim()))] }
135 const words = [...new Set(text.toLowerCase().split(/[^\p{L}\p{N}]+/u).filter((w) => w.length >= 6))]
136 words.sort((a, b) => b.length - a.length)
137 return { kind: 'words', items: words.slice(0, 4) }
138}
139
140function norm(s) {
141 return String(s).toLowerCase().replace(/\s+/g, ' ')
142}
143
144// Whether the summary still says what the line says, by its anchors. A line with no anchor at all
145// counts as present (nothing to test, and the restore block puts it back anyway).
146export function lineSurvives(summary, line) {
147 const hay = norm(summary)
148 const { kind, items } = anchorsOf(line)
149 if (items.length === 0) return true
150 const found = items.filter((i) => hay.includes(norm(i))).length
151 return kind === 'strong' ? found >= 1 : found >= Math.ceil(items.length / 2)
152}
153
154// What the summary lost from the person's pinned lines and the open tasks. Deterministic, no model.
155export function checkSummary(summary, { constraints = [], tasks = [] } = {}) {
156 const hay = norm(summary)
157 const missingConstraints = constraints.filter((c) => !lineSurvives(summary, c))
158 const missingTasks = tasks.filter((t) => {
159 if (t.id !== '' && hay.includes(norm(t.id))) return false
160 return !(t.title !== '' && lineSurvives(summary, t.title))
161 })
162 return { missingConstraints, missingTasks }
163}
164
165// ---- PROGRESS.md: archive by age ------------------------------------------------------------
166
167export const PROGRESS_ARCHIVE_DAYS = 60
168const DAY_MS = 86_400_000
169
170// Splits a dated log into what stays and what is old enough to archive. An entry starts at a line
171// like "- 2026-08-01: ..." (or "## 2026-08-01"); the lines under it belong to it, up to the next
172// entry or the next heading that is not a date. Everything else (the title, a rule, "## Log", a later
173// "## Conventions" section) is kept where it is. An entry whose date does not parse is kept too:
174// nothing is moved unless its date is certain.
175export function splitProgress(text, nowMs, days = PROGRESS_ARCHIVE_DAYS) {
176 const lines = String(text).split('\n')
177 const segments = [{ entry: false, lines: [] }]
178 const start = /^\s*(?:[-*]\s+|#{2,4}\s+)?(\d{4})-(\d{2})-(\d{2})\b/
179 for (const line of lines) {
180 const m = start.exec(line)
181 const last = segments[segments.length - 1]
182 if (m) {
183 const ms = Date.UTC(Number(m[1]), Number(m[2]) - 1, Number(m[3]))
184 const valid = Number.isFinite(ms) && new Date(ms).getUTCMonth() === Number(m[2]) - 1
185 segments.push({ entry: true, ms: valid ? ms : undefined, lines: [line] })
186 } else if (/^#{1,6}\s/.test(line)) {
187 // A heading that is not a date ends the entry above it.
188 if (last.entry) segments.push({ entry: false, lines: [line] })
189 else last.lines.push(line)
190 } else {
191 last.lines.push(line)
192 }
193 }
194 const cutoff = nowMs - days * DAY_MS
195 const isOld = (seg) => seg.entry && seg.ms !== undefined && seg.ms < cutoff
196 const old = segments.filter(isOld)
197 const kept = segments.filter((seg) => !isOld(seg))
198 const join = (list) => list.flatMap((seg) => seg.lines).join('\n').replace(/\n+$/, '')
199 return {
200 count: old.length,
201 keep: join(kept) + '\n',
202 archived: old.length > 0 ? join(old) + '\n' : '',
203 }
204}
205
206// ---- paths ----------------------------------------------------------------------------------
207
208// Claude Code names a project's folder by replacing every character that is not a letter or a digit
209// with "-" (checked on 2.1.300: "/private/tmp/x/.y" -> "-private-tmp-x--y").
210export function projectDirName(cwd) {
211 return String(cwd).replace(/[^A-Za-z0-9]/g, '-')
212}
213
214// ~/.claude/plugins/cache/<marketplace>/<name>/<version> -> ~/.claude/plugins/data/<name>-<marketplace>,
215// the folder Claude Code keeps for the plugin's own files. A plugin loaded from a plain directory has
216// none: undefined, and the caller uses a temporary folder instead.
217export function pluginDataDir(pluginRoot, home) {
218 const marker = '/plugins/cache/'
219 const at = String(pluginRoot).indexOf(marker)
220 if (at < 0 || typeof home !== 'string' || home === '') return undefined
221 const [marketplace, name] = String(pluginRoot)
222 .slice(at + marker.length)
223 .split('/')
224 if (!marketplace || !name) return undefined
225 const clean = (s) => s.replace(/[^A-Za-z0-9_-]/g, '-')
226 return `${String(pluginRoot).slice(0, at)}/plugins/data/${clean(name)}-${clean(marketplace)}`
227}
228
229// A file name that sorts by time and cannot escape its folder.
230export function backupName(prefix, ms, ext = 'md') {
231 const stamp = new Date(ms).toISOString().replace(/[-:]/g, '').replace(/\.\d+Z$/, 'Z')
232 return `${prefix.replace(/[^A-Za-z0-9_-]/g, '')}-${stamp}.${ext}`
233}
234
235// Which backups to delete so that only the newest `keep` remain (names sort by time).
236export function backupsToPrune(names, prefix, keep) {
237 const mine = names.filter((n) => n.startsWith(prefix + '-')).sort()
238 return mine.length > keep ? mine.slice(0, mine.length - keep) : []
239}
240hooks/coord.mjs 4 lines1// Which question is open right now, so the saver and the compact flow never ask at once.
2// No Claude Code API in here.
3export const open = { saver: false, compact: false, reset: false }
4hooks/report-logic.mjs 97 lines1// Pure helpers for /crew-report (token and cost by model and role) and the cache-cooling hint
2// (hooks/stats-flow.mjs). No Claude Code API in here, so tests/report-logic.test.mjs can run them.
3
4// ---- tokens and cost by model ---------------------------------------------------------------
5
6export function newStats() {
7 return new Map()
8}
9
10// One finished request: who made it ('main' or 'subagent'), the model family, its usage numbers, and
11// the cost that grew since the previous request ended (approximate when subagents run side by side).
12export function addStep(stats, { role, family, usage, usd }) {
13 const key = role + '|' + family
14 const row = stats.get(key) ?? { role, family, requests: 0, input: 0, cacheRead: 0, cacheWrite: 0, output: 0, usd: 0 }
15 row.requests += 1
16 row.input += Number(usage?.input_tokens) || 0
17 row.cacheRead += Number(usage?.cache_read_input_tokens) || 0
18 row.cacheWrite += Number(usage?.cache_creation_input_tokens) || 0
19 row.output += Number(usage?.output_tokens) || 0
20 row.usd += typeof usd === 'number' && usd > 0 ? usd : 0
21 stats.set(key, row)
22}
23
24export function statsRows(stats) {
25 return [...stats.values()].sort((a, b) => b.usd - a.usd || b.output - a.output)
26}
27
28// Of all output tokens, the share written by subagents, and the share written below the heavy tier
29// (Haiku or Sonnet): what routing is meant to move work onto.
30export function routingShare(rows) {
31 const total = rows.reduce((n, r) => n + r.output, 0)
32 if (total === 0) return { total: 0, subagent: 0, cheaper: 0 }
33 const sum = (pred) => rows.filter(pred).reduce((n, r) => n + r.output, 0)
34 return {
35 total,
36 subagent: Math.round((sum((r) => r.role === 'subagent') / total) * 100),
37 cheaper: Math.round((sum((r) => r.family === 'haiku' || r.family === 'sonnet') / total) * 100),
38 }
39}
40
41export function fmtTokens(n) {
42 if (typeof n !== 'number' || !Number.isFinite(n)) return '?'
43 if (n >= 1_000_000) return (n / 1_000_000).toFixed(1) + 'M'
44 if (n >= 1000) return Math.round(n / 1000) + 'k'
45 return String(Math.round(n))
46}
47
48export function fmtUsd(n) {
49 return typeof n === 'number' && Number.isFinite(n) ? '$' + n.toFixed(n < 10 ? 2 : 1) : '?'
50}
51
52// ---- the prompt cache going cold ------------------------------------------------------------
53// Claude Code gives a mod no way to read the main conversation's cache lifetime (5 minutes or 1 hour
54// depends on the account and settings), so it is learned from what the API reports: a request after an
55// idle gap that read almost nothing from the cache and wrote most of the context means the cache had
56// expired within that gap; one that read most of it means the cache was still alive. Until a gap has
57// shown an expiry, nothing is warned.
58
59export const CACHE_MIN_GAP_MS = 4 * 60 * 1000
60export const CACHE_WARN_MIN_TOKENS = 100_000
61
62// 'expired', 'alive', or undefined (too short a gap, or the numbers say nothing).
63export function classifyGap({ gapMs, input, cacheRead, cacheWrite }) {
64 const total = (Number(input) || 0) + (Number(cacheRead) || 0) + (Number(cacheWrite) || 0)
65 if (!(gapMs >= CACHE_MIN_GAP_MS) || total < 20_000) return undefined
66 if (cacheRead / total < 0.2 && cacheWrite / total >= 0.5) return 'expired'
67 if (cacheRead / total >= 0.7) return 'alive'
68 return undefined
69}
70
71// hint = { expiredMs?, aliveMs? }: the shortest gap seen to expire the cache, the longest seen to keep it.
72export function nextHint(hint, gapMs, verdict) {
73 const h = { ...hint }
74 if (verdict === 'expired') h.expiredMs = h.expiredMs === undefined ? gapMs : Math.min(h.expiredMs, gapMs)
75 if (verdict === 'alive') h.aliveMs = h.aliveMs === undefined ? gapMs : Math.max(h.aliveMs, gapMs)
76 return h
77}
78
79// Warn only when an expiry has been seen at a gap no longer than this one, the cache has not been seen
80// alive across a gap this long, and the context is big enough for the re-read to cost something.
81export function shouldWarnCold(hint, gapMs, contextTokens) {
82 if (!hint || hint.expiredMs === undefined) return false
83 if (typeof contextTokens !== 'number' || contextTokens < CACHE_WARN_MIN_TOKENS) return false
84 if (hint.aliveMs !== undefined && hint.aliveMs >= gapMs) return false
85 return gapMs >= hint.expiredMs
86}
87
88export function parseHint(text) {
89 try {
90 const h = JSON.parse(text)
91 const ok = (v) => typeof v === 'number' && Number.isFinite(v) && v > 0
92 return { expiredMs: ok(h?.expiredMs) ? h.expiredMs : undefined, aliveMs: ok(h?.aliveMs) ? h.aliveMs : undefined }
93 } catch (err) {
94 return {}
95 }
96}
97hooks/saver-i18n.mjs 345 lines1// Messages and language detection for the saver mod (hooks/register.js). Pure functions, no Claude
2// Code API, so tests/saver-i18n.test.mjs can run them with plain Node. Languages: English (the
3// fallback) and Turkish. Add a language by adding an object to MESSAGES with the same keys; the
4// parity test fails until every key and every {placeholder} matches English.
5
6export const MESSAGES = {
7 en: {
8 win_five_hour: '5-hour',
9 win_seven_day: 'weekly',
10 unit_d: 'd',
11 unit_h: 'h',
12 unit_m: 'm',
13 unit_lt: '<1m',
14 reset_in: ' It resets in {duration}.',
15 ask:
16 'Your {window} limit is {percent}% used.{reset} Turn on the token saver for this session? (Opus subagents run at medium effort, Sonnet at high at most.)',
17 answer_on: 'Turn on saver',
18 answer_not_now: 'Not now',
19 answer_never: "Don't ask again this session",
20 toast_saver_on: 'Saver is on for this session. /saver off switches it off.',
21 toast_age: 'This session was opened {duration} ago. A fresh one starts lean.',
22 ck_ask:
23 'Context is {tokens} tokens.{phase}{state} Compact now? Claude first updates STATUS.md and tasks.json (when they exist), then the conversation is compacted with a detailed brief so nothing important is lost.',
24 ck_phase: ' Claude reports a phase boundary: {phase}.',
25 ck_state: ' Now: {parts}.',
26 ck_state_agents: 'subagents running: {n}',
27 ck_state_waiting: 'waiting on background work or approval: {n}',
28 ck_state_shells: 'background processes: {n} ({list})',
29 ck_state_dirty: 'uncommitted files: {n}',
30 ck_wait_agents: 'Subagents are still running. Ask again when they have finished.',
31 ck_agents_still: 'subagents were still running after 3 minutes',
32 ck_yes: 'Yes, compact',
33 ck_later: 'Not now',
34 ck_never: "Don't ask again this session",
35 ck_gate_ask: 'STATUS.md / tasks.json have not changed since you approved. What now?',
36 ck_gate_anyway: 'Compact anyway',
37 ck_gate_retry: 'Ask Claude to update first',
38 ck_gate_cancel: 'Cancel',
39 toast_compact_done: 'Compacted. Raw summary saved: {path}',
40 toast_compact_done_plain: 'Compacted.',
41 toast_compact_missing: '{n} pinned note(s) or open task(s) were missing from the summary; they are put back from the project files.',
42 toast_compact_failed: 'Compaction did not run: {reason}',
43 toast_transcript_lost: 'The transcript lost lines in the last compaction; later compactions keep a copy first.',
44 cmd_compact_description: 'crew-chief: propose a compaction now (updates the handoff files first)',
45 cmd_compact_ok: 'ok, I will ask when this turn ends.',
46 cmd_compact_busy: 'a compaction is already being arranged.',
47 cmd_compact_off: 'the compact flow is off (CREW_CHIEF_COMPACT=off).',
48 reset_toast: 'Your {window} limit has reset.',
49 limit_ask: 'Your {window} limit stopped Claude. It resets in {duration}. Send "continue" to Claude automatically when it resets? (Only if you have not typed anything by then.)',
50 limit_yes: 'Yes, continue at reset',
51 limit_no: 'No',
52 limit_never: "Don't ask again this session",
53 limit_continue_toast: 'Your {window} limit reset; asked Claude to continue.',
54 tidy_description: 'crew-chief: audit what fills your context (oversized, stale, repeated); "archive" moves old PROGRESS.md entries',
55 tidy_head: 'Context audit (nothing was changed):',
56 tidy_none: 'Nothing oversized, stale or repeated found in the files Claude loaded.',
57 tidy_file_long: '{path}: {lines} lines (the target is under 200). Move rarely needed parts to path-scoped rules or a skill.',
58 tidy_memory_long: '{path}: {lines} lines / {kb} KB. Only the first 200 lines or 25 KB are loaded; the rest is dropped silently.',
59 tidy_memory_missing: '{path}: {n} entries point to files that do not exist: {list}.',
60 tidy_paths_missing: '{path}: mentions {n} path(s) that do not exist here: {list}.',
61 tidy_dupes: '{n} line(s) appear in more than one loaded file, for example: "{sample}".',
62 tidy_status_big: '{path}: {kb} KB, read at every session start. Move old failed attempts to an archive.',
63 tidy_progress_old: '{path}: {n} entries older than {days} days. /crew-tidy archive moves them to an archive file (it asks first).',
64 tidy_mcp: 'MCP server {server}: {count} tools, about {tokens} tokens ({loaded} loaded now). Disable it if you are not using it.',
65 tidy_categories: 'Largest parts of the context (estimate): {list}',
66 tidy_skills: 'Skill listing: {n} skills, about {tokens} tokens.',
67 tidy_global: 'Your global files were only looked at, never changed: {list}',
68 tidy_archive_nofile: 'No PROGRESS.md (or ilerleme.md) found next to the project\'s STATUS.md.',
69 tidy_archive_none: 'No entry older than {days} days (or none with a clear date). Nothing to move.',
70 tidy_archive_ask: 'Move {n} entries older than {days} days from {path} to {archive}? Nothing is deleted.',
71 tidy_archive_yes: 'Move them',
72 tidy_archive_no: 'Cancel',
73 tidy_archive_cancelled: 'Cancelled. Nothing was changed.',
74 tidy_archive_failed: 'Could not archive: {reason}. Nothing was lost.',
75 tidy_archive_changed: 'The file changed while the question was open. Nothing was moved; run /crew-tidy archive again.',
76 tidy_archive_done: 'Moved {n} entries to {archive}. Nothing was deleted.',
77 cmd_report_description: 'crew-chief: tokens and cost by model and by main/subagent in this session',
78 role_main: 'main',
79 role_subagent: 'subagent',
80 report_title: 'This session by role and model:',
81 report_none: 'No requests recorded in this session yet.',
82 report_row: '{role} · {model}: {requests} requests · in {input} · cache read {cacheRead} · cache write {cacheWrite} · out {output} · about {usd}',
83 report_total: 'Session cost so far: {usd} (as /cost totals it).',
84 report_share: 'Subagents wrote {sub}% of the output tokens; {cheaper}% came from Sonnet or Haiku.',
85 report_note: 'Tokens are exact. Dollars are approximate: Claude Code gives one session total, so each request is credited with what the total grew by since the previous one ended.',
86 cache_cold: 'The prompt cache has probably gone cold ({idle} idle). This message re-reads about {tokens} tokens at the full price.',
87 toast_cap: 'Saver: {model} subagent effort {from} -> {to}',
88 model_heavy: 'Opus',
89 model_sonnet: 'Sonnet',
90 cmd_description: 'crew-chief token saver: on, off, or status (Opus subagents at medium effort)',
91 cmd_on: 'saver on for this session: Opus subagents at medium effort, Sonnet at high at most.',
92 cmd_off: 'saver off for this session; it will not ask again until /clear or a new session.',
93 cmd_usage: 'usage: /saver [on|off|status]',
94 status_on: 'saver ON',
95 status_off: 'saver off',
96 status_snoozed: ' (questions snoozed for this session)',
97 status_resets: ' (resets in {duration})',
98 status_no_data: 'no plan limit data (needs a Pro or Max subscription)',
99 status_context: 'context {tokens}',
100 percent: '{n}%',
101 model_opus: 'Opus',
102 model_fable: 'Fable',
103 model_haiku: 'Haiku',
104 advisor_ask_standard:
105 "The advisor is off. Turned on, {main} asks {advisor} for advice at hard moments (before choosing an approach, when stuck, before finishing). In Anthropic's own benchmarks Sonnet with an Opus advisor finished tasks about 12% cheaper and slightly better than Sonnet alone, and Haiku gained even more. It is experimental, and each consultation is billed at {advisor} rates. Turn it on? (/advisor off switches it off again.)",
106 advisor_ask_second:
107 "The advisor is off. Turned on, a second {advisor} reviews {main}'s plan at hard moments: an independent check, most useful for high-stakes work. It costs extra, since each consultation reads the whole conversation again at {advisor} rates, and it is experimental. Turn it on? (/advisor off switches it off again.)",
108 advisor_answer_on: 'Turn it on',
109 advisor_answer_later: 'Remind me in a week',
110 advisor_answer_never: "Don't ask again",
111 advisor_toast_on: 'Advisor set to {advisor}. /advisor off switches it off.',
112 advisor_toast_failed: 'Could not turn the advisor on from here. Run /advisor yourself to see why or to pick another model.',
113 },
114 tr: {
115 win_five_hour: '5 saatlik',
116 win_seven_day: 'haftalık',
117 unit_d: 'g',
118 unit_h: 'sa',
119 unit_m: 'dk',
120 unit_lt: '<1dk',
121 reset_in: ' {duration} sonra sıfırlanır.',
122 ask:
123 '{window} limitin %{percent} dolu.{reset} Bu session için token tasarruf modu açılsın mı? (Opus alt ajanları medium, Sonnet en fazla high effort ile çalışır.)',
124 answer_on: 'Tasarruf modunu aç',
125 answer_not_now: 'Şimdi değil',
126 answer_never: "Bu session'da bir daha sorma",
127 toast_saver_on: 'Tasarruf modu bu session için açık. Kapatmak için /saver off.',
128 toast_age: 'Bu session {duration} önce açıldı. Yeni bir session daha hafif başlar.',
129 ck_ask:
130 'Bağlam {tokens} token.{phase}{state} Şimdi compact edelim mi? Önce Claude STATUS.md ve tasks.json dosyalarını (varsa) günceller, sonra konuşma, önemli hiçbir şey kaybolmasın diye ayrıntılı bir talimatla compact edilir.',
131 ck_phase: ' Claude bir faz sonu bildirdi: {phase}.',
132 ck_state: ' Şu an: {parts}.',
133 ck_state_agents: 'çalışan alt ajan: {n}',
134 ck_state_waiting: 'arka plan işini ya da onayı bekleyen: {n}',
135 ck_state_shells: 'arka plan süreci: {n} ({list})',
136 ck_state_dirty: 'commit’lenmemiş dosya: {n}',
137 ck_wait_agents: 'Alt ajanlar hâlâ çalışıyor. Bitince tekrar sor.',
138 ck_agents_still: 'alt ajanlar 3 dakika sonra hâlâ çalışıyordu',
139 ck_yes: 'Evet, compact et',
140 ck_later: 'Şimdi değil',
141 ck_never: "Bu session'da bir daha sorma",
142 ck_gate_ask: 'Onayından beri STATUS.md / tasks.json değişmedi. Ne yapalım?',
143 ck_gate_anyway: 'Yine de compact et',
144 ck_gate_retry: 'Önce Claude güncellesin',
145 ck_gate_cancel: 'Vazgeç',
146 toast_compact_done: 'Compact tamam. Ham özet yedeği: {path}',
147 toast_compact_done_plain: 'Compact tamam.',
148 toast_compact_missing: 'Özette {n} sabit not/açık görev yoktu; proje dosyalarından geri yüklendi.',
149 toast_compact_failed: 'Compact çalışmadı: {reason}',
150 toast_transcript_lost: 'Son compact transcript satırlarını kaybettirdi; sonraki compact’lar önce kopya alacak.',
151 cmd_compact_description: 'crew-chief: şimdi compact öner (önce handoff dosyalarını günceller)',
152 cmd_compact_ok: 'tamam, bu turn bitince soracağım.',
153 cmd_compact_busy: 'bir compact zaten hazırlanıyor.',
154 cmd_compact_off: 'compact akışı kapalı (CREW_CHIEF_COMPACT=off).',
155 reset_toast: '{window} limitin sıfırlandı.',
156 limit_ask: '{window} limitin Claude’u durdurdu. {duration} sonra sıfırlanır. Sıfırlanınca Claude’a otomatik "devam et" gönderilsin mi? (O arada sen bir şey yazmadıysan.)',
157 limit_yes: 'Evet, reset olunca devam ettir',
158 limit_no: 'Hayır',
159 limit_never: "Bu session'da bir daha sorma",
160 limit_continue_toast: '{window} limitin sıfırlandı; Claude’dan devam etmesini istedim.',
161 tidy_description: 'crew-chief: context’i dolduranları denetle (şişkin, bayat, tekrarlı); "archive" eski PROGRESS.md girdilerini taşır',
162 tidy_head: 'Context denetimi (hiçbir şey değiştirilmedi):',
163 tidy_none: 'Claude’un yüklediği dosyalarda şişkin, bayat ya da tekrarlı bir şey bulunmadı.',
164 tidy_file_long: '{path}: {lines} satır (hedef 200’ün altı). Nadir gereken kısımları yola özel kurallara ya da bir skill’e taşı.',
165 tidy_memory_long: '{path}: {lines} satır / {kb} KB. Yalnızca ilk 200 satır ya da 25 KB yüklenir, kalanı sessizce düşer.',
166 tidy_memory_missing: '{path}: {n} girdi olmayan dosyalara işaret ediyor: {list}.',
167 tidy_paths_missing: '{path}: burada olmayan {n} yoldan söz ediyor: {list}.',
168 tidy_dupes: '{n} satır birden fazla yüklü dosyada geçiyor, örneğin: "{sample}".',
169 tidy_status_big: '{path}: {kb} KB, her session başında okunuyor. Eski başarısız denemeleri bir arşive taşı.',
170 tidy_progress_old: '{path}: {days} günden eski {n} girdi var. /crew-tidy archive bunları arşiv dosyasına taşır (önce sorar).',
171 tidy_mcp: 'MCP sunucusu {server}: {count} araç, yaklaşık {tokens} token (şu an {loaded} tanesi yüklü). Kullanmıyorsan kapat.',
172 tidy_categories: 'Context’in en büyük parçaları (tahmin): {list}',
173 tidy_skills: 'Skill listesi: {n} skill, yaklaşık {tokens} token.',
174 tidy_global: 'Global dosyalarına sadece bakıldı, hiçbiri değiştirilmedi: {list}',
175 tidy_archive_nofile: 'Projenin STATUS.md dosyasının yanında PROGRESS.md (ya da ilerleme.md) bulunamadı.',
176 tidy_archive_none: '{days} günden eski (ya da tarihi net olan) girdi yok. Taşınacak bir şey yok.',
177 tidy_archive_ask: '{path} dosyasındaki {days} günden eski {n} girdi {archive} dosyasına taşınsın mı? Hiçbir şey silinmez.',
178 tidy_archive_yes: 'Taşı',
179 tidy_archive_no: 'Vazgeç',
180 tidy_archive_cancelled: 'Vazgeçildi. Hiçbir şey değişmedi.',
181 tidy_archive_failed: 'Arşivlenemedi: {reason}. Hiçbir şey kaybolmadı.',
182 tidy_archive_changed: 'Soru açıkken dosya değişti. Hiçbir şey taşınmadı; /crew-tidy archive komutunu yeniden çalıştır.',
183 tidy_archive_done: '{n} girdi {archive} dosyasına taşındı. Hiçbir şey silinmedi.',
184 cmd_report_description: 'crew-chief: bu session’da model ve ana/alt ajan bazında token ve maliyet',
185 role_main: 'ana',
186 role_subagent: 'alt ajan',
187 report_title: 'Bu session, rol ve model bazında:',
188 report_none: 'Bu session’da henüz kayıtlı istek yok.',
189 report_row: '{role} · {model}: {requests} istek · girdi {input} · cache okuma {cacheRead} · cache yazma {cacheWrite} · çıktı {output} · yaklaşık {usd}',
190 report_total: 'Şu ana kadarki session maliyeti: {usd} (/cost’un topladığı gibi).',
191 report_share: 'Çıktı token’larının %{sub}’i alt ajanlardan, %{cheaper}’i Sonnet ya da Haiku’dan geldi.',
192 report_note: 'Token sayıları kesin. Dolar tutarları yaklaşık: Claude Code tek bir session toplamı veriyor, bu yüzden her isteğe önceki istek bittiğinden beri toplamın artışı yazılıyor.',
193 cache_cold: 'Prompt cache büyük ihtimalle soğudu ({idle} boşta kaldı). Bu mesaj yaklaşık {tokens} token’ı tam fiyattan yeniden okuyacak.',
194 toast_cap: 'Tasarruf: {model} alt ajanı effort {from} -> {to}',
195 model_heavy: 'Opus',
196 model_sonnet: 'Sonnet',
197 cmd_description: 'crew-chief token tasarrufu: on, off veya status (Opus alt ajanları medium effort)',
198 cmd_on: 'tasarruf modu bu session için açık: Opus alt ajanları medium, Sonnet en fazla high effort ile çalışır.',
199 cmd_off: "tasarruf modu bu session için kapalı; /clear ya da yeni session'a kadar bir daha sormaz.",
200 cmd_usage: 'kullanım: /saver [on|off|status]',
201 status_on: 'tasarruf modu AÇIK',
202 status_off: 'tasarruf modu kapalı',
203 status_snoozed: ' (bu session için sorular kapalı)',
204 status_resets: ' ({duration} sonra sıfırlanır)',
205 status_no_data: 'plan limiti verisi yok (Pro veya Max abonelik gerekir)',
206 status_context: 'bağlam {tokens}',
207 percent: '%{n}',
208 model_opus: 'Opus',
209 model_fable: 'Fable',
210 model_haiku: 'Haiku',
211 advisor_ask_standard:
212 "Advisor kapalı. Açıkken {main}, zor anlarda (yaklaşım seçmeden önce, takılınca, bitirmeden önce) {advisor} modeline danışır. Anthropic'in kendi ölçümlerinde Opus advisor'lı Sonnet görevleri tek başına Sonnet'ten yaklaşık %12 daha ucuza ve biraz daha iyi bitirdi, Haiku ise daha da çok kazandı. Deneysel; her danışma {advisor} fiyatından faturalanır. Açılsın mı? (Tekrar kapatmak için /advisor off.)",
213 advisor_ask_second:
214 'Advisor kapalı. Açıkken ikinci bir {advisor}, zor anlarda {main} modelinin planını gözden geçirir: bağımsız bir kontrol, en çok yüksek riskli işlerde işe yarar. Ek maliyeti var, çünkü her danışmada bütün konuşma {advisor} fiyatından yeniden okunur; ayrıca deneysel. Açılsın mı? (Tekrar kapatmak için /advisor off.)',
215 advisor_answer_on: 'Aç',
216 advisor_answer_later: 'Bir hafta sonra hatırlat',
217 advisor_answer_never: 'Bir daha sorma',
218 advisor_toast_on: 'Advisor {advisor} olarak ayarlandı. Kapatmak için /advisor off.',
219 advisor_toast_failed: 'Advisor buradan açılamadı. Nedenini görmek ya da başka bir model seçmek için /advisor komutunu kendin çalıştır.',
220 },
221}
222
223export const LANGUAGES = Object.keys(MESSAGES)
224
225// t('tr', 'toast_context', { tokens: '160k' }). An unknown language or key falls back to English;
226// a placeholder with no value is left as written.
227export function t(lang, key, vars = {}) {
228 const table = MESSAGES[lang] ?? MESSAGES.en
229 const template = table[key] ?? MESSAGES.en[key] ?? key
230 return template.replace(/\{(\w+)\}/g, (whole, name) => (name in vars ? String(vars[name]) : whole))
231}
232
233// 'five_hour' -> "5-hour" / "5 saatlik"; a window kind this plugin does not know is shown as is.
234export function windowName(lang, kind) {
235 if (kind === 'five_hour') return t(lang, 'win_five_hour')
236 if (kind === 'seven_day') return t(lang, 'win_seven_day')
237 return String(kind)
238}
239
240export function unitsFor(lang) {
241 return { d: t(lang, 'unit_d'), h: t(lang, 'unit_h'), m: t(lang, 'unit_m'), lt: t(lang, 'unit_lt') }
242}
243
244// ---- language detection -------------------------------------------------------------------
245
246// Letters only Turkish uses (dotless i, g with breve, s with cedilla). o/u with umlaut and c with
247// cedilla are shared with German, French and others, so they are not evidence.
248const TURKISH_LETTERS = /[ığşİĞŞ]/g
249
250// Only words that are Turkish and nothing else. Short words that other languages also use (mi, ne,
251// ve, var, ile, ben, ama, sen ...) are left out on purpose: French, Italian, Spanish and Dutch
252// writers must never be read as Turkish. scripts/plugin-notices.sh keeps the same two lists in awk;
253// tests/saver-i18n.test.mjs fails when they drift apart.
254export const TURKISH_WORDS = new Set([
255 'bir', 'bu', 'için', 'evet', 'hayır', 'tamam', 'bana', 'gibi', 'daha', 'çok', 'yap', 'yaz',
256 'bakalım', 'nasıl', 'neden', 'şu', 'bunu', 'şunu', 'olsun', 'olur', 'değil', 'lütfen', 'merhaba',
257 'selam', 'peki', 'hepsini', 'sonra', 'önce', 'kadar', 'göster', 'ekle', 'sil', 'düzelt', 'devam',
258 'başla', 'şimdi', 'zaten', 'çünkü', 'hangi', 'burada', 'yeni', 'eski', 'iyi', 'günler',
259 'günaydın', 'teşekkürler', 'sağol',
260])
261
262export const ENGLISH_WORDS = new Set([
263 'the', 'and', 'is', 'are', 'to', 'of', 'for', 'with', 'that', 'this', 'you', 'can', 'it', 'in',
264 'be', 'do', 'not', 'what', 'how', 'please', 'yes', 'fix', 'add', 'run', 'why', 'when', 'where',
265 'will', 'would', 'should', 'have', 'has', 'was', 'from', 'my', 'your', 'we', 'me', 'if', 'then',
266 'so', 'but', 'or', 'as', 'at', 'by', 'all', 'now', 'just', 'also', 'make', 'use', 'need', 'want',
267])
268
269// Drops what is code or log output, not prose: fenced blocks, indented lines, lines with braces,
270// semicolons, arrows, "()" or "::", shell prompts, "SomethingError:" lines and stack frames.
271// Keywords such as for/in/if/is/not would otherwise count as English.
272export function stripCode(text) {
273 const out = []
274 let fenced = false
275 for (const line of String(text).split(/\r?\n/)) {
276 if (/^\s*(```|~~~)/.test(line)) {
277 fenced = !fenced
278 continue
279 }
280 if (fenced) continue
281 if (/^(\s{4,}|\t)/.test(line)) continue
282 if (/[{};]|=>|\(\)|::|^\s*\$ |^\s*\w+Error:|\bat\s+\S+\s*\(/.test(line)) continue
283 out.push(line)
284 }
285 return out.join('\n')
286}
287
288// 'tr', 'en', or undefined when the text is too short, too mixed, or mostly code to tell. Turkish
289// needs a real Turkish word, or three distinctive letters in text with no English word at all (one
290// or two letters, or letters among English words, are a name like Ayşe, Barış or Çağrı) and at least as much evidence as English; with two or more Turkish words a tie goes to
291// Turkish (a Turkish sentence around a pasted English error message). English needs two common
292// English words and more of them than Turkish evidence.
293export function classifyText(text) {
294 if (typeof text !== 'string' || text.trim() === '' || text.trimStart().startsWith('/')) return undefined
295 const sample = stripCode(text.slice(0, 2000))
296 const letters = Math.min((sample.match(TURKISH_LETTERS) || []).length, 6)
297 let wordsTr = 0
298 let wordsEn = 0
299 // toLowerCase turns the dotted capital İ into i plus a combining dot; drop the dot.
300 for (const word of sample.toLowerCase().replace(/̇/g, '').split(/[^\p{L}]+/u)) {
301 if (word === '') continue
302 if (TURKISH_WORDS.has(word)) wordsTr += 1
303 if (ENGLISH_WORDS.has(word)) wordsEn += 1
304 }
305 const turkish = wordsTr * 2 + letters
306 const turkishLeads = turkish > wordsEn || (wordsTr >= 2 && turkish >= wordsEn)
307 if ((wordsTr >= 1 || (letters >= 3 && wordsEn === 0)) && turkish >= 2 && turkishLeads) return 'tr'
308 if (wordsEn >= 2 && wordsEn > turkish) return 'en'
309 return undefined
310}
311
312// The majority of the recent per-prompt verdicts; a tie or an empty list decides nothing.
313export function majority(votes) {
314 const tr = votes.filter((v) => v === 'tr').length
315 const en = votes.filter((v) => v === 'en').length
316 if (tr > en) return 'tr'
317 if (en > tr) return 'en'
318 return undefined
319}
320
321// "turkish", "Türkçe", "tr" -> 'tr'; "english", "en" -> 'en'; anything else (a language this plugin
322// has no messages for, "turkmen", or garbage) -> undefined, so detection moves on to the next signal.
323export function languageFromName(name) {
324 if (typeof name !== 'string') return undefined
325 const n = name.trim().toLowerCase().replace(/\u0307/g, '')
326 if (['tr', 'turkish', 'turkce', 'türkçe'].includes(n)) return 'tr'
327 if (['en', 'english', 'ingilizce'].includes(n)) return 'en'
328 return undefined
329}
330
331// Which language to speak, and which signal decided. Order: CREW_CHIEF_LANG, Claude Code's
332// `language` setting, what the person has been writing, what was detected in an earlier session,
333// the system locale, English.
334export function pickLanguage({ override, setting, votes = [], stored, locale } = {}) {
335 const fromOverride = languageFromName(override)
336 if (fromOverride) return { lang: fromOverride, source: 'override' }
337 const fromSetting = languageFromName(setting)
338 if (fromSetting) return { lang: fromSetting, source: 'setting' }
339 const fromVotes = majority(votes)
340 if (fromVotes) return { lang: fromVotes, source: 'prompts' }
341 if (stored === 'tr' || stored === 'en') return { lang: stored, source: 'stored' }
342 if (typeof locale === 'string' && /^tr([_.@-]|$)/i.test(locale.trim())) return { lang: 'tr', source: 'locale' }
343 return { lang: 'en', source: 'default' }
344}
345hooks/saver-logic.mjs 140 lines1// Pure helpers for the saver mod (hooks/register.js). No Claude Code API in here, so
2// tests/saver-logic.test.mjs can run them with plain Node.
3
4export const FIVE_HOUR_DEFAULT = [70, 80, 90]
5export const SEVEN_DAY_DEFAULT = [50, 75, 85, 90]
6export const SESSION_AGE_TOAST_MS = 8 * 60 * 60 * 1000
7
8const EFFORT_RANK = { low: 0, medium: 1, high: 2, xhigh: 3, max: 4 }
9
10// "70, 80,90" -> [70, 80, 90]. Anything that is not a whole number from 1 to 100 is dropped;
11// when nothing usable is left (or the variable is unset) the fallback list is used.
12export function parseThresholds(text, fallback) {
13 if (typeof text !== 'string' || text.trim() === '') return [...fallback]
14 const found = text
15 .split(',')
16 .map((part) => part.trim())
17 .filter((part) => /^\d{1,3}$/.test(part))
18 .map(Number)
19 .filter((n) => n >= 1 && n <= 100)
20 const unique = [...new Set(found)].sort((a, b) => a - b)
21 return unique.length > 0 ? unique : [...fallback]
22}
23
24// Which thresholds a window has newly crossed. `seen` holds keys for thresholds already acted on.
25// `top` is the highest new one (ask once for it); `crossed` lists the keys of every threshold at or
26// below the percent, so the caller can mark them all and never ask for the lower ones later.
27export function crossing(percent, thresholds, seen, keyPrefix) {
28 if (typeof percent !== 'number' || Number.isNaN(percent)) return { top: undefined, crossed: [] }
29 const reached = thresholds.filter((t) => percent >= t)
30 const fresh = reached.filter((t) => !seen.has(keyPrefix + t))
31 return {
32 top: fresh.length > 0 ? Math.max(...fresh) : undefined,
33 crossed: reached.map((t) => keyPrefix + t),
34 }
35}
36
37// 'claude-opus-5-5' / 'opus' -> 'heavy'; sonnet -> 'sonnet'; everything else -> 'other'.
38export function modelTier(model) {
39 const name = typeof model === 'string' ? model.toLowerCase() : ''
40 if (name.includes('opus') || name.includes('fable')) return 'heavy'
41 if (name.includes('sonnet')) return 'sonnet'
42 return 'other'
43}
44
45// The saver's effort ceiling for a subagent request. Opus and Fable run at medium at most,
46// Sonnet at high at most (no xhigh or max), everything else is left alone. A missing or numeric
47// effort is never touched.
48export function capEffort(model, effort) {
49 const rank = EFFORT_RANK[effort]
50 if (rank === undefined) return { effort, capped: false }
51 const tier = modelTier(model)
52 const ceiling = tier === 'heavy' ? 'medium' : tier === 'sonnet' ? 'high' : undefined
53 if (ceiling === undefined || rank <= EFFORT_RANK[ceiling]) return { effort, capped: false }
54 return { effort: ceiling, capped: true, from: effort, tier }
55}
56
57// crew-chief's own Opus agents. Their model comes from the agent definition, which a tool call does
58// not show, so they are named here; any other agent counts only when the call names an Opus or
59// Fable model itself.
60const HEAVY_AGENT = /(^|:)(implementer-hard|reviewer)$/
61
62// The effort the saver puts on an Agent tool call, or undefined to leave the call alone. The
63// subagent's own `effort:` in its definition beats a rewrite made later at turn.step (seen with
64// Claude Code 2.1.310: the hook wrote high -> medium and /tasks still showed high), but an effort
65// passed with the call is the more specific one. Only Opus and Fable agents, only downwards:
66// an explicit low or medium stays, and a call naming Sonnet or Haiku is never touched.
67export function agentCallEffort(input) {
68 if (input === null || typeof input !== 'object') return undefined
69 const model = typeof input.model === 'string' ? input.model : undefined
70 const type = typeof input.subagent_type === 'string' ? input.subagent_type : ''
71 const heavy = model !== undefined ? modelTier(model) === 'heavy' : HEAVY_AGENT.test(type)
72 if (!heavy) return undefined
73 const rank = EFFORT_RANK[input.effort]
74 if (input.effort !== undefined && (rank === undefined || rank <= EFFORT_RANK.medium)) return undefined
75 return 'medium'
76}
77
78// 6_300_000 -> "1h 45m", 90_000 -> "2m" (rounded up), 1 ms -> "1m", zero or invalid -> "<1m".
79// `units` renames the letters (see unitsFor in saver-i18n.mjs).
80export function formatDuration(ms, units = { d: 'd', h: 'h', m: 'm', lt: '<1m' }) {
81 if (typeof ms !== 'number' || !(ms > 0)) return units.lt
82 const minutes = Math.ceil(ms / 60_000)
83 if (minutes < 1) return units.lt
84 const days = Math.floor(minutes / 1440)
85 const hours = Math.floor((minutes % 1440) / 60)
86 const rest = minutes % 60
87 if (days > 0) return `${days}${units.d} ${hours}${units.h}`
88 if (hours > 0) return `${hours}${units.h} ${rest}${units.m}`
89 return `${rest}${units.m}`
90}
91
92export function tokensLabel(n) {
93 if (typeof n !== 'number') return '?'
94 return n >= 1000 ? `${Math.round(n / 1000)}k` : String(n)
95}
96
97// ---- advisor offer -------------------------------------------------------------------------
98
99export const ADVISOR_LATER_MS = 7 * 24 * 60 * 60 * 1000
100
101// 'claude-sonnet-5-5' -> 'sonnet'. Used to pick the advisor and to name the model in a message.
102export function modelFamily(model) {
103 const name = typeof model === 'string' ? model.toLowerCase() : ''
104 for (const family of ['fable', 'opus', 'sonnet', 'haiku']) {
105 if (name.includes(family)) return family
106 }
107 return 'other'
108}
109
110// Whether and how to offer the advisor for this main model. Sonnet and Haiku get the usual offer
111// (a stronger model on call); Opus and Fable get the "second opinion" wording, with the advisor
112// Claude Code accepts for them (Opus 5+ or Fable for Opus, only Fable for Fable). Unknown models
113// get nothing: the pairing rules are not known.
114export function advisorPlan(model) {
115 const family = modelFamily(model)
116 if (family === 'sonnet' || family === 'haiku') return { family, advisor: 'opus', kind: 'standard' }
117 if (family === 'opus') return { family, advisor: 'opus', kind: 'second' }
118 if (family === 'fable') return { family, advisor: 'fable', kind: 'second' }
119 return undefined
120}
121
122// What is stored under the `advisor` key: 'never' and 'answered' end the offers for good,
123// 'later:<ms>' pauses them until that time, anything else (including nothing) allows one.
124export function advisorOfferAllowed(stored, now) {
125 if (stored === 'never' || stored === 'answered') return false
126 if (typeof stored === 'string' && stored.startsWith('later:')) {
127 const until = Number(stored.slice('later:'.length))
128 // A pause longer than a week was written with a clock that has since moved back: ignore it.
129 return Number.isFinite(until) ? now >= until || until - now > ADVISOR_LATER_MS : true
130 }
131 return true
132}
133
134// An environment variable that switches something on: set, and not 0/false/no/off.
135export function isEnvFlag(value) {
136 if (typeof value !== 'string') return false
137 const v = value.trim().toLowerCase()
138 return v !== '' && !['0', 'false', 'no', 'off'].includes(v)
139}
140hooks/tidy-logic.mjs 95 lines1// Pure helpers for /crew-tidy (hooks/tidy-flow.mjs): what in the context is oversized, repeated, or
2// points at something that is gone. No Claude Code API in here, so tests/tidy-logic.test.mjs runs them.
3// Everything here only measures; deciding what to cut stays with the person.
4
5// Anthropic's guidance (checked 2026-10): a CLAUDE.md under about 200 lines; auto memory loads the
6// first 200 lines or 25 KB of MEMORY.md and drops the rest without a word.
7export const INSTRUCTION_LINES = 200
8export const MEMORY_LINES = 200
9export const MEMORY_BYTES = 25 * 1024
10// STATUS.md is read at every session start, so it pays for itself every time.
11export const STATUS_BYTES = 6 * 1024
12export const MCP_NOTABLE_TOKENS = 2000
13export const DUPLICATE_MIN_CHARS = 30
14
15export function measure(text) {
16 const s = String(text)
17 const lines = s === '' ? 0 : s.replace(/\n$/, '').split('\n').length
18 return { lines, bytes: new TextEncoder().encode(s).length }
19}
20
21// auto memory's index is a list of "- [Title](file.md) — hook" lines; the files they name.
22export function memoryIndexLinks(text) {
23 const out = []
24 for (const m of String(text).matchAll(/\]\(([^)\s#]+\.md)(?:#[^)\s]*)?\)/g)) {
25 if (!/^[a-z][a-z0-9+.-]*:/i.test(m[1]) && !m[1].startsWith('/')) out.push(m[1])
26 }
27 return [...new Set(out)]
28}
29
30const FILE_EXT = /\.(md|json|ya?ml|toml|lock|txt|sh|py|rb|go|rs|java|kt|swift|dart|js|jsx|mjs|cjs|ts|tsx|css|scss|html|sql|env|cfg|ini|gradle|plist)$/i
31
32// Paths written in `backticks` outside fenced blocks: the ones a reader could check against the
33// project folder. URLs, globs, placeholders, version-like words and home-relative paths are skipped,
34// so a finding is a real reference that leads nowhere, not a guess.
35export function extractPathRefs(text) {
36 const out = []
37 let fenced = false
38 for (const line of String(text).split(/\r?\n/)) {
39 if (/^\s*(```|~~~)/.test(line)) {
40 fenced = !fenced
41 continue
42 }
43 if (fenced) continue
44 for (const m of line.matchAll(/`([^`\s]{3,200})`/g)) {
45 const raw = m[1].replace(/[.,;:]+$/, '')
46 if (/[*?<>{}$|\\=()[\]"'!@#%^&+~]/.test(raw)) continue
47 if (/^[a-z][a-z0-9+.-]*:/i.test(raw)) continue
48 const looksLikePath = raw.includes('/') ? /^[\w.-]+(\/[\w.-]+)*\/$|^[\w.-]+(\/[\w.-]+)+$|^\.{0,2}\/[\w./-]+$/.test(raw) : FILE_EXT.test(raw)
49 if (!looksLikePath) continue
50 if (/^\d+(\.\d+)*$/.test(raw)) continue
51 out.push(raw)
52 }
53 }
54 return [...new Set(out)]
55}
56
57// Lines (long enough to mean something) that appear more than once in the files given together,
58// keyed by their trimmed text. Headings, tables, fences and list-only markers are not repeats.
59export function findDuplicateLines(files) {
60 const seen = new Map()
61 for (const file of files) {
62 for (const raw of String(file.text).split(/\r?\n/)) {
63 const line = raw.trim().replace(/^[-*]\s+/, '')
64 if (line.length < DUPLICATE_MIN_CHARS) continue
65 if (/^(#|\||```|~~~|<!--|---)/.test(line)) continue
66 const entry = seen.get(line) ?? { line, where: [] }
67 entry.where.push(file.path)
68 seen.set(line, entry)
69 }
70 }
71 return [...seen.values()].filter((e) => e.where.length > 1)
72}
73
74// MCP tools grouped by server: how many tools, how many tokens, how many are loaded now.
75export function summarizeMcp(tools) {
76 const by = new Map()
77 for (const tool of tools ?? []) {
78 const row = by.get(tool.serverName) ?? { server: tool.serverName, count: 0, tokens: 0, loaded: 0 }
79 row.count += 1
80 row.tokens += Number(tool.tokens) || 0
81 if (tool.isLoaded) row.loaded += 1
82 by.set(tool.serverName, row)
83 }
84 return [...by.values()].sort((a, b) => b.tokens - a.tokens)
85}
86
87// Whether a path is one of the person's global files (outside any project): reported, never changed.
88export function isGlobalPath(path, home) {
89 return typeof home === 'string' && home !== '' && String(path).startsWith(home + '/.claude/') && !String(path).includes('/.claude/projects/')
90}
91
92export function kb(bytes) {
93 return (bytes / 1024).toFixed(1)
94}
95