chompyy 0.4.0 → 0.4.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +7 -0
- package/dist/advice.js +383 -0
- package/dist/away.js +4 -1
- package/dist/blueprint.js +45 -0
- package/dist/board.js +61 -2
- package/dist/cli.js +138 -5
- package/dist/detect.js +568 -0
- package/dist/didwork.js +367 -0
- package/dist/nudge.js +438 -0
- package/dist/pacing.js +5 -0
- package/dist/premise.js +122 -0
- package/package.json +1 -1
package/dist/detect.js
ADDED
|
@@ -0,0 +1,568 @@
|
|
|
1
|
+
// `chompyy detect` (FEATURES §8, step 2 of the detective): runs the rulebook (research/detective/RULEBOOK.md) on
|
|
2
|
+
// your own local files and lists what it finds. This first version covers the two chapters that weigh most:
|
|
3
|
+
// startup tax (S2–S5: what loads before you type) and cache (C1, C2: context rebuilt from scratch).
|
|
4
|
+
//
|
|
5
|
+
// The rulebook's personality applies to every finding: evidence first with a count, measured vs estimated
|
|
6
|
+
// labelled, what it doesn't prove said out loud, no dollars on a subscription, smallest fix first.
|
|
7
|
+
import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs';
|
|
8
|
+
import { homedir } from 'node:os';
|
|
9
|
+
import { basename, dirname, join } from 'node:path';
|
|
10
|
+
import { projectsDir } from './dream.js';
|
|
11
|
+
/**
|
|
12
|
+
* Folders under ~/.claude/projects made by automated runs in temp folders (benchmarks, sandboxes, Chompyy's own
|
|
13
|
+
* cards): not your sessions, so they don't count for or against you.
|
|
14
|
+
*/
|
|
15
|
+
export const isAutomated = (folder) => /^-private-|^-var-folders-|^-tmp-|-T-|chompyy-worktrees|\.chompyy-worktrees/.test(folder);
|
|
16
|
+
const num = (v) => (typeof v === 'number' && Number.isFinite(v) ? v : 0);
|
|
17
|
+
export function readSession(file) {
|
|
18
|
+
const turns = new Map();
|
|
19
|
+
let cwd = '';
|
|
20
|
+
let id = basename(file, '.jsonl');
|
|
21
|
+
const skills = new Map();
|
|
22
|
+
const commands = new Map();
|
|
23
|
+
const mcp = new Map();
|
|
24
|
+
// What changed since the last request: read back when the next request says the tool list changed.
|
|
25
|
+
let loaded = [];
|
|
26
|
+
let after = '';
|
|
27
|
+
for (const line of readFileSync(file, 'utf8').split('\n')) {
|
|
28
|
+
if (!line.includes('"assistant"') && !line.includes('<command-name>') && !line.includes('deferred_tools_record'))
|
|
29
|
+
continue;
|
|
30
|
+
let e;
|
|
31
|
+
try {
|
|
32
|
+
e = JSON.parse(line);
|
|
33
|
+
}
|
|
34
|
+
catch {
|
|
35
|
+
continue;
|
|
36
|
+
}
|
|
37
|
+
if (!cwd && typeof e.cwd === 'string')
|
|
38
|
+
cwd = e.cwd;
|
|
39
|
+
const att = e.attachment;
|
|
40
|
+
if (e.type === 'attachment' && att?.type === 'deferred_tools_record' && att.entries?.length) {
|
|
41
|
+
// Tool Search loaded these tools into the list; an MCP tool counts as its server.
|
|
42
|
+
loaded = [...new Set(att.entries.map((x) => String(x.name ?? '')).filter(Boolean).map((n) => (n.startsWith('mcp__') ? n.split('__')[1] : n)))];
|
|
43
|
+
continue;
|
|
44
|
+
}
|
|
45
|
+
if (typeof e.sessionId === 'string')
|
|
46
|
+
id = e.sessionId;
|
|
47
|
+
const msg = e.message;
|
|
48
|
+
const content = msg?.content;
|
|
49
|
+
if (typeof content === 'string' || Array.isArray(content)) {
|
|
50
|
+
const text = typeof content === 'string' ? content : content.map((b) => (typeof b?.text === 'string' ? b.text : '')).join('');
|
|
51
|
+
for (const m of text.matchAll(/<command-name>\/?([^<\s]+)<\/command-name>/g)) {
|
|
52
|
+
commands.set(m[1], (commands.get(m[1]) ?? 0) + 1);
|
|
53
|
+
if (/^(mcp|model|plugin|config|permissions)$/.test(m[1]))
|
|
54
|
+
after = `/${m[1]}`;
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
if (e.type !== 'assistant' || !msg?.usage || e.isSidechain)
|
|
58
|
+
continue;
|
|
59
|
+
if (Array.isArray(content)) {
|
|
60
|
+
for (const b of content) {
|
|
61
|
+
if (b?.type !== 'tool_use' || !b.name)
|
|
62
|
+
continue;
|
|
63
|
+
if (b.name === 'Skill' && typeof b.input?.skill === 'string')
|
|
64
|
+
skills.set(b.input.skill, (skills.get(b.input.skill) ?? 0) + 1);
|
|
65
|
+
if (b.name.startsWith('mcp__')) {
|
|
66
|
+
const server = b.name.split('__')[1];
|
|
67
|
+
mcp.set(server, (mcp.get(server) ?? 0) + 1);
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
const u = msg.usage;
|
|
72
|
+
const cc = (u.cache_creation ?? {});
|
|
73
|
+
const diag = (msg.diagnostics ?? e.diagnostics) ?? {};
|
|
74
|
+
const reason = (diag.cache_miss_reason ?? {});
|
|
75
|
+
const key = msg.id ?? `${turns.size}`;
|
|
76
|
+
const turn = {
|
|
77
|
+
at: Date.parse(String(e.timestamp ?? '')) || 0,
|
|
78
|
+
cacheRead: num(u.cache_read_input_tokens),
|
|
79
|
+
cacheWrite: num(u.cache_creation_input_tokens),
|
|
80
|
+
wrote1h: num(cc.ephemeral_1h_input_tokens) > 0,
|
|
81
|
+
...(reason.type ? { miss: reason.type } : {}),
|
|
82
|
+
...(reason.cache_missed_input_tokens ? { missedTokens: num(reason.cache_missed_input_tokens) } : {}),
|
|
83
|
+
};
|
|
84
|
+
// One request is logged once per content block: keep the first time and the largest numbers.
|
|
85
|
+
const had = turns.get(key);
|
|
86
|
+
if (!had) {
|
|
87
|
+
if (turn.miss === 'tools_changed') {
|
|
88
|
+
if (loaded.length)
|
|
89
|
+
turn.loaded = loaded;
|
|
90
|
+
if (after)
|
|
91
|
+
turn.after = after;
|
|
92
|
+
}
|
|
93
|
+
loaded = [];
|
|
94
|
+
after = '';
|
|
95
|
+
}
|
|
96
|
+
turns.set(key, had ? { ...turn, at: had.at || turn.at, miss: had.miss ?? turn.miss, loaded: had.loaded, after: had.after, cacheWrite: Math.max(had.cacheWrite, turn.cacheWrite), cacheRead: Math.max(had.cacheRead, turn.cacheRead) } : turn);
|
|
97
|
+
}
|
|
98
|
+
if (!turns.size)
|
|
99
|
+
return null;
|
|
100
|
+
const session = {
|
|
101
|
+
id,
|
|
102
|
+
cwd,
|
|
103
|
+
turns: [...turns.values()].filter((t) => t.at).sort((a, b) => a.at - b.at),
|
|
104
|
+
};
|
|
105
|
+
return Object.assign(session, { skills, commands, mcp });
|
|
106
|
+
}
|
|
107
|
+
/** Your sessions from the last `days` days (by file time), automated runs left out. */
|
|
108
|
+
export function scan(opts = {}) {
|
|
109
|
+
const now = (opts.now ?? new Date()).getTime();
|
|
110
|
+
const since = now - (opts.days ?? 30) * 86_400_000;
|
|
111
|
+
const root = opts.root ?? projectsDir();
|
|
112
|
+
const out = { sessions: [], skills: new Map(), commands: new Map(), mcp: new Map(), firstAt: Infinity, lastAt: 0 };
|
|
113
|
+
if (!existsSync(root))
|
|
114
|
+
return { ...out, firstAt: 0 };
|
|
115
|
+
for (const folder of readdirSync(root)) {
|
|
116
|
+
if (isAutomated(folder))
|
|
117
|
+
continue;
|
|
118
|
+
const dir = join(root, folder);
|
|
119
|
+
let names;
|
|
120
|
+
try {
|
|
121
|
+
names = readdirSync(dir).filter((n) => n.endsWith('.jsonl'));
|
|
122
|
+
}
|
|
123
|
+
catch {
|
|
124
|
+
continue;
|
|
125
|
+
}
|
|
126
|
+
for (const n of names) {
|
|
127
|
+
const file = join(dir, n);
|
|
128
|
+
try {
|
|
129
|
+
if (statSync(file).mtimeMs < since)
|
|
130
|
+
continue;
|
|
131
|
+
}
|
|
132
|
+
catch {
|
|
133
|
+
continue;
|
|
134
|
+
}
|
|
135
|
+
const s = readSession(file);
|
|
136
|
+
if (!s || !s.turns.length)
|
|
137
|
+
continue;
|
|
138
|
+
out.sessions.push({ id: s.id, cwd: s.cwd, turns: s.turns });
|
|
139
|
+
out.firstAt = Math.min(out.firstAt, s.turns[0].at);
|
|
140
|
+
out.lastAt = Math.max(out.lastAt, s.turns.at(-1).at);
|
|
141
|
+
for (const [k, v] of s.skills)
|
|
142
|
+
out.skills.set(k, (out.skills.get(k) ?? 0) + v);
|
|
143
|
+
for (const [k, v] of s.commands)
|
|
144
|
+
out.commands.set(k, (out.commands.get(k) ?? 0) + v);
|
|
145
|
+
for (const [k, v] of s.mcp) {
|
|
146
|
+
const m = out.mcp.get(k) ?? { calls: 0, projects: new Set() };
|
|
147
|
+
m.calls += v;
|
|
148
|
+
m.projects.add(s.cwd);
|
|
149
|
+
out.mcp.set(k, m);
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
if (out.firstAt === Infinity)
|
|
154
|
+
out.firstAt = 0;
|
|
155
|
+
return out;
|
|
156
|
+
}
|
|
157
|
+
/** Characters ÷ 4: every tool uses this; label it estimated. */
|
|
158
|
+
export const tokensOf = (text) => Math.ceil(text.length / 4);
|
|
159
|
+
function skillAt(file, source, plugin) {
|
|
160
|
+
let text;
|
|
161
|
+
try {
|
|
162
|
+
text = readFileSync(file, 'utf8');
|
|
163
|
+
}
|
|
164
|
+
catch {
|
|
165
|
+
return null;
|
|
166
|
+
}
|
|
167
|
+
const front = text.match(/^---\n([\s\S]*?)\n---/)?.[1] ?? '';
|
|
168
|
+
const name = front.match(/^name:\s*(.+)$/m)?.[1]?.trim().replace(/^["']|["']$/g, '') || basename(dirname(file));
|
|
169
|
+
const description = front.match(/^description:\s*([\s\S]*?)(?=\n[a-z_-]+:|$)/m)?.[1]?.trim() ?? '';
|
|
170
|
+
return { name, calledAs: plugin ? `${plugin}:${name}` : name, descriptionTokens: tokensOf(`${name}: ${description}`), source, installedAt: statSync(file).mtimeMs, file };
|
|
171
|
+
}
|
|
172
|
+
const skillFiles = (dir, depth = 3) => {
|
|
173
|
+
if (!existsSync(dir))
|
|
174
|
+
return [];
|
|
175
|
+
const out = [];
|
|
176
|
+
for (const n of readdirSync(dir, { withFileTypes: true })) {
|
|
177
|
+
const p = join(dir, n.name);
|
|
178
|
+
if (n.isFile() && n.name === 'SKILL.md')
|
|
179
|
+
out.push(p);
|
|
180
|
+
else if (n.isDirectory() && depth > 0 && n.name !== 'node_modules' && !n.name.startsWith('_archived'))
|
|
181
|
+
out.push(...skillFiles(p, depth - 1));
|
|
182
|
+
}
|
|
183
|
+
return out;
|
|
184
|
+
};
|
|
185
|
+
/** A plugin's skills: the ones its manifest lists (it can ship more than it exposes), else everything under skills/. */
|
|
186
|
+
function pluginSkillFiles(installPath) {
|
|
187
|
+
try {
|
|
188
|
+
const manifest = JSON.parse(readFileSync(join(installPath, '.claude-plugin', 'plugin.json'), 'utf8'));
|
|
189
|
+
if (Array.isArray(manifest.skills)) {
|
|
190
|
+
return manifest.skills.filter((p) => typeof p === 'string').map((p) => (p.endsWith('SKILL.md') ? join(installPath, p) : join(installPath, p, 'SKILL.md'))).filter(existsSync);
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
catch { }
|
|
194
|
+
return skillFiles(join(installPath, 'skills'), 2);
|
|
195
|
+
}
|
|
196
|
+
/** Your skills (~/.claude/skills, including account-synced ones) and the skills of enabled plugins. */
|
|
197
|
+
export function installedSkills(claudeDir = join(homedir(), '.claude')) {
|
|
198
|
+
const skills = [];
|
|
199
|
+
const mine = join(claudeDir, 'skills');
|
|
200
|
+
for (const f of skillFiles(mine)) {
|
|
201
|
+
const s = skillAt(f, f.includes('/synced/') ? 'synced' : 'yours');
|
|
202
|
+
if (s)
|
|
203
|
+
skills.push(s);
|
|
204
|
+
}
|
|
205
|
+
let enabled = {};
|
|
206
|
+
try {
|
|
207
|
+
enabled = JSON.parse(readFileSync(join(claudeDir, 'settings.json'), 'utf8')).enabledPlugins ?? {};
|
|
208
|
+
}
|
|
209
|
+
catch { }
|
|
210
|
+
let installed = {};
|
|
211
|
+
try {
|
|
212
|
+
const j = JSON.parse(readFileSync(join(claudeDir, 'plugins', 'installed_plugins.json'), 'utf8'));
|
|
213
|
+
installed = j.plugins ?? j;
|
|
214
|
+
}
|
|
215
|
+
catch { }
|
|
216
|
+
for (const [id, on] of Object.entries(enabled)) {
|
|
217
|
+
if (!on)
|
|
218
|
+
continue;
|
|
219
|
+
const plugin = id.split('@')[0];
|
|
220
|
+
for (const inst of installed[id] ?? []) {
|
|
221
|
+
if (!inst.installPath)
|
|
222
|
+
continue;
|
|
223
|
+
for (const f of pluginSkillFiles(inst.installPath)) {
|
|
224
|
+
const s = skillAt(f, 'plugin', plugin);
|
|
225
|
+
if (s)
|
|
226
|
+
skills.push({ ...s, plugin: id });
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
return skills;
|
|
231
|
+
}
|
|
232
|
+
/** MCP servers from ~/.claude.json (user and per-project) and each project's .mcp.json. */
|
|
233
|
+
export function configuredMcp(workspaces, home = homedir()) {
|
|
234
|
+
const out = [];
|
|
235
|
+
try {
|
|
236
|
+
const j = JSON.parse(readFileSync(join(home, '.claude.json'), 'utf8'));
|
|
237
|
+
for (const n of Object.keys(j.mcpServers ?? {}))
|
|
238
|
+
out.push({ name: n, scope: 'user' });
|
|
239
|
+
for (const [p, v] of Object.entries(j.projects ?? {}))
|
|
240
|
+
for (const n of Object.keys(v.mcpServers ?? {}))
|
|
241
|
+
out.push({ name: n, scope: p });
|
|
242
|
+
}
|
|
243
|
+
catch { }
|
|
244
|
+
for (const w of new Set(workspaces)) {
|
|
245
|
+
try {
|
|
246
|
+
const j = JSON.parse(readFileSync(join(w, '.mcp.json'), 'utf8'));
|
|
247
|
+
for (const n of Object.keys(j.mcpServers ?? {}))
|
|
248
|
+
out.push({ name: n, scope: w });
|
|
249
|
+
}
|
|
250
|
+
catch { }
|
|
251
|
+
}
|
|
252
|
+
return out;
|
|
253
|
+
}
|
|
254
|
+
// ---------- the rules ----------
|
|
255
|
+
const DAY = 86_400_000;
|
|
256
|
+
const fmt = (n) => (n >= 1_000_000 ? `${(n / 1_000_000).toFixed(n >= 10_000_000 ? 0 : 1)}M` : n >= 1000 ? `${(n / 1000).toFixed(n >= 10_000 ? 0 : 1)}k` : String(Math.round(n)));
|
|
257
|
+
const median = (xs) => {
|
|
258
|
+
const s = [...xs].sort((a, b) => a - b);
|
|
259
|
+
return s.length ? (s.length % 2 ? s[(s.length - 1) / 2] : (s[s.length / 2 - 1] + s[s.length / 2]) / 2) : 0;
|
|
260
|
+
};
|
|
261
|
+
const home = (p) => p.replace(homedir(), '~');
|
|
262
|
+
/** S2: CLAUDE.md over 200 lines or 2,000 tokens, charged to the sessions that load it. */
|
|
263
|
+
export function ruleS2(s, claudeDir = join(homedir(), '.claude')) {
|
|
264
|
+
const files = new Map(); // file → sessions that load it
|
|
265
|
+
const userMd = join(claudeDir, 'CLAUDE.md');
|
|
266
|
+
for (const ses of s.sessions) {
|
|
267
|
+
for (const f of [userMd, ses.cwd ? join(ses.cwd, 'CLAUDE.md') : ''])
|
|
268
|
+
if (f && existsSync(f))
|
|
269
|
+
files.set(f, (files.get(f) ?? 0) + 1);
|
|
270
|
+
}
|
|
271
|
+
const out = [];
|
|
272
|
+
for (const [f, sessions] of files) {
|
|
273
|
+
const text = readFileSync(f, 'utf8');
|
|
274
|
+
const lines = text.split('\n').length;
|
|
275
|
+
const tokens = tokensOf(text);
|
|
276
|
+
if (lines <= 200 && tokens <= 2000)
|
|
277
|
+
continue;
|
|
278
|
+
out.push({
|
|
279
|
+
rule: 'S2',
|
|
280
|
+
title: 'CLAUDE.md is long',
|
|
281
|
+
say: `${home(f)} is ${lines} lines (~${fmt(tokens)} tokens), loaded in ${sessions} sessions.`,
|
|
282
|
+
basis: 'estimated',
|
|
283
|
+
tokens: tokens * sessions,
|
|
284
|
+
tokensHow: `~${fmt(tokens)} × ${sessions} sessions`,
|
|
285
|
+
notProve: "Long isn't wrong: some lines stop repeat mistakes.",
|
|
286
|
+
fix: 'Tier it: keep rules and key paths; move workflows into skills and guides into files read on demand. Every moved rule says where it went.',
|
|
287
|
+
lane: 'work',
|
|
288
|
+
});
|
|
289
|
+
}
|
|
290
|
+
return out;
|
|
291
|
+
}
|
|
292
|
+
/** S3: installed skills with no use, when there's enough history to say so. */
|
|
293
|
+
export function ruleS3(s, skills, now) {
|
|
294
|
+
const spanDays = s.sessions.length ? (s.lastAt - s.firstAt) / DAY : 0;
|
|
295
|
+
if (s.sessions.length < 20 || spanDays < 14)
|
|
296
|
+
return [];
|
|
297
|
+
const used = new Set([...s.skills.keys(), ...s.commands.keys()]);
|
|
298
|
+
const isUsed = (k) => used.has(k.calledAs) || used.has(k.name) || [...used].some((u) => u.endsWith(`:${k.name}`));
|
|
299
|
+
const unused = skills.filter((k) => !isUsed(k) && now - k.installedAt > DAY && !/chompyy/i.test(k.name));
|
|
300
|
+
if (unused.length < 5)
|
|
301
|
+
return [];
|
|
302
|
+
const tokens = unused.reduce((a, k) => a + k.descriptionTokens, 0);
|
|
303
|
+
const bySource = (src) => unused.filter((k) => k.source === src);
|
|
304
|
+
const parts = ['plugin', 'synced', 'yours'].map((src) => [src, bySource(src)]).filter(([, l]) => l.length);
|
|
305
|
+
const label = { plugin: 'from plugins', synced: 'synced from your claude.ai account', yours: 'in ~/.claude/skills' };
|
|
306
|
+
return [
|
|
307
|
+
{
|
|
308
|
+
rule: 'S3',
|
|
309
|
+
title: 'Unused skills load every session',
|
|
310
|
+
say: `${unused.length} of ${skills.length} skills unused in ${s.sessions.length} sessions over ${Math.round(spanDays)} days (${parts.map(([src, l]) => `${l.length} ${label[src]}`).join(', ')}): ~${fmt(tokens)} tokens every session start. E.g. ${unused.slice(0, 5).map((k) => k.calledAs).join(', ')}.`,
|
|
311
|
+
basis: 'estimated',
|
|
312
|
+
tokens: tokens * s.sessions.length,
|
|
313
|
+
tokensHow: `~${fmt(tokens)} × ${s.sessions.length} sessions`,
|
|
314
|
+
notProve: "Unused so far doesn't mean never needed.",
|
|
315
|
+
targets: {
|
|
316
|
+
// A plugin you never use goes off whole; one you use a little (≤3 skills, 10+ unused) goes off after
|
|
317
|
+
// copying the ones you use into your own skills.
|
|
318
|
+
plugins: [...new Set(skills.filter((k) => k.plugin).map((k) => k.plugin))].flatMap((id) => {
|
|
319
|
+
const of = skills.filter((k) => k.plugin === id);
|
|
320
|
+
const kept = of.filter(isUsed);
|
|
321
|
+
const idle = of.filter((k) => !isUsed(k));
|
|
322
|
+
if (kept.length > 3 || (kept.length && idle.length < 10))
|
|
323
|
+
return [];
|
|
324
|
+
return [{
|
|
325
|
+
id,
|
|
326
|
+
skills: idle.length,
|
|
327
|
+
tokens: idle.reduce((a, k) => a + k.descriptionTokens, 0),
|
|
328
|
+
...(kept.length ? { keep: kept.map((k) => ({ name: k.name, dir: dirname(k.file ?? '') })) } : {}),
|
|
329
|
+
}];
|
|
330
|
+
}),
|
|
331
|
+
synced: bySource('synced').map((k) => k.name),
|
|
332
|
+
yours: bySource('yours').map((k) => ({ name: k.name, file: k.file ?? '' })),
|
|
333
|
+
},
|
|
334
|
+
fix: [
|
|
335
|
+
bySource('plugin').length ? 'Turn off unused plugins (/plugin)' : '',
|
|
336
|
+
bySource('synced').length ? 'turn off unused synced skills in claude.ai settings' : '',
|
|
337
|
+
bySource('yours').length ? 'move your unused skills out of ~/.claude/skills (an _archived folder inside still loads)' : '',
|
|
338
|
+
].filter(Boolean).join('; ').replace(/^./, (c) => c.toUpperCase()) + '.',
|
|
339
|
+
lane: 'settings',
|
|
340
|
+
},
|
|
341
|
+
];
|
|
342
|
+
}
|
|
343
|
+
/** S4: configured MCP servers with no calls. */
|
|
344
|
+
export function ruleS4(s, servers) {
|
|
345
|
+
if (s.sessions.length < 2)
|
|
346
|
+
return [];
|
|
347
|
+
const idle = servers.filter((m) => !s.mcp.has(m.name));
|
|
348
|
+
if (!idle.length)
|
|
349
|
+
return [];
|
|
350
|
+
return [
|
|
351
|
+
{
|
|
352
|
+
rule: 'S4',
|
|
353
|
+
title: 'Unused MCP servers',
|
|
354
|
+
say: `${idle.length} MCP server${idle.length > 1 ? 's' : ''} never called in ${s.sessions.length} sessions: ${idle.map((m) => `${m.name} (${m.scope === 'user' ? 'all projects' : home(m.scope)})`).join(', ')}.`,
|
|
355
|
+
basis: 'estimated',
|
|
356
|
+
notProve: 'With Tool Search (the default), an idle server costs little at startup. One that reconnects mid-session still rebuilds the cache.',
|
|
357
|
+
fix: 'Remove it, or move it to the one project that uses it.',
|
|
358
|
+
lane: 'settings',
|
|
359
|
+
},
|
|
360
|
+
];
|
|
361
|
+
}
|
|
362
|
+
/** S5: MEMORY.md past what Claude Code loads (200 lines or 25 KB). */
|
|
363
|
+
export function ruleS5(root = projectsDir()) {
|
|
364
|
+
const out = [];
|
|
365
|
+
if (!existsSync(root))
|
|
366
|
+
return out;
|
|
367
|
+
for (const folder of readdirSync(root)) {
|
|
368
|
+
if (isAutomated(folder))
|
|
369
|
+
continue;
|
|
370
|
+
const f = join(root, folder, 'memory', 'MEMORY.md');
|
|
371
|
+
if (!existsSync(f))
|
|
372
|
+
continue;
|
|
373
|
+
const text = readFileSync(f, 'utf8');
|
|
374
|
+
const lines = text.split('\n').length;
|
|
375
|
+
const bytes = Buffer.byteLength(text);
|
|
376
|
+
if (lines <= 200 && bytes <= 25_000)
|
|
377
|
+
continue;
|
|
378
|
+
out.push({
|
|
379
|
+
rule: 'S5',
|
|
380
|
+
title: 'MEMORY.md is cut off',
|
|
381
|
+
say: `${home(f)} is ${lines} lines (${Math.round(bytes / 1000)} KB); only the first 200 lines or 25 KB load.`,
|
|
382
|
+
basis: 'measured',
|
|
383
|
+
fix: 'Compress it to one line per memory; move duplicates out.',
|
|
384
|
+
lane: 'work',
|
|
385
|
+
});
|
|
386
|
+
}
|
|
387
|
+
return out;
|
|
388
|
+
}
|
|
389
|
+
/** Each return after the cache expired: when, and what it wrote again (C1's test, shared with the nudge's trend). */
|
|
390
|
+
export function coldReturns(s, since) {
|
|
391
|
+
const out = [];
|
|
392
|
+
for (const ses of s.sessions) {
|
|
393
|
+
for (let i = 1; i < ses.turns.length; i++) {
|
|
394
|
+
const t = ses.turns[i];
|
|
395
|
+
const prev = ses.turns[i - 1];
|
|
396
|
+
if (t.at < since || t.miss !== 'previous_message_not_found')
|
|
397
|
+
continue;
|
|
398
|
+
const ttl = prev.wrote1h ? 60 * 60_000 : 5 * 60_000;
|
|
399
|
+
if (t.at - prev.at > ttl)
|
|
400
|
+
out.push({ at: t.at, tokens: t.cacheWrite });
|
|
401
|
+
}
|
|
402
|
+
}
|
|
403
|
+
return out;
|
|
404
|
+
}
|
|
405
|
+
/** C1: coming back after the cache expired, so the whole context is written again. */
|
|
406
|
+
export function ruleC1(s, now) {
|
|
407
|
+
const since = now - 14 * DAY;
|
|
408
|
+
const cold = [];
|
|
409
|
+
let allWrites = 0;
|
|
410
|
+
for (const ses of s.sessions) {
|
|
411
|
+
for (let i = 0; i < ses.turns.length; i++) {
|
|
412
|
+
const t = ses.turns[i];
|
|
413
|
+
if (t.at < since)
|
|
414
|
+
continue;
|
|
415
|
+
allWrites += t.cacheWrite;
|
|
416
|
+
const prev = ses.turns[i - 1];
|
|
417
|
+
if (!prev || t.miss !== 'previous_message_not_found')
|
|
418
|
+
continue;
|
|
419
|
+
const ttl = prev.wrote1h ? 60 * 60_000 : 5 * 60_000;
|
|
420
|
+
if (t.at - prev.at > ttl)
|
|
421
|
+
cold.push(t.cacheWrite);
|
|
422
|
+
}
|
|
423
|
+
}
|
|
424
|
+
const coldWrites = cold.reduce((a, b) => a + b, 0);
|
|
425
|
+
const share = allWrites ? coldWrites / allWrites : 0;
|
|
426
|
+
if (cold.length < 3 && share < 0.05)
|
|
427
|
+
return [];
|
|
428
|
+
return [
|
|
429
|
+
{
|
|
430
|
+
rule: 'C1',
|
|
431
|
+
title: 'Coming back after the cache expired',
|
|
432
|
+
say: `${cold.length} returns in 14 days after the cache expired (an hour idle): median ${fmt(median(cold))} tokens rewritten each, ${fmt(coldWrites)} in all, ${Math.round(share * 100)}% of your cache writes.`,
|
|
433
|
+
basis: 'measured',
|
|
434
|
+
notProve: "Some were worth it: context you'd otherwise rebuild.",
|
|
435
|
+
tokens: coldWrites,
|
|
436
|
+
// Never automated keep-warm pings (rulebook T2).
|
|
437
|
+
fix: 'Before a long break: /compact, or leave a note and start fresh.',
|
|
438
|
+
lane: 'habit',
|
|
439
|
+
},
|
|
440
|
+
];
|
|
441
|
+
}
|
|
442
|
+
/** C2: the cache thrown away mid-session (the tool list or earlier messages changed), with what caused it. */
|
|
443
|
+
export function ruleC2(s) {
|
|
444
|
+
const hits = [];
|
|
445
|
+
let sessionsHit = 0;
|
|
446
|
+
for (const ses of s.sessions) {
|
|
447
|
+
const here = ses.turns.filter((t) => t.miss === 'tools_changed' || t.miss === 'messages_changed');
|
|
448
|
+
hits.push(...here);
|
|
449
|
+
if (here.length)
|
|
450
|
+
sessionsHit++;
|
|
451
|
+
}
|
|
452
|
+
const size = (t) => t.missedTokens ?? t.cacheWrite;
|
|
453
|
+
if (sessionsHit < 2 && !hits.some((t) => size(t) >= 50_000))
|
|
454
|
+
return [];
|
|
455
|
+
const total = hits.reduce((a, t) => a + size(t), 0);
|
|
456
|
+
// Group by cause: "loaded claude-in-chrome", "/mcp", or unknown.
|
|
457
|
+
const causes = new Map();
|
|
458
|
+
for (const t of hits) {
|
|
459
|
+
const cause = t.miss === 'messages_changed' ? 'messages' : t.loaded?.length ? `loaded ${t.loaded.join(', ')}` : t.after ?? 'tools';
|
|
460
|
+
causes.set(cause, [...(causes.get(cause) ?? []), t]);
|
|
461
|
+
}
|
|
462
|
+
const sorted = [...causes].sort((x, y) => y[1].reduce((a, t) => a + size(t), 0) - x[1].reduce((a, t) => a + size(t), 0));
|
|
463
|
+
const said = (cause, ts) => {
|
|
464
|
+
const n = ts.length === 1 ? 'once' : `${ts.length}×`;
|
|
465
|
+
const sizes = ts.map((t) => fmt(size(t))).join(', ');
|
|
466
|
+
if (cause.startsWith('loaded '))
|
|
467
|
+
return `${n} after ${cause.slice(7)}'s tools loaded mid-session (${sizes})`;
|
|
468
|
+
if (cause.startsWith('/'))
|
|
469
|
+
return `${n} after ${cause} (${sizes})`;
|
|
470
|
+
if (cause === 'messages')
|
|
471
|
+
return `${n} after earlier messages changed (${sizes})`;
|
|
472
|
+
return `${n} after the tool list changed, cause not logged (${sizes})`;
|
|
473
|
+
};
|
|
474
|
+
const fixes = [];
|
|
475
|
+
const servers = [...new Set(hits.flatMap((t) => t.loaded ?? []))];
|
|
476
|
+
if (servers.length)
|
|
477
|
+
fixes.push(`Load ${servers.join(', ')} at the start of a session, or give that work its own session.`);
|
|
478
|
+
if (hits.some((t) => t.after))
|
|
479
|
+
fixes.push('Change MCP servers, models or plugins between sessions.');
|
|
480
|
+
if (hits.some((t) => t.miss === 'tools_changed' && !t.loaded?.length && !t.after))
|
|
481
|
+
fixes.push('Likely an MCP server reconnecting: turn flaky ones off for that project.');
|
|
482
|
+
if (hits.some((t) => t.miss === 'messages_changed'))
|
|
483
|
+
fixes.push('Rewinding or editing old messages rewrites the cache: start fresh instead.');
|
|
484
|
+
return [
|
|
485
|
+
{
|
|
486
|
+
rule: 'C2',
|
|
487
|
+
title: 'Cache thrown away mid-session',
|
|
488
|
+
say: `${hits.length} full rewrite${hits.length > 1 ? 's' : ''} mid-session in ${sessionsHit} session${sessionsHit > 1 ? 's' : ''}: ${sorted.map(([c, ts]) => said(c, ts)).join('; ')}.`,
|
|
489
|
+
basis: 'measured',
|
|
490
|
+
tokens: total,
|
|
491
|
+
fix: fixes.join(' '),
|
|
492
|
+
lane: 'habit',
|
|
493
|
+
},
|
|
494
|
+
];
|
|
495
|
+
}
|
|
496
|
+
export function detect(opts = {}) {
|
|
497
|
+
const now = (opts.now ?? new Date()).getTime();
|
|
498
|
+
const s = scan({ days: opts.days ?? 30, now: new Date(now), ...(opts.root ? { root: opts.root } : {}) });
|
|
499
|
+
const skills = installedSkills(opts.claudeDir);
|
|
500
|
+
const servers = configuredMcp(s.sessions.map((x) => x.cwd).filter(Boolean), opts.home);
|
|
501
|
+
const findings = [
|
|
502
|
+
...ruleC1(s, now),
|
|
503
|
+
...ruleC2(s),
|
|
504
|
+
...ruleS3(s, skills, now),
|
|
505
|
+
...ruleS2(s, opts.claudeDir),
|
|
506
|
+
...ruleS4(s, servers),
|
|
507
|
+
...ruleS5(opts.root),
|
|
508
|
+
];
|
|
509
|
+
// Baselines for the checks advice cards register before a fix: what a session start costs, and last week's cold returns.
|
|
510
|
+
const starts = s.sessions.map((x) => x.turns[0]).map((t) => t.cacheRead + t.cacheWrite).filter((n) => n > 0);
|
|
511
|
+
const week = coldReturns(s, now - 7 * DAY);
|
|
512
|
+
return {
|
|
513
|
+
scanned: {
|
|
514
|
+
sessions: s.sessions.length,
|
|
515
|
+
days: opts.days ?? 30,
|
|
516
|
+
skills: skills.length,
|
|
517
|
+
mcpServers: servers.length,
|
|
518
|
+
...(starts.length ? { startTokens: median(starts) } : {}),
|
|
519
|
+
coldWeek: { count: week.length, tokens: week.reduce((a, x) => a + x.tokens, 0) },
|
|
520
|
+
// The last 4 weeks, oldest first: the advice card's chart.
|
|
521
|
+
coldWeeks: [3, 2, 1, 0].map((w) => {
|
|
522
|
+
const xs = coldReturns(s, now - (w + 1) * 7 * DAY).filter((x) => x.at < now - w * 7 * DAY);
|
|
523
|
+
return { from: new Date(now - (w + 1) * 7 * DAY).toISOString(), count: xs.length, tokens: xs.reduce((a, x) => a + x.tokens, 0) };
|
|
524
|
+
}),
|
|
525
|
+
},
|
|
526
|
+
findings,
|
|
527
|
+
};
|
|
528
|
+
}
|
|
529
|
+
const short = (text) => text.split(/(?<=\.)\s/)[0];
|
|
530
|
+
/**
|
|
531
|
+
* One screen: what it read, the findings ranked by tokens, and the one fix to start with. `all` adds each
|
|
532
|
+
* finding's evidence, what it doesn't prove, and every fix.
|
|
533
|
+
*/
|
|
534
|
+
export function detectText(r, opts = {}) {
|
|
535
|
+
const { sessions, days, skills, mcpServers } = r.scanned;
|
|
536
|
+
if (!sessions) {
|
|
537
|
+
return [
|
|
538
|
+
`No Claude Code sessions from the last ${days} days in ${opts.projects ?? '~/.claude/projects'}.`,
|
|
539
|
+
'detect reads the transcripts Claude Code keeps on this computer. Use Claude Code for a few days, then run it again.',
|
|
540
|
+
];
|
|
541
|
+
}
|
|
542
|
+
const read = `Read ${sessions} sessions (last ${days} days), ${skills} skills, ${mcpServers} MCP servers. Nothing left this computer.`;
|
|
543
|
+
if (!r.findings.length)
|
|
544
|
+
return ['Nothing to fix in what this version checks (startup tax and cache).', '', read];
|
|
545
|
+
const ranked = [...r.findings].sort((a, b) => (b.tokens ?? -1) - (a.tokens ?? -1));
|
|
546
|
+
const cost = (f) => (f.tokens === undefined ? '' : `${f.basis === 'estimated' ? '~' : ''}${fmt(f.tokens)}`);
|
|
547
|
+
const cw = Math.max(...ranked.map((f) => cost(f).length));
|
|
548
|
+
const w = Math.max(...ranked.map((f) => f.title.length));
|
|
549
|
+
const lines = [`Start here: ${short(ranked[0].fix)}`, ''];
|
|
550
|
+
for (const f of ranked.slice(0, opts.all ? undefined : 5))
|
|
551
|
+
lines.push(` ${cost(f).padStart(cw)} ${f.title.padEnd(w)} ${f.basis}`);
|
|
552
|
+
if (!opts.all && ranked.length > 5)
|
|
553
|
+
lines.push(` …and ${ranked.length - 5} more: chompyy detect --all`);
|
|
554
|
+
lines.push('', read);
|
|
555
|
+
if (sessions < 20)
|
|
556
|
+
lines.push(`Only ${sessions} sessions: some checks need 20 over 14 days.`);
|
|
557
|
+
if (!opts.all) {
|
|
558
|
+
lines.push('Evidence and every fix: chompyy detect --all');
|
|
559
|
+
return lines;
|
|
560
|
+
}
|
|
561
|
+
for (const f of ranked) {
|
|
562
|
+
lines.push('', `${cost(f) ? `${cost(f)} · ` : ''}${f.title} (${f.basis}${f.tokensHow ? `: ${f.tokensHow}` : ''})`, ` ${f.say}`);
|
|
563
|
+
if (f.notProve)
|
|
564
|
+
lines.push(` Not proven: ${f.notProve}`);
|
|
565
|
+
lines.push(` Fix: ${f.fix}`);
|
|
566
|
+
}
|
|
567
|
+
return lines;
|
|
568
|
+
}
|