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/README.md CHANGED
@@ -143,7 +143,7 @@ Each card in a git repo runs in its own worktree at `~/.chompyy/worktrees/<id>`
143
143
  | `chompyy trends` | Last 7 days vs the 7 before: cost per card, keep rate, rating, blueprint edits; then what Chompyy learned: rules this week, waiting, corrections per conversation |
144
144
  | `chompyy premise [--json]` | How often a 5-hour window reset with 20%+ left in a week that still had 10%+ spare: the capacity away runs can use. From your quota readings; every ended window is kept in `windows.jsonl` (numbers only), so it grows past the 8 days of `quota-history.json`. `--json` to share it |
145
145
  | `chompyy detect [--days 30] [--all] [--json]` | The detective: what wastes tokens in your setup and habits, from your own files. One screen: the findings ranked by tokens and the fix to start with; `--all` adds each finding's count, measured or estimated, what it doesn't prove, and every fix. A mid-session cache rebuild names its cause (e.g. Tool Search loading an MCP server's tools). Works cold with `npx chompyy detect`, nothing else installed. This version checks startup tax (long CLAUDE.md, unused skills and MCP servers, cut-off MEMORY.md) and cache (cold returns, mid-session rebuilds). Reads only; changes nothing |
146
- | `chompyy advise [--json]` | The detective, step 3: turns detect's findings into suggested cards on the board (the app's "Find savings"). Each card's plan shows what Chompyy saw, what it doesn't prove, the exact change and how it will check it worked. Approve a settings card (e.g. turn off a plugin you never use) and Chompyy applies it once no Claude Code session has been active for 10 minutes, backed up first; `chompyy undo <id>` puts it back if nothing changed it since. Habit cards are tracked from the day you approve; some things only you can do (claude.ai-synced skills). Dropped advice never comes back. Advice never runs on an away run |
146
+ | `chompyy advise [--json]` | The detective, step 3: turns detect's findings into suggested cards on the board (the app's Savings window: "Find savings again"; `chompyy advise fix` is its "Fix for me"). Each card's plan shows what Chompyy saw, what it doesn't prove, the exact change and how it will check it worked. Approve a settings card (e.g. turn off a plugin you never use) and Chompyy applies it once no Claude Code session has been active for 10 minutes, backed up first; `chompyy undo <id>` puts it back if nothing changed it since. Habit cards are tracked from the day you approve; some things only you can do (claude.ai-synced skills). Dropped advice never comes back. Advice never runs on an away run |
147
147
  | `chompyy advise apply` | Apply approved settings advice now if no session has been active for 10 minutes (the app and the 5-minute tick do this on their own) |
148
148
  | `chompyy worked [--all] [--json] [--share]` | Did the advice work: each applied card against the check it set up, plus the nudge's measured result, and one "Saved so far" total (also in the menu panel) that adds only what was counted. `--share` prints a summary with no project, skill or file names |
149
149
  | `chompyy nudge on\|off` | Live suggestions while you work. Adds a UserPromptSubmit hook to `~/.claude/settings.json` (backed up first; your other hooks stay). When you come back to a conversation of 40k+ tokens after more than an hour, its cache has expired: the hook stops that first message once and says what sending it rebuilds, what a fresh start costs, and the cheaper ways (/clear with a note, or /compact). Send it again and it goes through. A conversation compacted since its last reply (your /compact, or Claude Code's own while you were away) sends a summary, so it isn't stopped. Needs a global install (`npm install -g chompyy`); away runs turn hooks off, so it never touches them |
@@ -154,6 +154,8 @@ Each card in a git repo runs in its own worktree at `~/.chompyy/worktrees/<id>`
154
154
  | `chompyy recap [--month 2026-11] [--json]` | Your month with Chompyy on one card: tokens, API value and cookies, busiest day, conversations, cards baked and kept, biggest bake. This month once it's a week old, else last month. No names, safe to share |
155
155
  | `chompyy menu [--json]` | Every coding agent you used in the last 30 days as a café chalkboard: Claude Code and the others, tokens and API value, most first. Agent and model names only, safe to share |
156
156
  | `chompyy label [--json]` | Your week of Claude Code as a Nutrition Facts label: cached reads (fibre), cache writes (carbs), tokens resent after a break (added sugar), input and output (protein). Amounts only, safe to share |
157
+ | `chompyy approvals [--json]` | Which of Chompyy's suggestions you approve, by kind (repo tasks, chores, tests, docs, …), from what you approved, dropped or let expire. New suggestions are ranked by it and the suggester is told what you tend to want |
158
+ | `chompyy savings [--json]` | Where your tokens went this week (cheap cached reads vs the slice worth fixing), every waste ranked with its status (to fix, measuring, worked) and before → after, and your biggest cold return step by step. The app's Savings window draws it |
157
159
  | `chompyy stamps [--json]` | Your loyalty stamp card: one stamp per card you kept, ten to a card, with the dates. No titles, safe to share |
158
160
  | `chompyy agents [--json] [--refresh]` | Every other coding agent codeburn reads (Cursor, Copilot, Gemini CLI, OpenCode, … about 40): tokens and API value today, this week and over 30 and 90 days (agents used in the last 90 days), at most one scan per 10 minutes |
159
161
  | `chompyy codex [on\|off] [--json]` | Codex beside Claude: its 5-hour and weekly limits (reads Codex's saved login to ask OpenAI; never renews or changes it) and its tokens and API value (codeburn's Codex parser) |
@@ -57,3 +57,31 @@ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
57
57
  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
58
58
  SOFTWARE.
59
59
  ```
60
+
61
+ `cli/src/stuck.ts`: the error kinds are adapted from `ERROR_PATTERNS` in [sniffly](https://github.com/chiphuyen/sniffly) (`sniffly/core/constants.py`, MIT, Copyright (c) 2025 Chip Huyen), regrouped and reworded.
62
+
63
+ Its licence, in full:
64
+
65
+ ```
66
+ MIT License
67
+
68
+ Copyright (c) 2025 Chip Huyen
69
+
70
+ Permission is hereby granted, free of charge, to any person obtaining a copy
71
+ of this software and associated documentation files (the "Software"), to deal
72
+ in the Software without restriction, including without limitation the rights
73
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
74
+ copies of the Software, and to permit persons to whom the Software is
75
+ furnished to do so, subject to the following conditions:
76
+
77
+ The above copyright notice and this permission notice shall be included in all
78
+ copies or substantial portions of the Software.
79
+
80
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
81
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
82
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
83
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
84
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
85
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
86
+ SOFTWARE.
87
+ ```
package/dist/advice.js CHANGED
@@ -28,6 +28,63 @@ function plan(f, a, what) {
28
28
  `**Check:** ${a.check}`,
29
29
  ].filter(Boolean).join('\n\n');
30
30
  }
31
+ /** Most new-check cards one advise run makes, and the least tokens a week worth a card. */
32
+ export const NEW_CHECK_CARDS = 3;
33
+ export const NEW_CHECK_MIN_WEEK = 10_000;
34
+ /** codeburn reports that point at sessions or correlations, with no step to take: listed, never a card. */
35
+ const NO_CARD = new Set(['retry-heavy-capabilities', 'low-worth-sessions', 'cost-outliers']);
36
+ /**
37
+ * codeburn checks Chompyy can fix itself, as a Claude Code setting with a backup and Undo (settings lane): no
38
+ * shell-profile edits. These always get a card (not capped), since one approval does the whole fix.
39
+ */
40
+ export const AUTO_FIX = {
41
+ 'bash-output-cap': (settings) => ({
42
+ changes: [{ file: settings, key: ['env', 'BASH_MAX_OUTPUT_LENGTH'], from: settingAt(settings, ['env', 'BASH_MAX_OUTPUT_LENGTH']), to: '15000' }],
43
+ doing: 'Cap shell output at 15,000 characters in new sessions (Claude Code setting). Undo puts it back',
44
+ }),
45
+ };
46
+ function settingAt(file, key) {
47
+ try {
48
+ return getAt(JSON.parse(readFileSync(file, 'utf8')), key);
49
+ }
50
+ catch {
51
+ return undefined;
52
+ }
53
+ }
54
+ /** Tokens a week, from a total over `days` days. */
55
+ export const perWeek = (tokens, days) => Math.round((tokens / Math.max(1, days)) * 7);
56
+ /**
57
+ * A card for one of codeburn's checks or our newer rules: what it found, the exact fix to do (a command, a line for
58
+ * CLAUDE.md, or a habit), and the check registered before: the same check, per week, a third or less of today.
59
+ * Nothing is changed for you yet: "I've done it" (or trying the habit) starts the clock.
60
+ */
61
+ export function newCheckAdvice(f, days, settings = claudeSettingsPath()) {
62
+ if (!f.tokens)
63
+ return null;
64
+ const week = perWeek(f.tokens, days);
65
+ const habit = f.lane === 'habit';
66
+ const goal = Math.floor(week / 3);
67
+ const a = {
68
+ key: f.key ?? `cb:${f.codeburnId}`,
69
+ rule: f.rule,
70
+ lane: habit ? 'habit' : 'manual',
71
+ basis: f.basis,
72
+ tokens: f.tokens,
73
+ baseline: { tokens: week },
74
+ check: `It worked if this check finds ~${k(goal)} tokens a week or less (now ~${k(week)}).`,
75
+ saw: `${f.basis === 'estimated' ? '~' : ''}${k(week)} tokens a week: ${f.title.charAt(0).toLowerCase()}${f.title.slice(1)}`,
76
+ // codeburn's fix reads "<action>: <detail>"; the action alone is the short step.
77
+ doing: (f.source === 'codeburn' ? f.fix.split(': ')[0] : f.fix.split(/(?<=\.)\s/)[0]).replace(/\.$/, ''),
78
+ checkShort: `~${k(goal)} a week or less (now ~${k(week)})`,
79
+ };
80
+ const auto = f.codeburnId ? AUTO_FIX[f.codeburnId]?.(settings) : undefined;
81
+ if (auto) {
82
+ Object.assign(a, { lane: 'settings', changes: auto.changes, doing: auto.doing });
83
+ return { title: f.title, idea: auto.doing, plan: plan(f, a, settingsWhat(auto.changes)), advice: a };
84
+ }
85
+ const what = habit ? `**Try:** ${f.fix}` : `**Do:** ${f.fix}\n\nThen press "I've done it".`;
86
+ return { title: f.title, idea: f.fix, plan: plan(f, a, what), advice: a };
87
+ }
31
88
  const settingsWhat = (changes) => [
32
89
  '**The change:**',
33
90
  ...changes.map((c) => `- ${describeKey(c)}`),
@@ -39,7 +96,23 @@ export function adviceFrom(r, opts = {}) {
39
96
  const out = [];
40
97
  const settings = opts.settings ?? claudeSettingsPath();
41
98
  const home = homedir();
99
+ // codeburn's checks and our newer ones (own key): cards only for the biggest few with a concrete step, so the
100
+ // board isn't flooded; the rest stay in detect and the Savings window.
101
+ const isNew = (f) => (f.source === 'codeburn' || f.key) && !f.worthKnowing && !!f.tokens;
102
+ const autoFix = r.findings.filter((f) => isNew(f) && f.codeburnId && AUTO_FIX[f.codeburnId]);
103
+ const fresh = r.findings
104
+ .filter((f) => isNew(f) && !autoFix.includes(f) && !NO_CARD.has(f.codeburnId ?? '') && perWeek(f.tokens, r.scanned.days) >= NEW_CHECK_MIN_WEEK)
105
+ .sort((a, b) => b.tokens - a.tokens)
106
+ .slice(0, NEW_CHECK_CARDS);
107
+ for (const f of [...autoFix, ...fresh]) {
108
+ const draft = newCheckAdvice(f, r.scanned.days, settings);
109
+ if (draft)
110
+ out.push({ ...draft, cwd: home });
111
+ }
42
112
  for (const f of r.findings) {
113
+ // codeburn's checks and our newer ones (own key): handled above.
114
+ if (f.source === 'codeburn' || f.key)
115
+ continue;
43
116
  if (f.rule === 'C1') {
44
117
  const w = r.scanned.coldWeek;
45
118
  const a = {
@@ -147,7 +220,8 @@ export function adviceFrom(r, opts = {}) {
147
220
  return out;
148
221
  }
149
222
  /** Keys you dropped (not ones that expired unseen): those never come back. */
150
- function droppedKeys() {
223
+ /** Advice keys you dropped ("no, never"): never suggested again, and the Savings window says you declined them. */
224
+ export function droppedKeys() {
151
225
  const path = homePath('archive.jsonl');
152
226
  const keys = new Set();
153
227
  if (!existsSync(path))
@@ -220,6 +294,29 @@ export function approveAdvice(c, now) {
220
294
  a.state = a.lane === 'habit' ? 'trying' : 'done';
221
295
  return a.lane === 'habit' ? `✅ #${c.id} closed: trying it from today. ${a.check}` : `✅ #${c.id} closed. ${a.check}`;
222
296
  }
297
+ /** Lanes Chompyy carries out itself: a settings change (backed up, Undo) or a sandboxed away run. */
298
+ export const SELF_LANES = new Set(['settings', 'work']);
299
+ /**
300
+ * "Fix these for me": approve every suggested advice card Chompyy can carry out itself. Settings go in once no
301
+ * Claude Code session has run for 10 minutes; work cards run in the next away run (tonight's, with a bedtime).
302
+ * Habits and steps only you can take stay as they are, counted so the window can say so.
303
+ */
304
+ export function fixForMe(board, now) {
305
+ const open = board.cards.filter((c) => c.advice && (c.column === 'suggested' || c.column === 'later'));
306
+ const approved = [];
307
+ for (const c of open) {
308
+ if (!SELF_LANES.has(c.advice.lane))
309
+ continue;
310
+ if (c.advice.lane === 'work') {
311
+ c.column = 'approved';
312
+ c.approvedAt = c.updatedAt = now.toISOString();
313
+ }
314
+ else
315
+ approveAdvice(c, now);
316
+ approved.push(c);
317
+ }
318
+ return { approved, needsYou: open.length - approved.length };
319
+ }
223
320
  /** When a Claude Code session last wrote its transcript (ms), so settings never change under an open conversation. */
224
321
  export function lastSessionActivity(root = projectsDir()) {
225
322
  let last = 0;
@@ -0,0 +1,129 @@
1
+ // Which of Chompyy's suggestions you approve: a separate taste from how you like work done (FEATURES §3). Every
2
+ // suggested card you approve, drop or leave to expire is one decision; each card has a few plain features (where it
3
+ // came from, next step or chore, small or medium, what it's about). The approve rate per feature ranks new
4
+ // suggestions and tells the suggester what you tend to want. Counts only, from the board and its archive.
5
+ import { existsSync, readFileSync } from 'node:fs';
6
+ import { homePath } from './home.js';
7
+ const TOPICS = [
8
+ ['tests', /\btests?\b|\bspec\b|coverage/i],
9
+ ['docs', /\bdocs?\b|readme|documentation|changelog|comment/i],
10
+ ['bug fixes', /\bfix(es|ed)?\b|\bbug\b|crash|broken|error/i],
11
+ ['refactors', /refactor|clean ?up|simplif|rename|split|extract/i],
12
+ ['speed', /\bperf|faster|slow|cache|speed/i],
13
+ ['UI', /\bui\b|window|button|panel|popover|layout|board|menu/i],
14
+ ['savings', /token|quota|compact|skill|plugin|mcp/i],
15
+ ];
16
+ /** A card's features: "from repo tasks", "chores", "small", "tests", … (plain words: they show in the app and prompt). */
17
+ export function features(c) {
18
+ const out = [];
19
+ if (c.source === 'detect')
20
+ out.push('savings advice');
21
+ else if (c.source === 'history')
22
+ out.push('ideas from history');
23
+ else if (c.source === 'suggest')
24
+ out.push('repo tasks');
25
+ const why = c.why ?? '';
26
+ if (/^Chore\b/.test(why))
27
+ out.push('chores');
28
+ else if (/^Next step\b/.test(why))
29
+ out.push('next steps');
30
+ if (/· medium/.test(why))
31
+ out.push('medium tasks');
32
+ else if (/· small/.test(why))
33
+ out.push('small tasks');
34
+ // Topic from the title only: every suggested idea says how it's checked ("tests pass"), which isn't its topic.
35
+ for (const [name, re] of TOPICS)
36
+ if (re.test(c.title))
37
+ out.push(name);
38
+ return out;
39
+ }
40
+ const PAST_SUGGESTED = new Set(['approved', 'running', 'review', 'done']);
41
+ /** One decision per Chompyy-suggested card: approved (on the board), dropped or expired (in the archive). */
42
+ export function decisions(board, archived) {
43
+ const out = [];
44
+ for (const c of board.cards) {
45
+ if (!c.source)
46
+ continue;
47
+ if (c.approvedAt || PAST_SUGGESTED.has(c.column))
48
+ out.push({ card: c, outcome: 'yes' });
49
+ }
50
+ for (const c of archived) {
51
+ if (!c.source || !c.droppedAt)
52
+ continue;
53
+ if (c.approvedAt)
54
+ out.push({ card: c, outcome: 'yes' });
55
+ else
56
+ out.push({ card: c, outcome: c.expired ? 'ignored' : 'no' });
57
+ }
58
+ return out;
59
+ }
60
+ /** A feature needs this many decisions before it ranks anything or reaches the prompt. */
61
+ export const MIN_DECISIONS = 3;
62
+ export function featureStats(ds) {
63
+ const by = new Map();
64
+ for (const d of ds) {
65
+ for (const f of features(d.card)) {
66
+ const s = by.get(f) ?? { feature: f, yes: 0, no: 0, ignored: 0, rate: 0 };
67
+ s[d.outcome] += 1;
68
+ by.set(f, s);
69
+ }
70
+ }
71
+ for (const s of by.values())
72
+ s.rate = (s.yes + 1) / (s.yes + s.no + s.ignored / 2 + 2);
73
+ return [...by.values()].sort((a, b) => b.rate - a.rate || b.yes - a.yes);
74
+ }
75
+ const decided = (s) => s.yes + s.no + s.ignored;
76
+ /** How likely you'd approve this card: the mean rate of its features with enough decisions, else 0.5. */
77
+ export function approveScore(c, stats) {
78
+ const known = features(c).map((f) => stats.find((s) => s.feature === f)).filter((s) => !!s && decided(s) >= MIN_DECISIONS);
79
+ return known.length ? known.reduce((a, s) => a + s.rate, 0) / known.length : 0.5;
80
+ }
81
+ /** The strongest reason a card ranks where it does, e.g. "you approved 9 of 10 chores". */
82
+ export function reasonFor(c, stats) {
83
+ const known = features(c).map((f) => stats.find((s) => s.feature === f)).filter((s) => !!s && decided(s) >= MIN_DECISIONS);
84
+ const top = known.sort((a, b) => Math.abs(b.rate - 0.5) - Math.abs(a.rate - 0.5))[0];
85
+ return top ? `you approved ${top.yes} of ${decided(top)} ${top.feature}` : null;
86
+ }
87
+ /** For the suggester's prompt: what you tend to approve and drop. Empty until there are enough decisions. */
88
+ export function approvalsPrompt(stats) {
89
+ const known = stats.filter((s) => decided(s) >= MIN_DECISIONS);
90
+ const likes = known.filter((s) => s.rate >= 0.6).slice(0, 3);
91
+ const dislikes = known.filter((s) => s.rate <= 0.4).slice(-3);
92
+ if (!likes.length && !dislikes.length)
93
+ return '';
94
+ const say = (s) => `${s.feature} (approved ${s.yes} of ${decided(s)})`;
95
+ return [
96
+ '## Which suggestions the owner approves (from past decisions)',
97
+ likes.length ? `Tends to approve: ${likes.map(say).join(', ')}.` : '',
98
+ dislikes.length ? `Tends to drop or ignore: ${dislikes.map(say).join(', ')}. Suggest fewer of these unless the source is strong.` : '',
99
+ ].filter(Boolean).join('\n');
100
+ }
101
+ export function loadArchive() {
102
+ const path = homePath('archive.jsonl');
103
+ if (!existsSync(path))
104
+ return [];
105
+ const out = [];
106
+ for (const line of readFileSync(path, 'utf8').split('\n')) {
107
+ try {
108
+ if (line.trim())
109
+ out.push(JSON.parse(line));
110
+ }
111
+ catch { }
112
+ }
113
+ return out;
114
+ }
115
+ export function approvalStats(board) {
116
+ return featureStats(decisions(board, loadArchive()));
117
+ }
118
+ export function approvalsText(stats, total) {
119
+ if (!total)
120
+ return 'No decisions on suggested cards yet. Approve or drop a few and Chompyy learns which ones you want.';
121
+ const known = stats.filter((s) => decided(s) >= MIN_DECISIONS);
122
+ const lines = [`What you approve, from ${total} decisions on suggested cards:`, ''];
123
+ for (const s of known.slice(0, 8))
124
+ lines.push(` ${String(Math.round(s.rate * 100)).padStart(3)}% ${s.feature.padEnd(20)} approved ${s.yes}, dropped ${s.no}, let expire ${s.ignored}`);
125
+ if (!known.length)
126
+ lines.push(` Not enough yet: each kind needs ${MIN_DECISIONS} decisions.`);
127
+ lines.push('', 'New suggestions are ranked by this, and the suggester is told what you tend to want.');
128
+ return lines.join('\n');
129
+ }
package/dist/appstate.js CHANGED
@@ -20,6 +20,8 @@ import { learning } from './learning.js';
20
20
  import { describeSignal, loadStore, nextQuestion, readSignals, receipts } from './taste.js';
21
21
  import { agentInstalled, awayRunning, loadTriggerState } from './triggers.js';
22
22
  import { nightcap } from './nightcap.js';
23
+ import { punchcard } from './punchcard.js';
24
+ import { loadLedger } from './usage.js';
23
25
  import { demonOffer } from './demon.js';
24
26
  import { planFor } from './permissions.js';
25
27
  import { loadProfile, preflightHosts } from './preflight.js';
@@ -135,6 +137,14 @@ export function nightcapNow(board, config, now) {
135
137
  approved: board.cards.filter((c) => c.column === 'approved').length,
136
138
  fired: loadTriggerState().fired,
137
139
  awayBusy: awayRunning() !== null,
140
+ quietFrom: () => {
141
+ try {
142
+ return punchcard(loadLedger().rows, now).quiet?.from ?? null;
143
+ }
144
+ catch {
145
+ return null;
146
+ }
147
+ },
138
148
  });
139
149
  }
140
150
  function safeWarmCaches(now) {
package/dist/away.js CHANGED
@@ -7,7 +7,7 @@ import { formatDuration } from './duration.js';
7
7
  import { budgetGate } from './gate.js';
8
8
  import { homePath } from './home.js';
9
9
  import { windowView } from './quota.js';
10
- import { costRange, readRuns, recordRun, usedBetween } from './costs.js';
10
+ import { costRange, hitRate, readRuns, recordRun, usedBetween } from './costs.js';
11
11
  import { applyPermissions } from './permissions.js';
12
12
  import { tasteForPrompt } from './taste.js';
13
13
  import { boxTempDirs } from './verify.js';
@@ -280,11 +280,15 @@ export async function runCard(id, timeoutMs, deps, trigger) {
280
280
  const c = getCard(b, id);
281
281
  c.column = 'running';
282
282
  c.updatedAt = new Date(startedMs).toISOString();
283
- const est = costRange(c, readRuns());
283
+ const past = readRuns();
284
+ const est = costRange(c, past);
285
+ const right = hitRate(past);
284
286
  c.oven = {
285
287
  since: c.updatedAt,
286
288
  until: new Date(startedMs + timeoutMs).toISOString(),
287
289
  ...(est ? { expect: new Date(startedMs + Math.min(est.durationMidMs, timeoutMs)).toISOString(), from: est.n } : {}),
290
+ // How often these ranges were right (a backtest over past runs): the timer's hover says it.
291
+ ...(est && right && right.time.of >= 3 ? { right: right.time } : {}),
288
292
  };
289
293
  return { ...c };
290
294
  });
package/dist/cli.js CHANGED
@@ -4,7 +4,7 @@ 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, writeFileSync } from 'node:fs';
7
- import { resolve } from 'node:path';
7
+ import { join, resolve } from 'node:path';
8
8
  import { parseArgs } from 'node:util';
9
9
  import { away, runCard } from './away.js';
10
10
  import { formatPreflight, loadProfile, preflight, saveProfile } from './preflight.js';
@@ -32,26 +32,29 @@ import { nutritionLabel } from './label.js';
32
32
  import { recap, recapMonth } from './recap.js';
33
33
  import { menuFrom } from './menu.js';
34
34
  import { limitsState, READERS, refreshLimits } from './agentlimits.js';
35
- import { detect, detectText } from './detect.js';
35
+ import { detectFull, detectText, scan } from './detect.js';
36
+ import { savingsView } from './savings.js';
37
+ import { punchcard } from './punchcard.js';
38
+ import { approvalsPrompt, approvalStats, approvalsText, decisions, featureStats, loadArchive } from './approvals.js';
36
39
  import { allWindowEnds, archiveWindowEnds, premise, premiseText } from './premise.js';
37
40
  import { keychainAllowed, loadLiveState, refreshLiveQuota } from './livequota.js';
38
41
  import { recentProjects } from './projects.js';
39
- import { cliVersion, installApp } from './macapp.js';
42
+ import { cliVersion, installApp, installedVersion, isNewer } from './macapp.js';
40
43
  import { buildDigest, historyRetention, scanHistory } from './history.js';
41
44
  import { acceptColdStart, forgetColdStart, formatColdStart, loadColdStart, runColdStart } from './coldstart.js';
42
45
  import { keepHistory } from './claudesettings.js';
43
46
  import { blueprintHash, drawPicture } from './picture.js';
44
47
  import { receipt, receiptText } from './receipt.js';
45
- import { costRange, formatCostRange, readRuns, tasteEffect, tasteEffectLine, trendLines } from './costs.js';
48
+ import { costRange, formatCostRange, hitRate, readRuns, tasteEffect, tasteEffectLine, trendLines } from './costs.js';
46
49
  import { answerPreference, distill, distillDue, formatPrefs, formatQuestion, formatWhy, getPref, learnedCount, loadStore, nextQuestion, readSignals, recordOutcome, renderAgentsBlock, retirePreference, syncTasteFile, tasteChangesSince, tasteRulesForProject, } from './taste.js';
47
50
  import { cachedWorkspaces, dream, dreamDue, formatDream, formatWorkspaces, projectsDir, readLogPath, setTicked } from './dream.js';
48
51
  import { byKind, compactTokens, compare, formatExtras, formatUsage, loadLedger, periodDays, PERIODS, prCosts, usageView } from './usage.js';
49
52
  import { formatTrace, traceSession } from './trace.js';
50
53
  import { homedir } from 'node:os';
51
54
  import { clashOf, refreshCard, refreshGate, refreshClashing, withRefreshLock } from './refresh.js';
52
- import { adviseText, applyDue, approveAdvice, runAdvise, undoAdvice } from './advice.js';
55
+ import { adviceFrom, adviseText, applyDue, approveAdvice, droppedKeys, fixForMe, runAdvise, SELF_LANES, undoAdvice } from './advice.js';
53
56
  import { daytimeFile, daytimeState, setDaytime } from './daytime.js';
54
- import { checkWorked, nudgeProofText, savedSoFar, shareText, workedText } from './didwork.js';
57
+ import { checkWorked, isNewCheck, measurable, newCheckDays, nudgeProofText, savedSoFar, shareText, workedText } from './didwork.js';
55
58
  import { addSuggested, suggestTasks, suggestText } from './suggest.js';
56
59
  import { coldWarningText, hookCommand, impact, loadNudges, nudgeInstalled, nudgeText, runHook, setNudge, setProjectMode, takeGoingCold } from './nudge.js';
57
60
  import { withKeepLock } from './keeplock.js';
@@ -148,6 +151,8 @@ Triggers (start away runs on their own; the budget gate still decides every card
148
151
  chompyy recap [--month 2026-11] [--json] your month on one shareable card: tokens, busiest day, cards baked
149
152
  chompyy menu [--json] every agent you used in 30 days as a café chalkboard: tokens and value, safe to share
150
153
  chompyy label [--json] your week as Nutrition Facts: cached reads, cache writes, resent tokens, output; shareable
154
+ chompyy approvals [--json] which suggestions you approve, by kind; ranks new suggestions
155
+ chompyy savings [--json] where your tokens went, what's worth fixing, what your fixes saved
151
156
  chompyy stamps [--json] your loyalty stamp card: one stamp per kept card, ten to a card; shareable
152
157
  chompyy agents [--json] every other coding agent on this Mac (Cursor, Copilot, Gemini, …): tokens and value
153
158
  chompyy codex [on|off] [--json] Codex's limits and tokens beside Claude's (on = read its login, never change it)
@@ -692,6 +697,30 @@ async function main(argv) {
692
697
  console.log(l.tip);
693
698
  return;
694
699
  }
700
+ case 'savings': {
701
+ // The Savings window: the week as one bar (fine vs fixable), every waste ranked with its status and
702
+ // before → after, and one conversation step by step (savings.ts).
703
+ let resent = 0;
704
+ try {
705
+ resent = impact().thisWeek.tokens;
706
+ }
707
+ catch { }
708
+ const label = nutritionLabel(loadLedger().rows, resent, now);
709
+ const r = await detectFull({ now });
710
+ const cards = loadBoard().cards;
711
+ const { total } = savedSoFar(cards.filter((c) => c.advice), now, { on: nudgeInstalled() || loadNudges().length > 0 });
712
+ const view = savingsView({ label, detect: r, cards, saved: total ? { tokens: total.tokens, since: total.since, line: total.line } : null, scan: scan({ days: 14, now }), now, dropped: droppedKeys(), autoKeys: new Set(adviceFrom(r, { nudgeOn: nudgeInstalled() }).filter((d) => SELF_LANES.has(d.advice.lane)).map((d) => d.advice.key)) });
713
+ if (values.json)
714
+ return json(view);
715
+ console.log(`This week: ${compactTokens(view.week.tokens)} tokens, ${view.week.parts.filter((p) => p.fixable).map((p) => `${compactTokens(p.tokens)} resent for nothing`).join('') || 'nothing resent'}.`);
716
+ if (view.saved)
717
+ console.log(view.saved.line);
718
+ console.log(`Still fixable: ~${compactTokens(view.fixable.tokens)} tokens in ${view.fixable.days} days.\n`);
719
+ for (const row of view.rows.slice(0, 5))
720
+ console.log(` ${row.status.padEnd(13)} ${row.tokens === undefined ? '' : compactTokens(row.tokens).padStart(6)} ${row.title}`);
721
+ console.log('\nOpen it as a picture: the Savings window in the app.');
722
+ return;
723
+ }
695
724
  case 'stamps': {
696
725
  // The loyalty stamp card: one stamp per kept card, ten to a card. Safe to share (no titles).
697
726
  const c = stampCard(loadBoard().cards);
@@ -781,9 +810,14 @@ async function main(argv) {
781
810
  return console.log(formatLive(loadLive()));
782
811
  }
783
812
  case 'app': {
784
- console.log(`Downloading Chompyy ${cliVersion()} for Mac…`);
785
- const at = await installApp();
786
- console.log(`Installed ${at} and opened it. Look for the cookie in your menu bar.`);
813
+ const have = installedVersion(join(homedir(), 'Applications'));
814
+ if (!have || !isNewer(have, cliVersion()))
815
+ console.log(`Downloading Chompyy ${cliVersion()} for Mac…`);
816
+ const r = await installApp();
817
+ if (r.kept)
818
+ console.log(`Opened Chompyy ${r.kept}. Kept it: this chompyy command is older (${cliVersion()}).\nUpdate the command: npm install -g chompyy@latest`);
819
+ else
820
+ console.log(`Installed ${r.at} and opened it. Look for the cookie in your menu bar.`);
787
821
  return;
788
822
  }
789
823
  case 'history': {
@@ -951,7 +985,7 @@ async function main(argv) {
951
985
  console.log(` #${card.id} ${card.title} [${state}]`);
952
986
  if (card.column === 'later' && !card.blueprint?.trim())
953
987
  console.log(' blueprint needed before approval');
954
- console.log(` ${formatCostRange(costRange(card, runs))}`);
988
+ console.log(` ${formatCostRange(costRange(card, runs), hitRate(runs))}`);
955
989
  }
956
990
  console.log('\nThis is a read-only list. Start selected work with `chompyy away <duration>`.');
957
991
  return;
@@ -1015,7 +1049,7 @@ async function main(argv) {
1015
1049
  return json(cardView(card));
1016
1050
  console.log(formatCard(card));
1017
1051
  if (!card.run)
1018
- console.log(`\n${formatCostRange(costRange(card, readRuns()))}`);
1052
+ console.log(`\n${formatCostRange(costRange(card, readRuns()), hitRate(readRuns()))}`);
1019
1053
  else if (card.run.cost?.fiveHourPct != null)
1020
1054
  console.log(`used ${card.run.cost.fiveHourPct}% of the 5h window${card.run.trigger ? ` · started by the ${card.run.trigger} trigger` : ''}`);
1021
1055
  return;
@@ -1371,7 +1405,7 @@ async function main(argv) {
1371
1405
  if (values.json && values.app) {
1372
1406
  const long = usageView(ledger, now, 84, 0, canShow);
1373
1407
  const week = usageView(ledger, now, 7, 10, canShow);
1374
- return json({ generatedAt: to, period: period || `${days}d`, days: long.days, today: long.today, week, view: { ...view, byKind: kinds, prs }, compare: cmp, unpriced: long.unpriced });
1408
+ return json({ generatedAt: to, period: period || `${days}d`, days: long.days, today: long.today, week, view: { ...view, byKind: kinds, prs }, compare: cmp, unpriced: long.unpriced, punchcard: punchcard(ledger.rows, now) });
1375
1409
  }
1376
1410
  if (values.json)
1377
1411
  return json({ ...view, byKind: kinds, prs, compare: cmp });
@@ -1404,7 +1438,7 @@ async function main(argv) {
1404
1438
  return;
1405
1439
  }
1406
1440
  case 'detect': {
1407
- const r = detect({ days: values.days ? Number(values.days) : 30, now });
1441
+ const r = await detectFull({ days: values.days ? Number(values.days) : 30, now });
1408
1442
  if (values.json)
1409
1443
  return json(r);
1410
1444
  console.log(detectText(r, { all: Boolean(values.all), projects: projectsDir().replace(homedir(), '~') }).join('\n'));
@@ -1419,7 +1453,26 @@ async function main(argv) {
1419
1453
  return json(lines);
1420
1454
  return console.log(lines.length ? lines.join('\n') : 'Nothing waiting to be applied.');
1421
1455
  }
1422
- const res = updateBoard((b) => runAdvise(b, now));
1456
+ const found = await detectFull({ now });
1457
+ if (args[0] === 'fix') {
1458
+ // "Fix these for me" (Savings window): cards for every finding, then approve what Chompyy can do itself.
1459
+ updateBoard((b) => runAdvise(b, now, found));
1460
+ const res = updateBoard((b) => fixForMe(b, now));
1461
+ const applied = updateBoard((b) => applyDue(b, now));
1462
+ if (values.json)
1463
+ return json({ approved: res.approved.map((c) => ({ id: c.id, title: c.title, lane: c.advice.lane })), needsYou: res.needsYou, applied });
1464
+ if (!res.approved.length)
1465
+ return console.log(`Nothing Chompyy can fix by itself right now.${res.needsYou ? ` ${res.needsYou} need you: habits and steps only you can take.` : ''}`);
1466
+ console.log(`Fixing ${res.approved.length}:`);
1467
+ for (const c of res.approved)
1468
+ console.log(` #${c.id} ${c.title} · ${c.advice.lane === 'work' ? 'runs in the next away run' : 'settings, once no session has run for 10 min (Undo any time)'}`);
1469
+ for (const line of applied)
1470
+ console.log(` ${line}`);
1471
+ if (res.needsYou)
1472
+ console.log(`${res.needsYou} need you: habits and steps only you can take.`);
1473
+ return;
1474
+ }
1475
+ const res = updateBoard((b) => runAdvise(b, now, found));
1423
1476
  if (values.json)
1424
1477
  return json({ added: res.added.map((c) => c.id), updated: res.updated.map((c) => c.id), skipped: res.skipped });
1425
1478
  return console.log(adviseText(res));
@@ -1439,7 +1492,14 @@ async function main(argv) {
1439
1492
  }
1440
1493
  case 'worked': {
1441
1494
  // The detective, step 5: each applied/tried advice card against the check it registered (didwork.ts).
1442
- const cards = updateBoard((b) => checkWorked(b, now));
1495
+ // New-check cards (codeburn's checks, our newer rules) re-run those checks over the days since each started.
1496
+ const recheck = new Map();
1497
+ for (const c of loadBoard().cards.filter((x) => measurable(x) && isNewCheck(x.advice))) {
1498
+ const days = newCheckDays(Date.parse(c.advice.since ?? c.approvedAt ?? c.updatedAt), now.getTime());
1499
+ if (days >= 7 && !recheck.has(days))
1500
+ recheck.set(days, (await detectFull({ days, now })).findings);
1501
+ }
1502
+ const cards = updateBoard((b) => checkWorked(b, now, { recheck }));
1443
1503
  const { proof, total } = savedSoFar(cards, now, { on: nudgeInstalled() || loadNudges().length > 0 });
1444
1504
  if (values.share) {
1445
1505
  // A summary to paste on the tester issue: counts, tokens and dates; no project, skill or file names.
@@ -1465,13 +1525,25 @@ async function main(argv) {
1465
1525
  throw new Error('Suggesting tasks needs the claude command (Claude Code in Terminal). See TRY.md.');
1466
1526
  if (!values.force && !windowActive(now))
1467
1527
  throw new Error('No active 5-hour window: suggesting now would start one. Try again while you use Claude Code, or add --force.');
1468
- const existing = loadBoard().cards.map((c) => c.title);
1469
- const { tasks, dropped } = await suggestTasks(repo, new ClaudeRunner(config.claudeBin), { model: config.suggestModel, cwd: chompyyHome(), existing });
1470
- const cards = updateBoard((b) => addSuggested(b, repo, tasks, now));
1528
+ const board = loadBoard();
1529
+ const existing = board.cards.map((c) => c.title);
1530
+ // What you tend to approve (approvals.ts) steers the suggester and ranks what comes back.
1531
+ const stats = approvalStats(board);
1532
+ const { tasks, dropped } = await suggestTasks(repo, new ClaudeRunner(config.claudeBin), { model: config.suggestModel, cwd: chompyyHome(), existing, approvals: approvalsPrompt(stats) });
1533
+ const cards = updateBoard((b) => addSuggested(b, repo, tasks, now, stats));
1471
1534
  if (values.json)
1472
1535
  return json({ repo, added: cards.map((c) => ({ id: c.id, title: c.title, why: c.why })), dropped });
1473
1536
  return console.log(suggestText(repo, cards, dropped));
1474
1537
  }
1538
+ case 'approvals': {
1539
+ // Which suggestions you approve: the rate per kind of card, from approvals, drops and expiries.
1540
+ const board = loadBoard();
1541
+ const ds = decisions(board, loadArchive());
1542
+ const stats = featureStats(ds);
1543
+ if (values.json)
1544
+ return json({ decisions: ds.length, features: stats });
1545
+ return console.log(approvalsText(stats, ds.length));
1546
+ }
1475
1547
  case 'hook': {
1476
1548
  // Claude Code's UserPromptSubmit hook. Must never fail loudly or stop a prompt by accident.
1477
1549
  if (args[0] !== 'prompt')
package/dist/costs.js CHANGED
@@ -86,13 +86,51 @@ export function costRange(card, runs) {
86
86
  basis,
87
87
  };
88
88
  }
89
+ /**
90
+ * Backtest: for each past run, the range Chompyy would have given from only the runs before it, and whether the run
91
+ * landed inside. The last `last` runs that had a range count. Same formula as costRange, so it's the range you saw.
92
+ */
93
+ export function hitRate(runs, last = 10) {
94
+ const ordered = [...runs].sort((a, b) => a.at.localeCompare(b.at));
95
+ const time = [];
96
+ const quota = [];
97
+ for (let i = 0; i < ordered.length; i++) {
98
+ const r = ordered[i];
99
+ if (r.status === 'error')
100
+ continue;
101
+ const est = costRange({ id: r.card, title: r.title, idea: r.idea, cwd: r.cwd }, ordered.slice(0, i));
102
+ if (!est)
103
+ continue;
104
+ time.push(r.durationMs >= est.durationLowMs && r.durationMs <= est.durationHighMs);
105
+ if (r.fiveHourPct !== null)
106
+ quota.push(r.fiveHourPct >= est.low && r.fiveHourPct <= est.high);
107
+ }
108
+ if (!time.length)
109
+ return null;
110
+ const tail = (xs) => xs.slice(-last);
111
+ return {
112
+ time: { hit: tail(time).filter(Boolean).length, of: tail(time).length },
113
+ quota: { hit: tail(quota).filter(Boolean).length, of: tail(quota).length },
114
+ };
115
+ }
116
+ /** Both, plainly: "the quota range was right for 8 of the last 10 runs, the time range for 5 of 10". Needs 3 runs. */
117
+ export function hitLine(h) {
118
+ if (!h)
119
+ return '';
120
+ const q = h.quota.of >= 3 ? `the quota range was right for ${h.quota.hit} of the last ${h.quota.of} runs` : '';
121
+ const t = h.time.of >= 3 ? `the time range for ${h.time.hit} of ${h.time.of}` : '';
122
+ if (q && t)
123
+ return `${q}, ${t}`;
124
+ return q || (t ? `the time range was right for ${h.time.hit} of the last ${h.time.of} runs` : '');
125
+ }
89
126
  const fmtPct = (n) => (n < 10 ? String(Math.round(n * 10) / 10) : String(Math.round(n)));
90
- export function formatCostRange(r) {
127
+ export function formatCostRange(r, hit = null) {
91
128
  if (!r)
92
129
  return 'Cost: not known yet (needs 2 past runs)';
130
+ const right = hitLine(hit);
93
131
  const pct = r.low === r.high ? `~${fmtPct(r.low)}%` : `${fmtPct(r.low)}–${fmtPct(r.high)}%`;
94
132
  const dur = r.durationLowMs === r.durationHighMs ? formatDuration(r.durationLowMs) : `${formatDuration(r.durationLowMs)}–${formatDuration(r.durationHighMs)}`;
95
- return `Cost: ${pct} of a 5h window · ${dur} (from ${r.n} ${r.basis === 'similar' ? 'similar' : 'past'} run${r.n === 1 ? '' : 's'})`;
133
+ return `Cost: ${pct} of a 5h window · ${dur} (from ${r.n} ${r.basis === 'similar' ? 'similar' : 'past'} run${r.n === 1 ? '' : 's'})${right ? `\n So far ${right}.` : ''}`;
96
134
  }
97
135
  export function periodStats(runs, signals, from, to) {
98
136
  const inRange = (at) => {