chompyy 0.3.0 → 0.4.1
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 +6 -3
- package/THIRD_PARTY_NOTICES.md +1 -1
- package/dist/appstate.js +81 -5
- package/dist/away.js +93 -16
- package/dist/blueprint.js +102 -7
- package/dist/board.js +110 -12
- package/dist/catalog.js +81 -0
- package/dist/cli.js +444 -56
- package/dist/coldstart.js +2 -1
- package/dist/config.js +7 -7
- package/dist/deps.js +124 -0
- package/dist/detect.js +511 -0
- package/dist/dream.js +422 -0
- package/dist/duration.js +3 -3
- package/dist/gate.js +11 -5
- package/dist/live.js +255 -0
- package/dist/livequota.js +27 -4
- package/dist/macapp.js +25 -2
- package/dist/pacing.js +5 -0
- package/dist/permissions.js +106 -0
- package/dist/picture.js +13 -6
- package/dist/picturetype.js +208 -0
- package/dist/preflight.js +168 -0
- package/dist/premise.js +122 -0
- package/dist/projects.js +3 -2
- package/dist/refresh.js +290 -0
- package/dist/report.js +3 -0
- package/dist/review.js +66 -9
- package/dist/runner.js +56 -8
- package/dist/taste.js +34 -13
- package/dist/tokens.js +75 -0
- package/dist/tokenstore.js +61 -0
- package/dist/trace.js +284 -0
- package/dist/triggers.js +16 -5
- package/dist/usage.js +467 -0
- package/dist/vendor/codeburn/prices.js +45 -0
- package/dist/verify.js +24 -5
- package/dist/verifycard.js +146 -0
- package/dist/workspace.js +132 -18
- package/package.json +3 -2
package/dist/detect.js
ADDED
|
@@ -0,0 +1,511 @@
|
|
|
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 };
|
|
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);
|
|
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) and loads in every session there: ${sessions} sessions in this scan.`,
|
|
282
|
+
basis: 'estimated',
|
|
283
|
+
tokens: tokens * sessions,
|
|
284
|
+
tokensHow: `~${fmt(tokens)} × ${sessions} sessions`,
|
|
285
|
+
notProve: "Long isn't wrong: lines that stop the agent repeating a mistake earn their place.",
|
|
286
|
+
fix: 'A card to tier it: keep identity, critical rules and key paths; move workflows into skills and long guides into files it reads when needed. No rule deleted without saying 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: 'Skills you never use still load every session',
|
|
310
|
+
say: `${unused.length} of ${skills.length} installed skills had no use in ${s.sessions.length} sessions over ${Math.round(spanDays)} days (${parts.map(([src, l]) => `${l.length} ${label[src]}`).join(', ')}). Their names and descriptions add ~${fmt(tokens)} tokens to every session start. Examples: ${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: "Not seeing a skill used doesn't prove you'll never need it.",
|
|
315
|
+
fix: [
|
|
316
|
+
bySource('plugin').length ? 'Turn off plugins you don\'t use (`/plugin`, or enabledPlugins in ~/.claude/settings.json)' : '',
|
|
317
|
+
bySource('synced').length ? 'turn off synced skills you don\'t use in claude.ai settings' : '',
|
|
318
|
+
bySource('yours').length ? 'move your own unused skills outside ~/.claude/skills (an _archived folder inside still loads)' : '',
|
|
319
|
+
].filter(Boolean).join('; ') + '.',
|
|
320
|
+
lane: 'settings',
|
|
321
|
+
},
|
|
322
|
+
];
|
|
323
|
+
}
|
|
324
|
+
/** S4: configured MCP servers with no calls. */
|
|
325
|
+
export function ruleS4(s, servers) {
|
|
326
|
+
if (s.sessions.length < 2)
|
|
327
|
+
return [];
|
|
328
|
+
const idle = servers.filter((m) => !s.mcp.has(m.name));
|
|
329
|
+
if (!idle.length)
|
|
330
|
+
return [];
|
|
331
|
+
return [
|
|
332
|
+
{
|
|
333
|
+
rule: 'S4',
|
|
334
|
+
title: 'MCP servers you never call',
|
|
335
|
+
say: `${idle.length} configured MCP server${idle.length > 1 ? 's were' : ' was'} never called in ${s.sessions.length} sessions: ${idle.map((m) => `${m.name} (${m.scope === 'user' ? 'all projects' : home(m.scope)})`).join(', ')}.`,
|
|
336
|
+
basis: 'estimated',
|
|
337
|
+
notProve: "With Tool Search deferral (the default now) an idle server costs little at startup. A server that reconnects mid-session does cost a cache rebuild, though (C2).",
|
|
338
|
+
fix: 'Remove it, or move it to the one project that needs it.',
|
|
339
|
+
lane: 'settings',
|
|
340
|
+
},
|
|
341
|
+
];
|
|
342
|
+
}
|
|
343
|
+
/** S5: MEMORY.md past what Claude Code loads (200 lines or 25 KB). */
|
|
344
|
+
export function ruleS5(root = projectsDir()) {
|
|
345
|
+
const out = [];
|
|
346
|
+
if (!existsSync(root))
|
|
347
|
+
return out;
|
|
348
|
+
for (const folder of readdirSync(root)) {
|
|
349
|
+
if (isAutomated(folder))
|
|
350
|
+
continue;
|
|
351
|
+
const f = join(root, folder, 'memory', 'MEMORY.md');
|
|
352
|
+
if (!existsSync(f))
|
|
353
|
+
continue;
|
|
354
|
+
const text = readFileSync(f, 'utf8');
|
|
355
|
+
const lines = text.split('\n').length;
|
|
356
|
+
const bytes = Buffer.byteLength(text);
|
|
357
|
+
if (lines <= 200 && bytes <= 25_000)
|
|
358
|
+
continue;
|
|
359
|
+
out.push({
|
|
360
|
+
rule: 'S5',
|
|
361
|
+
title: 'MEMORY.md is cut off',
|
|
362
|
+
say: `${home(f)} is ${lines} lines (${Math.round(bytes / 1000)} KB). Claude Code loads only the first 200 lines or 25 KB, so the rest never reaches the agent.`,
|
|
363
|
+
basis: 'measured',
|
|
364
|
+
fix: 'Compress the index to one line per memory, and move duplicates out.',
|
|
365
|
+
lane: 'work',
|
|
366
|
+
});
|
|
367
|
+
}
|
|
368
|
+
return out;
|
|
369
|
+
}
|
|
370
|
+
/** C1: coming back after the cache expired, so the whole context is written again. */
|
|
371
|
+
export function ruleC1(s, now) {
|
|
372
|
+
const since = now - 14 * DAY;
|
|
373
|
+
const cold = [];
|
|
374
|
+
let allWrites = 0;
|
|
375
|
+
for (const ses of s.sessions) {
|
|
376
|
+
for (let i = 0; i < ses.turns.length; i++) {
|
|
377
|
+
const t = ses.turns[i];
|
|
378
|
+
if (t.at < since)
|
|
379
|
+
continue;
|
|
380
|
+
allWrites += t.cacheWrite;
|
|
381
|
+
const prev = ses.turns[i - 1];
|
|
382
|
+
if (!prev || t.miss !== 'previous_message_not_found')
|
|
383
|
+
continue;
|
|
384
|
+
const ttl = prev.wrote1h ? 60 * 60_000 : 5 * 60_000;
|
|
385
|
+
if (t.at - prev.at > ttl)
|
|
386
|
+
cold.push(t.cacheWrite);
|
|
387
|
+
}
|
|
388
|
+
}
|
|
389
|
+
const coldWrites = cold.reduce((a, b) => a + b, 0);
|
|
390
|
+
const share = allWrites ? coldWrites / allWrites : 0;
|
|
391
|
+
if (cold.length < 3 && share < 0.05)
|
|
392
|
+
return [];
|
|
393
|
+
return [
|
|
394
|
+
{
|
|
395
|
+
rule: 'C1',
|
|
396
|
+
title: 'Coming back after the cache expired',
|
|
397
|
+
say: `${cold.length} times in the last 14 days you came back to a session after its cache had expired (an hour for the main conversation), so the whole context was written again: median ${fmt(median(cold))} tokens each, ${fmt(coldWrites)} in all, ${Math.round(share * 100)}% of your cache writes.`,
|
|
398
|
+
basis: 'measured',
|
|
399
|
+
notProve: "Some of these returns were worth it: a long session with context you'd otherwise have to rebuild.",
|
|
400
|
+
tokens: coldWrites,
|
|
401
|
+
fix: 'Before a long break, finish the thought and leave a short note; start fresh from the note when you return. Or /compact before leaving so the rewrite is small. Never automated keep-warm pings (rulebook T2).',
|
|
402
|
+
lane: 'habit',
|
|
403
|
+
},
|
|
404
|
+
];
|
|
405
|
+
}
|
|
406
|
+
/** C2: the cache thrown away mid-session (the tool list or earlier messages changed), with what caused it. */
|
|
407
|
+
export function ruleC2(s) {
|
|
408
|
+
const hits = [];
|
|
409
|
+
let sessionsHit = 0;
|
|
410
|
+
for (const ses of s.sessions) {
|
|
411
|
+
const here = ses.turns.filter((t) => t.miss === 'tools_changed' || t.miss === 'messages_changed');
|
|
412
|
+
hits.push(...here);
|
|
413
|
+
if (here.length)
|
|
414
|
+
sessionsHit++;
|
|
415
|
+
}
|
|
416
|
+
const size = (t) => t.missedTokens ?? t.cacheWrite;
|
|
417
|
+
if (sessionsHit < 2 && !hits.some((t) => size(t) >= 50_000))
|
|
418
|
+
return [];
|
|
419
|
+
const total = hits.reduce((a, t) => a + size(t), 0);
|
|
420
|
+
// Group by cause: "loaded claude-in-chrome", "/mcp", or unknown.
|
|
421
|
+
const causes = new Map();
|
|
422
|
+
for (const t of hits) {
|
|
423
|
+
const cause = t.miss === 'messages_changed' ? 'messages' : t.loaded?.length ? `loaded ${t.loaded.join(', ')}` : t.after ?? 'tools';
|
|
424
|
+
causes.set(cause, [...(causes.get(cause) ?? []), t]);
|
|
425
|
+
}
|
|
426
|
+
const sorted = [...causes].sort((x, y) => y[1].reduce((a, t) => a + size(t), 0) - x[1].reduce((a, t) => a + size(t), 0));
|
|
427
|
+
const said = (cause, ts) => {
|
|
428
|
+
const n = ts.length === 1 ? 'once' : `${ts.length} times`;
|
|
429
|
+
const sizes = `${ts.map((t) => fmt(size(t))).join(', ')} re-cached`;
|
|
430
|
+
if (cause.startsWith('loaded '))
|
|
431
|
+
return `${n} right after Tool Search loaded ${cause.slice(7)}'s tools mid-session (${sizes})`;
|
|
432
|
+
if (cause.startsWith('/'))
|
|
433
|
+
return `${n} right after you ran ${cause} (${sizes})`;
|
|
434
|
+
if (cause === 'messages')
|
|
435
|
+
return `${n} because earlier messages changed (${sizes})`;
|
|
436
|
+
return `${n} because the tool list changed, cause not logged (${sizes})`;
|
|
437
|
+
};
|
|
438
|
+
const fixes = [];
|
|
439
|
+
const servers = [...new Set(hits.flatMap((t) => t.loaded ?? []))];
|
|
440
|
+
if (servers.length)
|
|
441
|
+
fixes.push(`Load ${servers.join(', ')} at the start of a session, or do that work in its own session: loading a tool mid-session puts it at the front of the context and everything after it is written again.`);
|
|
442
|
+
if (hits.some((t) => t.after))
|
|
443
|
+
fixes.push('Change MCP servers, models, plugins or settings between sessions, not in the middle of one.');
|
|
444
|
+
if (hits.some((t) => t.miss === 'tools_changed' && !t.loaded?.length && !t.after))
|
|
445
|
+
fixes.push('Usually an MCP server connecting or disconnecting: keep flaky servers off for that project.');
|
|
446
|
+
if (hits.some((t) => t.miss === 'messages_changed'))
|
|
447
|
+
fixes.push('Earlier messages change when you rewind or edit a message: start fresh rather than editing far back.');
|
|
448
|
+
return [
|
|
449
|
+
{
|
|
450
|
+
rule: 'C2',
|
|
451
|
+
title: 'Cache thrown away mid-session',
|
|
452
|
+
say: `${hits.length} time${hits.length > 1 ? 's' : ''} in ${sessionsHit} session${sessionsHit > 1 ? 's' : ''} the whole context was written again mid-session: ${sorted.map(([c, ts]) => said(c, ts)).join('; ')}.`,
|
|
453
|
+
basis: 'measured',
|
|
454
|
+
tokens: total,
|
|
455
|
+
fix: fixes.join(' '),
|
|
456
|
+
lane: 'habit',
|
|
457
|
+
},
|
|
458
|
+
];
|
|
459
|
+
}
|
|
460
|
+
export function detect(opts = {}) {
|
|
461
|
+
const now = (opts.now ?? new Date()).getTime();
|
|
462
|
+
const s = scan({ days: opts.days ?? 30, now: new Date(now), ...(opts.root ? { root: opts.root } : {}) });
|
|
463
|
+
const skills = installedSkills(opts.claudeDir);
|
|
464
|
+
const servers = configuredMcp(s.sessions.map((x) => x.cwd).filter(Boolean), opts.home);
|
|
465
|
+
const findings = [
|
|
466
|
+
...ruleC1(s, now),
|
|
467
|
+
...ruleC2(s),
|
|
468
|
+
...ruleS3(s, skills, now),
|
|
469
|
+
...ruleS2(s, opts.claudeDir),
|
|
470
|
+
...ruleS4(s, servers),
|
|
471
|
+
...ruleS5(opts.root),
|
|
472
|
+
];
|
|
473
|
+
return { scanned: { sessions: s.sessions.length, days: opts.days ?? 30, skills: skills.length, mcpServers: servers.length }, findings };
|
|
474
|
+
}
|
|
475
|
+
const short = (text) => text.split(/(?<=\.)\s/)[0];
|
|
476
|
+
/**
|
|
477
|
+
* One screen: what it read, the findings ranked by tokens, and the one fix to start with. `all` adds each
|
|
478
|
+
* finding's evidence, what it doesn't prove, and every fix.
|
|
479
|
+
*/
|
|
480
|
+
export function detectText(r, opts = {}) {
|
|
481
|
+
const { sessions, days, skills, mcpServers } = r.scanned;
|
|
482
|
+
if (!sessions) {
|
|
483
|
+
return [
|
|
484
|
+
`No Claude Code sessions from the last ${days} days in ${opts.projects ?? '~/.claude/projects'}.`,
|
|
485
|
+
'detect reads the transcripts Claude Code keeps on this computer. Use Claude Code for a few days, then run it again.',
|
|
486
|
+
];
|
|
487
|
+
}
|
|
488
|
+
const lines = [`Read ${sessions} of your Claude Code sessions from the last ${days} days, ${skills} installed skills and ${mcpServers} MCP servers. Nothing left this computer.`];
|
|
489
|
+
if (!r.findings.length)
|
|
490
|
+
return [...lines, '', 'Nothing to fix in what this version checks (startup tax and cache).'];
|
|
491
|
+
const ranked = [...r.findings].sort((a, b) => (b.tokens ?? -1) - (a.tokens ?? -1));
|
|
492
|
+
const cost = (f) => (f.tokens === undefined ? '' : `${f.basis === 'estimated' ? '~' : ''}${fmt(f.tokens)} tokens`);
|
|
493
|
+
const w = Math.max(...ranked.map((f) => f.title.length));
|
|
494
|
+
const cw = Math.max(...ranked.map((f) => cost(f).length));
|
|
495
|
+
lines.push('');
|
|
496
|
+
for (const f of ranked)
|
|
497
|
+
lines.push(` ${f.title.padEnd(w)} ${cost(f).padStart(cw)} ${f.basis.padEnd(9)} ${f.rule}`);
|
|
498
|
+
if (sessions < 20)
|
|
499
|
+
lines.push('', `Only ${sessions} sessions: some checks wait for 20 sessions over 14 days before calling anything unused.`);
|
|
500
|
+
if (!opts.all) {
|
|
501
|
+
lines.push('', `Start here: ${short(ranked[0].fix)}`, '', 'Evidence and every fix: chompyy detect --all');
|
|
502
|
+
return lines;
|
|
503
|
+
}
|
|
504
|
+
for (const f of ranked) {
|
|
505
|
+
lines.push('', `${f.rule} · ${f.title} (${f.basis}${f.tokensHow ? `: ${f.tokensHow}` : ''})`, ` ${f.say}`);
|
|
506
|
+
if (f.notProve)
|
|
507
|
+
lines.push(` What this doesn't prove: ${f.notProve}`);
|
|
508
|
+
lines.push(` Fix (${f.lane}): ${f.fix}`);
|
|
509
|
+
}
|
|
510
|
+
return lines;
|
|
511
|
+
}
|