chompyy 0.6.0 → 0.7.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/dist/detect.js CHANGED
@@ -8,6 +8,7 @@ import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs';
8
8
  import { homedir } from 'node:os';
9
9
  import { basename, dirname, join } from 'node:path';
10
10
  import { projectsDir } from './dream.js';
11
+ import { errorKind, ruleStuck } from './stuck.js';
11
12
  /**
12
13
  * Folders under ~/.claude/projects made by automated runs in temp folders (benchmarks, sandboxes, Chompyy's own
13
14
  * cards): not your sessions, so they don't count for or against you.
@@ -21,11 +22,15 @@ export function readSession(file) {
21
22
  const skills = new Map();
22
23
  const commands = new Map();
23
24
  const mcp = new Map();
25
+ const errors = new Map();
26
+ let failed = 0;
27
+ let interrupts = 0;
24
28
  // What changed since the last request: read back when the next request says the tool list changed.
25
29
  let loaded = [];
26
30
  let after = '';
27
31
  for (const line of readFileSync(file, 'utf8').split('\n')) {
28
- if (!line.includes('"assistant"') && !line.includes('<command-name>') && !line.includes('deferred_tools_record'))
32
+ const stuckLine = line.includes('"is_error":true') || line.includes('[Request interrupted');
33
+ if (!stuckLine && !line.includes('"assistant"') && !line.includes('<command-name>') && !line.includes('deferred_tools_record'))
29
34
  continue;
30
35
  let e;
31
36
  try {
@@ -54,6 +59,21 @@ export function readSession(file) {
54
59
  after = `/${m[1]}`;
55
60
  }
56
61
  }
62
+ if (stuckLine && e.type === 'user' && !e.isSidechain) {
63
+ const blocks = typeof content === 'string' ? [{ type: 'text', text: content }] : Array.isArray(content) ? content : [];
64
+ for (const b of blocks) {
65
+ if (b?.type === 'text' && typeof b.text === 'string' && b.text.startsWith('[Request interrupted'))
66
+ interrupts += 1;
67
+ if (b?.type !== 'tool_result' || b.is_error !== true)
68
+ continue;
69
+ failed += 1;
70
+ const text = typeof b.content === 'string' ? b.content : Array.isArray(b.content) ? b.content.map((x) => (typeof x?.text === 'string' ? x.text : '')).join(' ') : '';
71
+ const kind = errorKind(text.slice(0, 2000));
72
+ if (kind)
73
+ errors.set(kind, (errors.get(kind) ?? 0) + 1);
74
+ }
75
+ continue;
76
+ }
57
77
  if (e.type !== 'assistant' || !msg?.usage || e.isSidechain)
58
78
  continue;
59
79
  if (Array.isArray(content)) {
@@ -102,14 +122,15 @@ export function readSession(file) {
102
122
  cwd,
103
123
  turns: [...turns.values()].filter((t) => t.at).sort((a, b) => a.at - b.at),
104
124
  };
105
- return Object.assign(session, { skills, commands, mcp });
125
+ return Object.assign(session, { skills, commands, mcp, errors, failed, interrupts });
106
126
  }
127
+ const sessionMemo = new Map();
107
128
  /** Your sessions from the last `days` days (by file time), automated runs left out. */
108
129
  export function scan(opts = {}) {
109
130
  const now = (opts.now ?? new Date()).getTime();
110
131
  const since = now - (opts.days ?? 30) * 86_400_000;
111
132
  const root = opts.root ?? projectsDir();
112
- const out = { sessions: [], skills: new Map(), commands: new Map(), mcp: new Map(), firstAt: Infinity, lastAt: 0 };
133
+ const out = { sessions: [], skills: new Map(), commands: new Map(), mcp: new Map(), firstAt: Infinity, lastAt: 0, errors: new Map(), failed: 0, interrupts: 0 };
113
134
  if (!existsSync(root))
114
135
  return { ...out, firstAt: 0 };
115
136
  for (const folder of readdirSync(root)) {
@@ -125,14 +146,22 @@ export function scan(opts = {}) {
125
146
  }
126
147
  for (const n of names) {
127
148
  const file = join(dir, n);
149
+ let st;
128
150
  try {
129
- if (statSync(file).mtimeMs < since)
151
+ st = statSync(file);
152
+ if (st.mtimeMs < since)
130
153
  continue;
131
154
  }
132
155
  catch {
133
156
  continue;
134
157
  }
135
- const s = readSession(file);
158
+ // Parsed once per file version: savings, detect and the saved total each scan, in one process.
159
+ const key = `${st.size}:${st.mtimeMs}`;
160
+ let s = sessionMemo.get(file)?.key === key ? sessionMemo.get(file).s : undefined;
161
+ if (s === undefined) {
162
+ s = readSession(file);
163
+ sessionMemo.set(file, { key, s });
164
+ }
136
165
  if (!s || !s.turns.length)
137
166
  continue;
138
167
  out.sessions.push({ id: s.id, cwd: s.cwd, turns: s.turns });
@@ -142,6 +171,10 @@ export function scan(opts = {}) {
142
171
  out.skills.set(k, (out.skills.get(k) ?? 0) + v);
143
172
  for (const [k, v] of s.commands)
144
173
  out.commands.set(k, (out.commands.get(k) ?? 0) + v);
174
+ for (const [k, v] of s.errors)
175
+ out.errors.set(k, (out.errors.get(k) ?? 0) + v);
176
+ out.failed += s.failed;
177
+ out.interrupts += s.interrupts;
145
178
  for (const [k, v] of s.mcp) {
146
179
  const m = out.mcp.get(k) ?? { calls: 0, projects: new Set() };
147
180
  m.calls += v;
@@ -505,6 +538,7 @@ export function detect(opts = {}) {
505
538
  ...ruleS2(s, opts.claudeDir),
506
539
  ...ruleS4(s, servers),
507
540
  ...ruleS5(opts.root),
541
+ ...ruleStuck(s),
508
542
  ];
509
543
  // Baselines for the checks advice cards register before a fix: what a session start costs, and last week's cold returns.
510
544
  const starts = s.sessions.map((x) => x.turns[0]).map((t) => t.cacheRead + t.cacheWrite).filter((n) => n > 0);
@@ -526,6 +560,17 @@ export function detect(opts = {}) {
526
560
  findings,
527
561
  };
528
562
  }
563
+ /** `detect` plus codeburn's waste checks (wastechecks.ts), one list. Slower (a few seconds): the CLI and advise use it. */
564
+ export async function detectFull(opts = {}) {
565
+ const r = detect(opts);
566
+ if (opts.codeburn === false)
567
+ return r;
568
+ const { otherAgentChecks, wasteChecks } = await import('./wastechecks.js');
569
+ const window = { days: opts.days ?? 30, ...(opts.now ? { now: opts.now } : {}) };
570
+ const theirs = await wasteChecks(window);
571
+ const others = opts.agents === false ? [] : await otherAgentChecks(window);
572
+ return { ...r, findings: [...r.findings, ...theirs, ...others] };
573
+ }
529
574
  const short = (text) => text.split(/(?<=\.)\s/)[0];
530
575
  /**
531
576
  * One screen: what it read, the findings ranked by tokens, and the one fix to start with. `all` adds each
@@ -541,16 +586,28 @@ export function detectText(r, opts = {}) {
541
586
  }
542
587
  const read = `Read ${sessions} sessions (last ${days} days), ${skills} skills, ${mcpServers} MCP servers. Nothing left this computer.`;
543
588
  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));
589
+ return ['Nothing to fix in what this version checks.', '', read];
590
+ const byTokens = (a, b) => (b.tokens ?? -1) - (a.tokens ?? -1);
591
+ const ranked = r.findings.filter((f) => !f.worthKnowing).sort(byTokens);
592
+ const known = r.findings.filter((f) => f.worthKnowing).sort(byTokens);
593
+ if (!ranked.length)
594
+ ranked.push(...known.splice(0));
546
595
  const cost = (f) => (f.tokens === undefined ? '' : `${f.basis === 'estimated' ? '~' : ''}${fmt(f.tokens)}`);
547
596
  const cw = Math.max(...ranked.map((f) => cost(f).length));
548
597
  const w = Math.max(...ranked.map((f) => f.title.length));
549
- const lines = [`Start here: ${short(ranked[0].fix)}`, ''];
598
+ // Start with a concrete step: ours, or a codeburn fix it can write itself. Its habit nudges still rank below.
599
+ const start = ranked.find((f) => f.source !== 'codeburn' || f.lane === 'settings') ?? ranked[0];
600
+ const lines = [`Start here: ${short(start.fix)}`, ''];
550
601
  for (const f of ranked.slice(0, opts.all ? undefined : 5))
551
602
  lines.push(` ${cost(f).padStart(cw)} ${f.title.padEnd(w)} ${f.basis}`);
552
603
  if (!opts.all && ranked.length > 5)
553
604
  lines.push(` …and ${ranked.length - 5} more: chompyy detect --all`);
605
+ if (known.length) {
606
+ const kw = Math.max(...known.map((f) => cost(f).length));
607
+ lines.push('', 'Worth knowing (may be needed, not a fix):');
608
+ for (const f of known.slice(0, opts.all ? undefined : 3))
609
+ lines.push(` ${cost(f).padStart(kw)} ${f.title}`);
610
+ }
554
611
  lines.push('', read);
555
612
  if (sessions < 20)
556
613
  lines.push(`Only ${sessions} sessions: some checks need 20 over 14 days.`);
@@ -558,7 +615,7 @@ export function detectText(r, opts = {}) {
558
615
  lines.push('Evidence and every fix: chompyy detect --all');
559
616
  return lines;
560
617
  }
561
- for (const f of ranked) {
618
+ for (const f of [...ranked, ...known]) {
562
619
  lines.push('', `${cost(f) ? `${cost(f)} · ` : ''}${f.title} (${f.basis}${f.tokensHow ? `: ${f.tokensHow}` : ''})`, ` ${f.say}`);
563
620
  if (f.notProve)
564
621
  lines.push(` Not proven: ${f.notProve}`);
package/dist/didwork.js CHANGED
@@ -252,6 +252,30 @@ export function checkRuleAgain(a, now, s, root) {
252
252
  const still = ruleS4(s, configuredMcp(s.sessions.map((x) => x.cwd).filter(Boolean)));
253
253
  return { at, verdict: still.length ? 'no-change' : 'worked', method: 'recount', line: still.length ? `Re-checked: ${still[0].say}` : 'Re-checked: no configured MCP server goes unused any more: it worked.' };
254
254
  }
255
+ /** Cards for codeburn's checks and our newer rules (advice.ts newCheckAdvice): keyed `cb:<id>` or `<rule>:<what>`. */
256
+ export const isNewCheck = (a) => a.key.startsWith('cb:') || /^L1:/.test(a.key);
257
+ /** Days of data since the card started that a new-check card is measured over (at least a week). */
258
+ export const newCheckDays = (since, now) => Math.floor((now - since) / DAY);
259
+ /**
260
+ * A new-check card: the same check run again over only the days since you started, per week, against the per-week
261
+ * number registered on the card. Worked at ≥ 70% of the promise (down to a third). It can't isolate the fix from
262
+ * the rest of those days, so it's a before → after reading.
263
+ */
264
+ export function checkNewCheck(a, since, now, findings) {
265
+ const at = new Date(now).toISOString();
266
+ const days = newCheckDays(since, now);
267
+ const before = a.baseline?.tokens ?? 0;
268
+ if (days < 7 || !findings) {
269
+ return { at, verdict: 'too-early', method: 'before-after', line: `Checked again a week after you started (${new Date(since + 7 * DAY).toLocaleDateString('en-US', { month: 'short', day: 'numeric' })}).`, dueAt: new Date(since + 7 * DAY).toISOString() };
270
+ }
271
+ const found = findings.find((f) => (f.key ?? (f.source === 'codeburn' ? `cb:${f.codeburnId}` : f.rule)) === a.key);
272
+ const after = found?.tokens ? Math.round((found.tokens / days) * 7) : 0;
273
+ const saved = before - after;
274
+ const promise = before - Math.floor(before / 3);
275
+ const verdict = saved >= 0.7 * promise ? 'worked' : Math.abs(saved) < 0.05 * before ? 'no-change' : saved > 0 ? 'short' : 'worse';
276
+ const say = { worked: 'it worked', short: 'better, not there yet', 'no-change': 'no change yet', worse: 'it got worse', 'too-early': '', 'cant-tell': '' };
277
+ return { at, verdict, method: 'before-after', before, after, saved, per: 'week', line: `Re-checked over ${days} days: ~${k(after)} tokens a week (was ~${k(before)}): ${say[verdict]}.` };
278
+ }
255
279
  // ---------- all cards ----------
256
280
  /** The cards with something to measure: applied, being tried, or done (by you, or kept from an away run). */
257
281
  export function measurable(c) {
@@ -293,6 +317,8 @@ export function checkWorked(board, now, opts = {}) {
293
317
  a.result = checkSkillsGone(a, t, opts.claudeDir, c.blueprint);
294
318
  else if (a.rule === 'S2')
295
319
  a.result = checkClaudeMd(a, t);
320
+ else if (isNewCheck(a))
321
+ a.result = checkNewCheck(a, since, t, opts.recheck?.get(newCheckDays(since, t)));
296
322
  else if (a.rule === 'S4' || a.rule === 'S5')
297
323
  a.result = checkRuleAgain(a, t, s ?? scan({ now, root }), root);
298
324
  }
package/dist/macapp.js CHANGED
@@ -32,11 +32,42 @@ const defaultDeps = () => ({
32
32
  platform: process.platform,
33
33
  appsDir: join(homedir(), 'Applications'),
34
34
  });
35
- /** Install (or update) Chompyy.app. Returns where it went. */
35
+ /** The version in an installed Chompyy.app's Info.plist, or null when there's no app or no readable version. */
36
+ export function installedVersion(appsDir) {
37
+ try {
38
+ const plist = readFileSync(join(appsDir, 'Chompyy.app', 'Contents', 'Info.plist'), 'utf8');
39
+ return plist.match(/<key>CFBundleShortVersionString<\/key>\s*<string>([^<]+)<\/string>/)?.[1]?.trim() ?? null;
40
+ }
41
+ catch {
42
+ return null;
43
+ }
44
+ }
45
+ /** True when version `a` is newer than `b` (plain x.y.z; a missing part counts as 0). */
46
+ export function isNewer(a, b) {
47
+ const pa = a.split('.').map((n) => parseInt(n, 10) || 0);
48
+ const pb = b.split('.').map((n) => parseInt(n, 10) || 0);
49
+ for (let i = 0; i < Math.max(pa.length, pb.length); i++) {
50
+ const d = (pa[i] ?? 0) - (pb[i] ?? 0);
51
+ if (d)
52
+ return d > 0;
53
+ }
54
+ return false;
55
+ }
56
+ /**
57
+ * Install (or update) Chompyy.app. Returns where it is, and `kept` when a newer app was already there:
58
+ * an old `chompyy` command once replaced a 0.7.0 app with 0.5.0, so a newer app is opened as it is, never downgraded.
59
+ */
36
60
  export async function installApp(opts = {}, deps = defaultDeps()) {
37
61
  if (deps.platform !== 'darwin')
38
62
  throw new Error('The Chompyy app is macOS only for now. The CLI works everywhere: `chompyy help`.');
39
63
  const version = opts.version ?? cliVersion();
64
+ const have = installedVersion(deps.appsDir);
65
+ if (have && isNewer(have, version)) {
66
+ const at = join(deps.appsDir, 'Chompyy.app');
67
+ if (opts.open !== false)
68
+ deps.exec('open', [at]);
69
+ return { at, kept: have };
70
+ }
40
71
  const url = appZipUrl(version);
41
72
  const res = await deps.fetch(url);
42
73
  if (!res.ok)
@@ -73,7 +104,7 @@ export async function installApp(opts = {}, deps = defaultDeps()) {
73
104
  renameSync(unpacked, target);
74
105
  if (opts.open !== false)
75
106
  deps.exec('open', [target]);
76
- return target;
107
+ return { at: target };
77
108
  }
78
109
  finally {
79
110
  rmSync(tmp, { recursive: true, force: true });
package/dist/nightcap.js CHANGED
@@ -27,9 +27,19 @@ export function nextBedtime(now, bedtime, windowMin) {
27
27
  }
28
28
  return { inMin, key: `bedtime:${dayKey(day)}` };
29
29
  }
30
- /** A bedtime to offer: 23:30, or the next half hour at least 30 minutes away when it's already late. */
31
- export function offeredBedtime(now) {
30
+ /** A quiet hour (Usage → Week × hour) counts as a bedtime only at night: 21:00 to 04:00. */
31
+ export const nightHour = (h) => h >= 21 || h <= 4;
32
+ /**
33
+ * A bedtime to offer: the start of your quiet stretch when it's at night and at least 30 minutes away, else 23:30,
34
+ * or the next half hour at least 30 minutes away when it's already late.
35
+ */
36
+ export function offeredBedtime(now, quietFrom = null) {
32
37
  const minutes = now.getHours() * 60 + now.getMinutes();
38
+ if (quietFrom !== null && nightHour(quietFrom)) {
39
+ const ahead = (quietFrom * 60 - minutes + 24 * 60) % (24 * 60);
40
+ if (ahead >= 30 && ahead <= 8 * 60)
41
+ return `${pad(quietFrom)}:00`;
42
+ }
33
43
  const late = minutes >= 23 * 60 || minutes < OFFER_UNTIL;
34
44
  if (!late)
35
45
  return DEFAULT_BEDTIME;
@@ -56,5 +66,7 @@ export function nightcap(i) {
56
66
  const key = `nightcap-offer:${dayKey(evening)}`;
57
67
  if (i.fired.includes(key))
58
68
  return null; // "Not tonight"
59
- return { phase: 'offer', bedtime: offeredBedtime(i.now), cards: i.approved, key };
69
+ const quiet = i.quietFrom?.() ?? null;
70
+ const bedtime = offeredBedtime(i.now, quiet);
71
+ return { phase: 'offer', bedtime, cards: i.approved, key, ...(quiet !== null && bedtime === `${pad(quiet)}:00` ? { quiet: true } : {}) };
60
72
  }
package/dist/nudge.js CHANGED
@@ -324,6 +324,27 @@ export function coldWarningText(d) {
324
324
  body: `After ${at} its cache expires and coming back rewrites all ${k(d.context)}. Done with it? Do nothing.`,
325
325
  };
326
326
  }
327
+ /**
328
+ * A transcript's compactions and replies, in file order, parsed once per file version (path, size, mtime). Many stops
329
+ * point at the same big transcript; reading and parsing it again for each made the Savings window take seconds.
330
+ */
331
+ const marksMemo = new Map();
332
+ export function transcriptMarks(path) {
333
+ const st = statSync(path);
334
+ const key = `${st.size}:${st.mtimeMs}`;
335
+ const had = marksMemo.get(path);
336
+ if (had?.key === key)
337
+ return had.marks;
338
+ const marks = [];
339
+ for (const line of readFileSync(path, 'utf8').split('\n')) {
340
+ const c = compactionOf(line);
341
+ const r = replyOf(line);
342
+ if (c || r)
343
+ marks.push({ c, r });
344
+ }
345
+ marksMemo.set(path, { key, marks });
346
+ return marks;
347
+ }
327
348
  /**
328
349
  * Read each stopped conversation after the stop: sent anyway, carried on small (compacted), or left. A stop that
329
350
  * came after a compaction (Claude Code's own, while you were away) had nothing at stake: it isn't counted.
@@ -337,11 +358,9 @@ export function outcomes(events = loadNudges()) {
337
358
  let after = null;
338
359
  let compacted = null;
339
360
  try {
340
- for (const line of readFileSync(event.transcript, 'utf8').split('\n')) {
341
- const c = compactionOf(line);
361
+ for (const { c, r } of transcriptMarks(event.transcript)) {
342
362
  if (c && !compacted && c.at > at - event.idleMs && c.at < until)
343
363
  compacted = c;
344
- const r = replyOf(line);
345
364
  if (r && r.at > at && r.at < until) {
346
365
  after = r;
347
366
  break;
@@ -369,11 +388,9 @@ export function warnOutcomes(events = loadNudges()) {
369
388
  let next = null;
370
389
  let compacted = null;
371
390
  try {
372
- for (const line of readFileSync(event.transcript, 'utf8').split('\n')) {
373
- const c = compactionOf(line);
391
+ for (const { c, r } of transcriptMarks(event.transcript)) {
374
392
  if (c && !compacted && c.at > at && c.at < coldAt)
375
393
  compacted = c;
376
- const r = replyOf(line);
377
394
  if (r && r.at > at) {
378
395
  next = r;
379
396
  break;
@@ -0,0 +1,39 @@
1
+ const tokens = (r) => r.input + r.output + r.cacheRead + r.cacheWrite5m + r.cacheWrite1h;
2
+ export function punchcard(rows, now, weeks = 4) {
3
+ const from = now.getTime() - weeks * 7 * 86_400_000;
4
+ const grid = Array.from({ length: 7 }, () => Array(24).fill(0));
5
+ for (const r of rows) {
6
+ const t = Date.parse(r.at);
7
+ if (!(t >= from && t <= now.getTime()))
8
+ continue;
9
+ const d = new Date(t);
10
+ grid[(d.getDay() + 6) % 7][d.getHours()] += tokens(r);
11
+ }
12
+ return { grid, quiet: quietStretch(grid), weeks };
13
+ }
14
+ /** Quiet = under 5% of your busiest hour, summed over the week. Wraps past midnight (e.g. 01:00–08:00). */
15
+ export function quietStretch(grid) {
16
+ const byHour = Array.from({ length: 24 }, (_, h) => grid.reduce((a, day) => a + day[h], 0));
17
+ const peak = Math.max(...byHour);
18
+ if (peak <= 0)
19
+ return null;
20
+ const quiet = byHour.map((x) => x <= peak * 0.05);
21
+ if (quiet.every(Boolean))
22
+ return null;
23
+ let best = { from: 0, len: 0 };
24
+ // Start right after a busy hour so a stretch is never split by midnight.
25
+ const start = quiet.findIndex((q) => !q);
26
+ for (let i = 0, run = 0, runFrom = 0; i < 24; i++) {
27
+ const h = (start + 1 + i) % 24;
28
+ if (quiet[h]) {
29
+ if (!run)
30
+ runFrom = h;
31
+ run += 1;
32
+ if (run > best.len)
33
+ best = { from: runFrom, len: run };
34
+ }
35
+ else
36
+ run = 0;
37
+ }
38
+ return best.len >= 4 ? { from: best.from, to: (best.from + best.len) % 24, hours: best.len } : null;
39
+ }
@@ -0,0 +1,111 @@
1
+ // The Savings window's data (`chompyy savings --json`): one bar for the week (what's fine vs what's fixable), each
2
+ // waste ranked with its status and before → after bars, and one conversation step by step to show a waste happen.
3
+ // It only gathers what other parts already measure: the nutrition label (label.ts), detect + codeburn (detect.ts),
4
+ // the saved-so-far total and each advice card's verdict (didwork.ts).
5
+ import { basename } from 'node:path';
6
+ import { coldReturns } from './detect.js';
7
+ /** The advice-card key a finding's card carries. */
8
+ export const keyOf = (f) => f.key ?? (f.source === 'codeburn' ? `cb:${f.codeburnId}` : f.rule);
9
+ const STATUS = { worked: 'worked', short: 'not yet', 'no-change': 'not yet', worse: 'not yet' };
10
+ function statusOf(card, f, declined) {
11
+ if (f.worthKnowing)
12
+ return 'worth knowing';
13
+ if (!card && declined)
14
+ return 'declined';
15
+ if (!card?.advice)
16
+ return 'to fix';
17
+ const v = card.advice.result?.verdict;
18
+ if (v && STATUS[v])
19
+ return STATUS[v];
20
+ // Approved, not in yet: a setting waiting for 10 idle minutes, or a work card waiting for the away run.
21
+ if (card.column === 'approved' || card.column === 'running')
22
+ return 'queued';
23
+ if (card.advice.state === 'applied' || card.advice.state === 'trying' || card.advice.state === 'done')
24
+ return 'applied';
25
+ return 'card waiting';
26
+ }
27
+ export function weekParts(label) {
28
+ return {
29
+ from: label.from,
30
+ to: label.to,
31
+ tokens: label.tokens,
32
+ // "Resent after a break" sits inside cache writes on the label; here it's its own slice, taken out of writes.
33
+ parts: label.lines.map((l, i) => {
34
+ const resent = /resent/i.test(l.name);
35
+ const next = label.lines[i + 1];
36
+ const minus = !l.sub && next?.sub && /resent/i.test(next.name) ? next : null;
37
+ const tokens = l.tokens - (minus?.tokens ?? 0);
38
+ return { name: l.name, tokens, pct: label.tokens ? Math.round((tokens / label.tokens) * 1000) / 10 : 0, fixable: resent };
39
+ }),
40
+ };
41
+ }
42
+ export function savingsRows(r, cards, dropped = new Set()) {
43
+ const advice = cards.filter((c) => c.advice).sort((a, b) => (b.updatedAt ?? '').localeCompare(a.updatedAt ?? ''));
44
+ const rows = r.findings.map((f) => {
45
+ const key = keyOf(f);
46
+ const card = advice.find((c) => c.advice.key === key || c.advice.key.startsWith(`${key}:`));
47
+ const res = card?.advice?.result;
48
+ // Cold returns: tokens rebuilt per week (the card's own check counts returns, which reads worse as bars).
49
+ const bars = f.rule === 'C1' && r.scanned.coldWeeks
50
+ ? r.scanned.coldWeeks.map((w, i, all) => ({ label: new Date(w.from).toLocaleDateString('en-US', { month: 'short', day: 'numeric' }), value: w.tokens, ...(i === all.length - 1 ? { highlight: true } : {}) }))
51
+ : res?.before !== undefined && res.after !== undefined
52
+ ? [{ label: 'Before', value: res.before }, { label: 'After', value: res.after, highlight: true }]
53
+ : undefined;
54
+ return {
55
+ key,
56
+ title: f.title,
57
+ say: f.say,
58
+ fix: f.fix,
59
+ ...(f.tokens !== undefined ? { tokens: f.tokens } : {}),
60
+ basis: f.basis,
61
+ source: f.source ?? 'chompyy',
62
+ status: statusOf(card, f, dropped.has(key) || [...dropped].some((d) => d.startsWith(`${key}:`))),
63
+ ...(bars ? { bars } : {}),
64
+ ...(res?.line ? { verdict: res.line } : {}),
65
+ ...(card ? { cardId: card.id } : {}),
66
+ };
67
+ });
68
+ // Fixes first by tokens; then what you declined; worth-knowing at the end.
69
+ const tier = (x) => (x.status === 'worth knowing' ? 2 : x.status === 'declined' ? 1 : 0);
70
+ return rows.sort((a, b) => tier(a) - tier(b) || (b.tokens ?? -1) - (a.tokens ?? -1));
71
+ }
72
+ /** The biggest cold return in the last 14 days, with up to 8 requests before it and 4 after. */
73
+ export function coldTrace(s, now) {
74
+ const since = now - 14 * 86_400_000;
75
+ let best = null;
76
+ for (const ses of s.sessions) {
77
+ const one = { ...s, sessions: [ses] };
78
+ for (const c of coldReturns(one, since)) {
79
+ if (!best || c.tokens > best.tokens)
80
+ best = { ses, i: ses.turns.findIndex((t) => t.at === c.at), tokens: c.tokens };
81
+ }
82
+ }
83
+ if (!best || best.i < 1)
84
+ return undefined;
85
+ const { ses, i } = best;
86
+ const turns = ses.turns.slice(Math.max(0, i - 8), i + 5);
87
+ return {
88
+ project: basename(ses.cwd || 'conversation'),
89
+ rebuilt: best.tokens,
90
+ steps: turns.map((t, k) => {
91
+ const prev = k > 0 ? turns[k - 1] : null;
92
+ return { at: new Date(t.at).toISOString(), written: t.cacheWrite, read: t.cacheRead, gapMin: prev ? Math.round((t.at - prev.at) / 60_000) : 0, cold: t === ses.turns[i] };
93
+ }),
94
+ };
95
+ }
96
+ export function savingsView(input) {
97
+ const rows = savingsRows(input.detect, input.cards, input.dropped);
98
+ const open = (r) => r.status === 'to fix' || r.status === 'card waiting';
99
+ for (const r of rows)
100
+ if (input.autoKeys?.has(r.key) || [...(input.autoKeys ?? [])].some((k) => k.startsWith(`${r.key}:`)))
101
+ r.auto = true;
102
+ const trace = input.scan ? coldTrace(input.scan, input.now.getTime()) : undefined;
103
+ return {
104
+ week: weekParts(input.label),
105
+ saved: input.saved,
106
+ fixable: { tokens: rows.filter((r) => !['worth knowing', 'worked', 'declined'].includes(r.status)).reduce((a, r) => a + (r.tokens ?? 0), 0), days: input.detect.scanned.days },
107
+ rows,
108
+ fixForMe: { count: rows.filter((r) => open(r) && r.auto).length, needsYou: rows.filter((r) => open(r) && !r.auto).length },
109
+ ...(trace ? { trace } : {}),
110
+ };
111
+ }
package/dist/stuck.js ADDED
@@ -0,0 +1,36 @@
1
+ export const KINDS = [
2
+ { id: 'rejected', label: 'actions you turned down', re: /user doesn't want to (proceed|take this action)|\[Request interrupted/i, fix: 'Say what you want up front, or put the rule in CLAUDE.md: you turned these down after Claude started them.' },
3
+ { id: 'not-read', label: 'writes before reading the file', re: /File has not been read yet/i, fix: 'Ask Claude to read a file before it edits it.' },
4
+ { id: 'stale', label: 'edits on stale text', re: /File has been modified since read|String to replace not found|String not found in file|replace_all is false/i, fix: 'Have Claude read the file again before editing: the text it tried to replace had changed or appears twice.' },
5
+ { id: 'path', label: 'wrong paths', re: /No such file or directory|File does not exist|ENOENT|No module named|Cannot find module/i, fix: 'Have Claude list the folder before opening files, or add the project layout to CLAUDE.md.' },
6
+ { id: 'blocked', label: 'blocked by permissions', re: /Permission denied|was blocked|Operation not permitted|not allowed/i, fix: 'Allow the commands you trust with /permissions, or tell Claude in CLAUDE.md what it may not run.' },
7
+ { id: 'missing-tool', label: 'commands not installed', re: /command not found/i, fix: 'Install the missing command, or tell Claude in CLAUDE.md what to use instead.' },
8
+ { id: 'timeout', label: 'timeouts', re: /timed out/i, fix: 'Ask Claude to run long commands in the background.' },
9
+ { id: 'input', label: 'malformed tool calls', re: /InputValidationError|SyntaxError|syntax error|jq: error/i, fix: 'Mostly the model\'s slip: nothing to change unless one tool keeps failing.' },
10
+ ];
11
+ /** The kind of one failed tool call's text; null when no pattern names it (a plain non-zero exit, say). */
12
+ export function errorKind(text) {
13
+ return KINDS.find((k) => k.re.test(text))?.id ?? null;
14
+ }
15
+ /** Fewer named failures than this in the scan: not a pattern worth a line. */
16
+ export const MIN_ERRORS = 10;
17
+ /** L2 · Where Claude gets stuck. Counts, not tokens: L1 already prices recovering from failures. */
18
+ export function ruleStuck(s) {
19
+ const ranked = [...(s.errors ?? new Map())].filter(([id]) => id !== 'rejected').sort((a, b) => b[1] - a[1]);
20
+ const named = ranked.reduce((a, [, n]) => a + n, 0);
21
+ if (named < MIN_ERRORS)
22
+ return [];
23
+ const top = ranked.slice(0, 3).map(([id, n]) => `${n} ${KINDS.find((k) => k.id === id).label}`);
24
+ const turnedDown = s.errors?.get('rejected') ?? 0;
25
+ const stopped = (s.interrupts ?? 0) + turnedDown;
26
+ const fix = KINDS.find((k) => k.id === ranked[0][0]).fix;
27
+ return [{
28
+ rule: 'L2',
29
+ title: 'Where Claude gets stuck',
30
+ say: `${s.failed ?? named} failed tool calls. Most named: ${top.join(', ')}.${stopped ? ` You stopped or turned down Claude ${stopped} times.` : ''}`,
31
+ basis: 'measured',
32
+ notProve: 'Counts what failed, not what it cost; some failures are quick tries.',
33
+ fix,
34
+ lane: 'habit',
35
+ }];
36
+ }
package/dist/suggest.js CHANGED
@@ -9,6 +9,7 @@ import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs';
9
9
  import { basename, join } from 'node:path';
10
10
  import { addCard } from './board.js';
11
11
  import { readTaste } from './taste.js';
12
+ import { approveScore, reasonFor } from './approvals.js';
12
13
  import { exe } from './exe.js';
13
14
  /** Vision and convention docs, in order of how much they say about where the repo is going. */
14
15
  const DOCS = ['README.md', 'VISION.md', 'ROADMAP.md', 'FEATURES.md', 'PLAN.md', 'TODO.md', 'CONTRIBUTING.md', 'CLAUDE.md', 'AGENTS.md'];
@@ -146,20 +147,29 @@ function parseJson(text) {
146
147
  export async function suggestTasks(repo, runner, opts) {
147
148
  const count = opts.count ?? 5;
148
149
  const digest = repoDigest(repo, { existing: opts.existing, issues: opts.issues ?? openIssues(repo) });
149
- const result = await runner.run({ prompt: suggestPrompt(digest.text, count), cwd: opts.cwd, model: opts.model, tools: '', timeoutMs: 240_000 });
150
+ const text = opts.approvals ? `${digest.text}\n\n${opts.approvals}` : digest.text;
151
+ const result = await runner.run({ prompt: suggestPrompt(text, count), cwd: opts.cwd, model: opts.model, tools: '', timeoutMs: 240_000 });
150
152
  if (result.timedOut)
151
153
  throw new Error('Suggesting tasks timed out. Try again.');
152
154
  if (result.exitCode !== 0)
153
155
  throw new Error(`claude exited with ${result.exitCode}: ${result.stderr.trim().slice(0, 300)}`);
154
156
  return validateTasks(parseJson(result.output), digest.sources, opts.existing, count);
155
157
  }
156
- /** The tasks as suggested cards in that repo, each saying where it came from. */
157
- export function addSuggested(board, repo, tasks, now) {
158
- return tasks.map((t) => {
158
+ /**
159
+ * The tasks as suggested cards in that repo, each saying where it came from. With `stats` (approvals.ts), the ones
160
+ * you'd most likely approve go first, and the why says so ("you approved 9 of 10 chores").
161
+ */
162
+ export function addSuggested(board, repo, tasks, now, stats = []) {
163
+ const why = (t) => `${t.kind === 'vision' ? 'Next step' : 'Chore'} from ${t.source} · ${t.size}${t.why ? `: ${t.why}` : ''}`;
164
+ const ranked = tasks
165
+ .map((t) => ({ t, card: { title: t.title, idea: t.idea, why: why(t), source: 'suggest' } }))
166
+ .map((x) => ({ ...x, score: approveScore(x.card, stats), reason: reasonFor(x.card, stats) }))
167
+ .sort((a, b) => b.score - a.score);
168
+ return ranked.map(({ t, card, reason }) => {
159
169
  const c = addCard(board, t.idea, repo, now, 'suggested');
160
170
  c.title = t.title;
161
171
  c.source = 'suggest';
162
- c.why = `${t.kind === 'vision' ? 'Next step' : 'Chore'} from ${t.source} · ${t.size}${t.why ? `: ${t.why}` : ''}`;
172
+ c.why = card.why + (reason ? ` · ${reason}` : '');
163
173
  return c;
164
174
  });
165
175
  }
@@ -3114,6 +3114,8 @@ export function cachedCallToApiCall(call) {
3114
3114
  deduplicationKey: call.deduplicationKey,
3115
3115
  cacheCreationOneHourTokens: u.cacheCreationOneHourTokens || undefined,
3116
3116
  toolSequence: call.toolSequence,
3117
+ // Chompyy patch: carry the cached tool-error count back (upstream caches it but drops it on read).
3118
+ ...(call.toolErrors ? { toolErrors: call.toolErrors } : {}),
3117
3119
  activeDurationMs: call.activeDurationMs,
3118
3120
  activeGeneratedTokens: call.activeGeneratedTokens,
3119
3121
  toolWaitMs: call.toolWaitMs,