chompyy 0.4.1 → 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/dist/cli.js CHANGED
@@ -4,13 +4,14 @@ import { execFileSync, spawn } from 'node:child_process';
4
4
  import { backfillTokens, median } from './tokenstore.js';
5
5
  import { compact, formatTokens, totalTokens } from './tokens.js';
6
6
  import { closeSync, existsSync, openSync, readFileSync } from 'node:fs';
7
+ import { resolve } from 'node:path';
7
8
  import { parseArgs } from 'node:util';
8
9
  import { away, runCard } from './away.js';
9
10
  import { formatPreflight, loadProfile, preflight, saveProfile } from './preflight.js';
10
11
  import { verifyCard } from './verifycard.js';
11
12
  import { parsePermission, recordNeeds } from './permissions.js';
12
13
  import { draftAllPlan, draftBlueprint, draftFiveStarOptions, draftTitle, GENERIC_FIVE_STAR, isUsageLimit, writeBlueprintFile } from './blueprint.js';
13
- import { addCard, awayQueue, claimDrafts, COLUMNS, dropCard, expireSuggested, formatBoard, formatCard, getCard, loadBoard, moveCard, noteDraftFailure, quotaWaitReason, recoverRunning, titleFrom, updateBoard } from './board.js';
14
+ import { addCard, awayQueue, claimDrafts, COLUMNS, continueCard, cycleOf, dropCard, expireSuggested, formatBoard, formatCard, getCard, loadBoard, moveCard, noteDraftFailure, quotaWaitReason, recoverRunning, titleFrom, updateBoard } from './board.js';
14
15
  import { loadConfig, setConfig } from './config.js';
15
16
  import { formatDuration, parseDuration } from './duration.js';
16
17
  import { budgetGate } from './gate.js';
@@ -38,6 +39,9 @@ import { byKind, compare, formatExtras, formatUsage, loadLedger, periodDays, PER
38
39
  import { formatTrace, traceSession } from './trace.js';
39
40
  import { homedir } from 'node:os';
40
41
  import { clashOf, refreshCard, refreshGate, refreshClashing, withRefreshLock } from './refresh.js';
42
+ import { adviseText, applyDue, approveAdvice, runAdvise, undoAdvice } from './advice.js';
43
+ import { checkWorked, nudgeProof, nudgeProofText, workedText } from './didwork.js';
44
+ import { coldWarningText, hookCommand, impact, loadNudges, nudgeInstalled, nudgeText, runHook, setNudge, setProjectMode, takeGoingCold } from './nudge.js';
41
45
  import { formatLive, keepAffectsLive, liveOff, liveSet, liveUpdateLocked, loadLive, startLiveUpdate } from './live.js';
42
46
  import { agentInstalled, awayRunning, bedtimeKey, decideTrigger, installAgent, loadTriggerState, markFired, noteTick, parseClock, takeAwayLock, uninstallAgent } from './triggers.js';
43
47
  const HELP = `chompyy: use the 5-hour window capacity that would reset unused
@@ -48,6 +52,16 @@ Quota
48
52
  chompyy quota [--refresh] read live quota from Anthropic now (uses Claude Code's saved login; sends no message)
49
53
  chompyy quota --allow-keychain | --no-keychain allow (or stop) reading that login from the macOS Keychain
50
54
  chompyy detect [--days 30] [--all] [--json] what wastes tokens in your setup and habits, ranked, on one screen (--all: evidence and every fix)
55
+ chompyy advise [--json] turn detect's findings into suggested cards to approve or drop: settings changes are
56
+ applied (backed up, undoable) once no Claude Code session is active; habits are tracked
57
+ chompyy advise apply apply approved settings advice now, if no session has been active for 10 minutes
58
+ chompyy worked [--json] did it work? measure each approved advice card against the check on its card
59
+ chompyy nudge on|off live suggestions while you work: stops the first message to a big conversation
60
+ whose cache expired, with the price and the cheaper ways (Claude Code hook)
61
+ chompyy nudge strict|quiet|learn [dir] in this project: always stop me, only a heads-up, or learn (default:
62
+ after 3 stops in a row you sent anyway, a heads-up instead)
63
+ chompyy nudge on or off, and what the stops saved
64
+ chompyy nudge due [--json] conversations 45-60 min into a pause, about to go cold (each reported once; the app notifies; only while nudge is on)
51
65
  chompyy premise [--json] how often a 5-hour window reset with capacity left while the week still had room
52
66
  chompyy eat-tokens show leftover quota and cards you could choose to run (read-only)
53
67
 
@@ -77,6 +91,8 @@ Back
77
91
  chompyy undo <id> throw it away (removes its branch; yours are untouched)
78
92
  chompyy answer <id> answer the run's questions (stdin); the card goes back to approved
79
93
  chompyy redo <id> throw this attempt away and run it again from your latest code
94
+ chompyy continue <id> ["note"] a done card did only part of the job: run another cycle that builds on it
95
+ (the next run is told what was done and, from the note, what is still missing)
80
96
  chompyy rate <id> <1-5> ["why"] [--to-five "change" ...] rate a result; --to-five = what would have made it a 5
81
97
  chompyy five-star <id> options for "what would have made it a 5?" (JSON)
82
98
  chompyy signals [--json] everything Chompyy has recorded from you: ratings, edits, answers
@@ -240,7 +256,7 @@ function draftPending(now) {
240
256
  return;
241
257
  const toDraw = updateBoard((b) => {
242
258
  const due = b.cards.filter((c) => ['suggested', 'later', 'approved'].includes(c.column) &&
243
- c.blueprint && !c.draftingAt && !c.pictureError &&
259
+ c.blueprint && !c.draftingAt && !c.pictureError && (!c.advice || c.advice.lane === 'work') &&
244
260
  (!c.picture || c.picture.blueprintHash !== blueprintHash(c.blueprint)) &&
245
261
  (!c.drawingAt || Date.parse(c.drawingAt) < now.getTime() - 6 * 60_000));
246
262
  for (const c of due)
@@ -298,9 +314,12 @@ async function distillNow(now, force = false) {
298
314
  /** Keep a card: merge it, record it, update the live app, and bring the other cards in review up to date. */
299
315
  function keepNow(id, now) {
300
316
  const kept = getCard(loadBoard(), id);
317
+ const files = changedFiles(kept); // read before Keep removes the branch
301
318
  console.log(keepCard(kept));
302
319
  updateBoard((b) => {
303
320
  const card = getCard(b, id);
321
+ if (card.run)
322
+ card.run.files = files;
304
323
  card.outcome = 'kept';
305
324
  card.column = 'done';
306
325
  delete card.keepWhenRefreshed;
@@ -476,7 +495,7 @@ async function main(argv) {
476
495
  const now = new Date();
477
496
  const json = (data) => console.log(JSON.stringify(data, null, 2));
478
497
  // detect and premise only read: run once through npx, they must not point the app at npx's temporary copy.
479
- if (command !== 'statusline' && command !== 'detect' && command !== 'premise')
498
+ if (command !== 'statusline' && command !== 'detect' && command !== 'premise' && command !== 'hook')
480
499
  recordCliLocation();
481
500
  /** Fresh quota before anything that reads it (at most every 5 minutes unless forced). */
482
501
  const freshQuota = async (force = false) => {
@@ -891,6 +910,16 @@ async function main(argv) {
891
910
  const bad = allow.filter((a) => !parsePermission(a));
892
911
  if (bad.length)
893
912
  throw new Error(`Not a permission: ${bad.join(', ')}. Use network:<domain> or "command:<program> *".`);
913
+ // Advice cards (chompyy advise): what approving does depends on the lane, not an away run.
914
+ const adv = getCard(loadBoard(), id);
915
+ if (adv.advice && adv.advice.lane !== 'work') {
916
+ if (adv.column !== 'suggested' && adv.column !== 'later')
917
+ throw new Error(`Card #${adv.id} is in ${adv.column}; only a suggested card can be approved.`);
918
+ console.log(updateBoard((b) => approveAdvice(getCard(b, id), now)));
919
+ for (const line of updateBoard((b) => applyDue(b, now)))
920
+ console.log(` ${line}`);
921
+ return;
922
+ }
894
923
  const card = updateBoard((b) => {
895
924
  const c = moveCard(b, id, 'approved', now);
896
925
  if (allow.length)
@@ -946,6 +975,18 @@ async function main(argv) {
946
975
  // Run by the LaunchAgent every 5 minutes. Prints one line per tick to tick.log.
947
976
  await freshQuota();
948
977
  const config = loadConfig();
978
+ // Approved settings advice goes in once no Claude Code session is active.
979
+ try {
980
+ updateBoard((b) => applyDue(b, now));
981
+ }
982
+ catch { }
983
+ // Did it work? Re-measure applied advice once an hour (a transcript scan, so not every tick).
984
+ if (now.getMinutes() < 5) {
985
+ try {
986
+ updateBoard((b) => checkWorked(b, now));
987
+ }
988
+ catch { }
989
+ }
949
990
  const board = loadBoard();
950
991
  // Refreshes that waited for quota (refresh.ts) go as soon as there is some again.
951
992
  if (board.cards.some((c) => c.column === 'review' && c.refresh?.state === 'waiting') && !refreshGate(loadSnapshot(), now)) {
@@ -1103,6 +1144,62 @@ async function main(argv) {
1103
1144
  console.log(detectText(r, { all: Boolean(values.all), projects: projectsDir().replace(homedir(), '~') }).join('\n'));
1104
1145
  return;
1105
1146
  }
1147
+ case 'advise': {
1148
+ // The detective, step 3: findings become suggested cards. `advise apply`: apply approved settings advice
1149
+ // once no Claude Code session is active (the app asks every minute).
1150
+ if (args[0] === 'apply') {
1151
+ const lines = updateBoard((b) => applyDue(b, now));
1152
+ if (values.json)
1153
+ return json(lines);
1154
+ return console.log(lines.length ? lines.join('\n') : 'Nothing waiting to be applied.');
1155
+ }
1156
+ const res = updateBoard((b) => runAdvise(b, now));
1157
+ if (values.json)
1158
+ return json({ added: res.added.map((c) => c.id), updated: res.updated.map((c) => c.id), skipped: res.skipped });
1159
+ return console.log(adviseText(res));
1160
+ }
1161
+ case 'worked': {
1162
+ // The detective, step 5: each applied/tried advice card against the check it registered (didwork.ts).
1163
+ const cards = updateBoard((b) => checkWorked(b, now));
1164
+ const proof = nudgeInstalled() || loadNudges().length ? nudgeProof(now) : null;
1165
+ if (values.json)
1166
+ return json({ cards: cards.map((c) => ({ id: c.id, title: c.title, rule: c.advice.rule, lane: c.advice.lane, ...c.advice.result })), nudge: proof });
1167
+ if (!cards.length && proof)
1168
+ return console.log(nudgeProofText(proof).join('\n'));
1169
+ return console.log([workedText(cards), ...(proof ? ['', ...nudgeProofText(proof)] : [])].join('\n'));
1170
+ }
1171
+ case 'hook': {
1172
+ // Claude Code's UserPromptSubmit hook. Must never fail loudly or stop a prompt by accident.
1173
+ if (args[0] !== 'prompt')
1174
+ return;
1175
+ try {
1176
+ const out = runHook(await readStdin());
1177
+ if (out)
1178
+ console.log(out);
1179
+ }
1180
+ catch {
1181
+ /* let the prompt through */
1182
+ }
1183
+ return;
1184
+ }
1185
+ case 'nudge': {
1186
+ const sub = args[0];
1187
+ if (sub === 'on' || sub === 'off')
1188
+ return console.log(setNudge(sub === 'on', sub === 'on' ? hookCommand() : undefined));
1189
+ // Per project: always stop me here, never stop me (a heads-up only), or learn from what I do (the default).
1190
+ if (sub === 'strict' || sub === 'quiet' || sub === 'learn')
1191
+ return console.log(setProjectMode(sub, resolve(args[1] ?? process.cwd())));
1192
+ if (sub === 'due') {
1193
+ // The app asks every minute; each conversation going cold is reported once.
1194
+ const due = (nudgeInstalled() ? takeGoingCold(now.getTime()) : []).map((d) => ({ ...d, ...coldWarningText(d) }));
1195
+ if (values.json)
1196
+ return json(due);
1197
+ return console.log(due.length ? due.map((d) => `${d.title}\n ${d.body}`).join('\n') : 'Nothing about to go cold.');
1198
+ }
1199
+ if (values.json)
1200
+ return json(impact());
1201
+ return console.log([nudgeText(nudgeInstalled()), impact().line].join('\n'));
1202
+ }
1106
1203
  case 'premise': {
1107
1204
  const ends = allWindowEnds(loadSamples(), now.getTime());
1108
1205
  archiveWindowEnds(loadSamples(), now.getTime());
@@ -1166,9 +1263,15 @@ async function main(argv) {
1166
1263
  }
1167
1264
  case 'undo': {
1168
1265
  const id = need(args[0], 'chompyy undo <id>');
1169
- console.log(undoCard(getCard(loadBoard(), id)));
1266
+ const undone = getCard(loadBoard(), id);
1267
+ if (undone.advice && undone.advice.lane !== 'work')
1268
+ return console.log(updateBoard((b) => undoAdvice(getCard(b, id), now)));
1269
+ const files = changedFiles(undone); // read before Undo removes the branch
1270
+ console.log(undoCard(undone));
1170
1271
  updateBoard((b) => {
1171
1272
  const card = getCard(b, id);
1273
+ if (card.run)
1274
+ card.run.files = files;
1172
1275
  card.outcome = 'undone';
1173
1276
  card.column = 'done';
1174
1277
  card.updatedAt = now.toISOString();
@@ -1196,6 +1299,15 @@ async function main(argv) {
1196
1299
  console.log(`🔁 #${card.id} back in approved; it runs again from your latest code on the next away run.`);
1197
1300
  return;
1198
1301
  }
1302
+ case 'continue': {
1303
+ const id = need(args[0], 'chompyy continue <id> ["what is still missing"]');
1304
+ const note = args.slice(1).join(' ').trim();
1305
+ const before = getCard(loadBoard(), id);
1306
+ const prior = { summary: fullOutput(before) ?? before.run?.summary, files: before.run?.files ?? changedFiles(before) };
1307
+ const card = updateBoard((b) => continueCard(b, id, note, now, prior));
1308
+ console.log(`🔁 #${card.id} back in approved as cycle ${cycleOf(card)}; the next away run gets what cycle ${cycleOf(card) - 1} did${note ? ' and your note' : ''}.`);
1309
+ return;
1310
+ }
1199
1311
  case 'rate': {
1200
1312
  const usage = 'chompyy rate <id> <1-5> ["optional reason"]';
1201
1313
  const id = need(args[0], usage);
package/dist/detect.js CHANGED
@@ -167,7 +167,7 @@ function skillAt(file, source, plugin) {
167
167
  const front = text.match(/^---\n([\s\S]*?)\n---/)?.[1] ?? '';
168
168
  const name = front.match(/^name:\s*(.+)$/m)?.[1]?.trim().replace(/^["']|["']$/g, '') || basename(dirname(file));
169
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 };
170
+ return { name, calledAs: plugin ? `${plugin}:${name}` : name, descriptionTokens: tokensOf(`${name}: ${description}`), source, installedAt: statSync(file).mtimeMs, file };
171
171
  }
172
172
  const skillFiles = (dir, depth = 3) => {
173
173
  if (!existsSync(dir))
@@ -223,7 +223,7 @@ export function installedSkills(claudeDir = join(homedir(), '.claude')) {
223
223
  for (const f of pluginSkillFiles(inst.installPath)) {
224
224
  const s = skillAt(f, 'plugin', plugin);
225
225
  if (s)
226
- skills.push(s);
226
+ skills.push({ ...s, plugin: id });
227
227
  }
228
228
  }
229
229
  }
@@ -278,12 +278,12 @@ export function ruleS2(s, claudeDir = join(homedir(), '.claude')) {
278
278
  out.push({
279
279
  rule: 'S2',
280
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.`,
281
+ say: `${home(f)} is ${lines} lines (~${fmt(tokens)} tokens), loaded in ${sessions} sessions.`,
282
282
  basis: 'estimated',
283
283
  tokens: tokens * sessions,
284
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.',
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
287
  lane: 'work',
288
288
  });
289
289
  }
@@ -306,17 +306,36 @@ export function ruleS3(s, skills, now) {
306
306
  return [
307
307
  {
308
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(', ')}.`,
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
311
  basis: 'estimated',
312
312
  tokens: tokens * s.sessions.length,
313
313
  tokensHow: `~${fmt(tokens)} × ${s.sessions.length} sessions`,
314
- notProve: "Not seeing a skill used doesn't prove you'll never need it.",
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
+ },
315
334
  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('; ') + '.',
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()) + '.',
320
339
  lane: 'settings',
321
340
  },
322
341
  ];
@@ -331,11 +350,11 @@ export function ruleS4(s, servers) {
331
350
  return [
332
351
  {
333
352
  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(', ')}.`,
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(', ')}.`,
336
355
  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.',
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.',
339
358
  lane: 'settings',
340
359
  },
341
360
  ];
@@ -359,14 +378,30 @@ export function ruleS5(root = projectsDir()) {
359
378
  out.push({
360
379
  rule: 'S5',
361
380
  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.`,
381
+ say: `${home(f)} is ${lines} lines (${Math.round(bytes / 1000)} KB); only the first 200 lines or 25 KB load.`,
363
382
  basis: 'measured',
364
- fix: 'Compress the index to one line per memory, and move duplicates out.',
383
+ fix: 'Compress it to one line per memory; move duplicates out.',
365
384
  lane: 'work',
366
385
  });
367
386
  }
368
387
  return out;
369
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
+ }
370
405
  /** C1: coming back after the cache expired, so the whole context is written again. */
371
406
  export function ruleC1(s, now) {
372
407
  const since = now - 14 * DAY;
@@ -394,11 +429,12 @@ export function ruleC1(s, now) {
394
429
  {
395
430
  rule: 'C1',
396
431
  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.`,
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.`,
398
433
  basis: 'measured',
399
- notProve: "Some of these returns were worth it: a long session with context you'd otherwise have to rebuild.",
434
+ notProve: "Some were worth it: context you'd otherwise rebuild.",
400
435
  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).',
436
+ // Never automated keep-warm pings (rulebook T2).
437
+ fix: 'Before a long break: /compact, or leave a note and start fresh.',
402
438
  lane: 'habit',
403
439
  },
404
440
  ];
@@ -425,31 +461,31 @@ export function ruleC2(s) {
425
461
  }
426
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));
427
463
  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`;
464
+ const n = ts.length === 1 ? 'once' : `${ts.length}×`;
465
+ const sizes = ts.map((t) => fmt(size(t))).join(', ');
430
466
  if (cause.startsWith('loaded '))
431
- return `${n} right after Tool Search loaded ${cause.slice(7)}'s tools mid-session (${sizes})`;
467
+ return `${n} after ${cause.slice(7)}'s tools loaded mid-session (${sizes})`;
432
468
  if (cause.startsWith('/'))
433
- return `${n} right after you ran ${cause} (${sizes})`;
469
+ return `${n} after ${cause} (${sizes})`;
434
470
  if (cause === 'messages')
435
- return `${n} because earlier messages changed (${sizes})`;
436
- return `${n} because the tool list changed, cause not logged (${sizes})`;
471
+ return `${n} after earlier messages changed (${sizes})`;
472
+ return `${n} after the tool list changed, cause not logged (${sizes})`;
437
473
  };
438
474
  const fixes = [];
439
475
  const servers = [...new Set(hits.flatMap((t) => t.loaded ?? []))];
440
476
  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.`);
477
+ fixes.push(`Load ${servers.join(', ')} at the start of a session, or give that work its own session.`);
442
478
  if (hits.some((t) => t.after))
443
- fixes.push('Change MCP servers, models, plugins or settings between sessions, not in the middle of one.');
479
+ fixes.push('Change MCP servers, models or plugins between sessions.');
444
480
  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.');
481
+ fixes.push('Likely an MCP server reconnecting: turn flaky ones off for that project.');
446
482
  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.');
483
+ fixes.push('Rewinding or editing old messages rewrites the cache: start fresh instead.');
448
484
  return [
449
485
  {
450
486
  rule: 'C2',
451
487
  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('; ')}.`,
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('; ')}.`,
453
489
  basis: 'measured',
454
490
  tokens: total,
455
491
  fix: fixes.join(' '),
@@ -470,7 +506,25 @@ export function detect(opts = {}) {
470
506
  ...ruleS4(s, servers),
471
507
  ...ruleS5(opts.root),
472
508
  ];
473
- return { scanned: { sessions: s.sessions.length, days: opts.days ?? 30, skills: skills.length, mcpServers: servers.length }, findings };
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
+ };
474
528
  }
475
529
  const short = (text) => text.split(/(?<=\.)\s/)[0];
476
530
  /**
@@ -485,27 +539,30 @@ export function detectText(r, opts = {}) {
485
539
  'detect reads the transcripts Claude Code keeps on this computer. Use Claude Code for a few days, then run it again.',
486
540
  ];
487
541
  }
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.`];
542
+ const read = `Read ${sessions} sessions (last ${days} days), ${skills} skills, ${mcpServers} MCP servers. Nothing left this computer.`;
489
543
  if (!r.findings.length)
490
- return [...lines, '', 'Nothing to fix in what this version checks (startup tax and cache).'];
544
+ return ['Nothing to fix in what this version checks (startup tax and cache).', '', read];
491
545
  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));
546
+ const cost = (f) => (f.tokens === undefined ? '' : `${f.basis === 'estimated' ? '~' : ''}${fmt(f.tokens)}`);
494
547
  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}`);
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);
498
555
  if (sessions < 20)
499
- lines.push('', `Only ${sessions} sessions: some checks wait for 20 sessions over 14 days before calling anything unused.`);
556
+ lines.push(`Only ${sessions} sessions: some checks need 20 over 14 days.`);
500
557
  if (!opts.all) {
501
- lines.push('', `Start here: ${short(ranked[0].fix)}`, '', 'Evidence and every fix: chompyy detect --all');
558
+ lines.push('Evidence and every fix: chompyy detect --all');
502
559
  return lines;
503
560
  }
504
561
  for (const f of ranked) {
505
- lines.push('', `${f.rule} · ${f.title} (${f.basis}${f.tokensHow ? `: ${f.tokensHow}` : ''})`, ` ${f.say}`);
562
+ lines.push('', `${cost(f) ? `${cost(f)} · ` : ''}${f.title} (${f.basis}${f.tokensHow ? `: ${f.tokensHow}` : ''})`, ` ${f.say}`);
506
563
  if (f.notProve)
507
- lines.push(` What this doesn't prove: ${f.notProve}`);
508
- lines.push(` Fix (${f.lane}): ${f.fix}`);
564
+ lines.push(` Not proven: ${f.notProve}`);
565
+ lines.push(` Fix: ${f.fix}`);
509
566
  }
510
567
  return lines;
511
568
  }