chompyy 0.4.1 → 0.4.3

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
@@ -130,6 +130,11 @@ Each card in a git repo runs in its own worktree at `~/.chompyy/worktrees/<id>`
130
130
  | `chompyy trends` | Last 7 days vs the 7 before: cost per card, keep rate, rating, blueprint edits |
131
131
  | `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 |
132
132
  | `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 |
133
+ | `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 |
134
+ | `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) |
135
+ | `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. Needs a global install (`npm install -g chompyy`); away runs turn hooks off, so it never touches them |
136
+ | `chompyy nudge [--json]` | On or off, what the stops and warnings led to (compacted, left, sent anyway), the tokens not written again, and the measured trend: cold returns this week against last week. The menu panel shows the same line |
137
+ | `chompyy nudge due [--json]` | Conversations 45-60 minutes into a pause, about to go cold, each reported once (only while nudge is on). The menu bar app asks every minute and sends a notification, while /compact is still cheap |
133
138
  | `chompyy triggers on\|off` | Install or remove the macOS LaunchAgent that runs `chompyy tick` every 5 minutes |
134
139
  | `chompyy bedtime <23:30\|off>` / `last-hour <on\|off>` / `missed-reset <on\|off>` | Turn the bedtime, last-hour-before-reset and missed-reset (first tick after an unused reset, default off) triggers on or off |
135
140
 
package/dist/advice.js ADDED
@@ -0,0 +1,383 @@
1
+ // The detective, step 3: Advice cards (FEATURES.md §6, research/detective/RULEBOOK.md "Fix lanes"). Each detect
2
+ // finding becomes a suggested card you approve or drop. What approving does depends on the lane:
3
+ // settings the exact change shown on the card, applied when no Claude Code session is active (so no open
4
+ // conversation's cache is thrown away), backed up first; Undo puts it back if nothing changed it since
5
+ // habit nothing to apply: the card is marked "trying", with the baseline it will be checked against
6
+ // manual something only you can do (claude.ai settings, files outside a repo): marked "done by you"
7
+ // work a normal card: blueprint, away run on its own branch, keep or undo
8
+ // Every card states before it's applied what will be measured afterwards and what counts as "worked" (rule 7).
9
+ import { copyFileSync, cpSync, existsSync, readdirSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from 'node:fs';
10
+ import { homedir } from 'node:os';
11
+ import { basename, join } from 'node:path';
12
+ import { addCard } from './board.js';
13
+ import { detect, isAutomated } from './detect.js';
14
+ import { projectsDir } from './dream.js';
15
+ import { homePath } from './home.js';
16
+ import { claudeSettingsPath, nudgeInstalled } from './nudge.js';
17
+ import { gitRoot } from './workspace.js';
18
+ /** Don't touch settings while a Claude Code session was active this recently. */
19
+ export const IDLE_BEFORE_APPLY_MS = 10 * 60_000;
20
+ const k = (n) => (n >= 1e6 ? `${(n / 1e6).toFixed(1)}M` : n >= 1000 ? `${Math.round(n / 1000)}k` : `${n}`);
21
+ const tilde = (p) => p.replace(homedir(), '~');
22
+ const describeKey = (c) => `\`${tilde(c.file)}\`: \`${c.key.map((x, i) => (i ? `["${x}"]` : x)).join('')}\`: ${JSON.stringify(c.from ?? '(not set)')} → ${JSON.stringify(c.to)}`;
23
+ function plan(f, a, what) {
24
+ return [
25
+ `**Evidence** (${f.basis}): ${f.say}`,
26
+ f.notProve ? `**Not proven:** ${f.notProve}` : '',
27
+ what,
28
+ `**Check:** ${a.check}`,
29
+ ].filter(Boolean).join('\n\n');
30
+ }
31
+ const settingsWhat = (changes) => [
32
+ '**The change:**',
33
+ ...changes.map((c) => `- ${describeKey(c)}`),
34
+ '',
35
+ 'Applied once no Claude Code session has run for 10 minutes, so no open cache is lost. Backed up; Undo restores it.',
36
+ ].join('\n');
37
+ /** The cards detect's findings turn into. */
38
+ export function adviceFrom(r, opts = {}) {
39
+ const out = [];
40
+ const settings = opts.settings ?? claudeSettingsPath();
41
+ const home = homedir();
42
+ for (const f of r.findings) {
43
+ if (f.rule === 'C1') {
44
+ const w = r.scanned.coldWeek;
45
+ const a = {
46
+ key: 'C1',
47
+ rule: 'C1',
48
+ lane: 'habit',
49
+ basis: f.basis,
50
+ ...(f.tokens ? { tokens: f.tokens } : {}),
51
+ check: w
52
+ ? `Cold returns a week: ${w.count} before you start. It worked if week two has ${Math.floor((w.count * 2) / 3)} or fewer.`
53
+ : 'Cold returns a week, against the week before you start.',
54
+ };
55
+ const fix = 'Before a long break: /compact, or leave a note and start fresh.' + (opts.nudgeOn ? '' : ' `chompyy nudge on` reminds you in time.');
56
+ a.saw = `${k(f.tokens ?? 0)} tokens rewritten in 14 days: you came back after the cache expired`;
57
+ a.doing = 'Before a break: /compact, or leave a note and start fresh';
58
+ a.checkShort = w ? `Week two: ${Math.floor((w.count * 2) / 3)} or fewer cold returns (was ${w.count})` : 'Fewer cold returns a week';
59
+ const weeks = r.scanned.coldWeeks ?? [];
60
+ if (weeks.length) {
61
+ a.chart = {
62
+ title: 'Tokens rebuilt by cold returns, per week',
63
+ bars: weeks.map((x, i) => ({ label: i === weeks.length - 1 ? 'Last 7 days' : `Week of ${new Date(x.from).toLocaleDateString('en-US', { month: 'short', day: 'numeric' })}`, value: x.tokens })),
64
+ note: `Cold returns a week: ${weeks.map((x) => x.count).join(' · ')}. Goal: a third lower.`,
65
+ };
66
+ }
67
+ out.push({ title: 'Stop paying for cold returns', idea: fix, cwd: home, plan: plan(f, a, `**Do:** ${fix}`), advice: a });
68
+ }
69
+ else if (f.rule === 'C2') {
70
+ const a = { key: 'C2', rule: 'C2', lane: 'habit', basis: f.basis, ...(f.tokens ? { tokens: f.tokens } : {}), check: 'Mid-session rebuilds for two weeks after you start. It worked if there are none.', saw: `${k(f.tokens ?? 0)} tokens rewritten mid-session`, doing: 'Load tools at the start, or give that work its own session', checkShort: 'No mid-session rebuilds for two weeks' };
71
+ out.push({ title: 'Keep the cache through a session', idea: f.fix, cwd: home, plan: plan(f, a, `**Do:** ${f.fix}`), advice: a });
72
+ }
73
+ else if (f.rule === 'S3') {
74
+ const start = r.scanned.startTokens;
75
+ for (const p of f.targets?.plugins ?? []) {
76
+ const name = p.id.split('@')[0];
77
+ const changes = [{ file: settings, key: ['enabledPlugins', p.id], from: true, to: false }];
78
+ const copies = (p.keep ?? []).map((x) => ({ from: x.dir, to: join(opts.skillsDir ?? join(home, '.claude', 'skills'), x.name) }));
79
+ const kept = (p.keep ?? []).map((x) => x.name);
80
+ const a = {
81
+ key: `S3:plugin:${p.id}`,
82
+ rule: 'S3',
83
+ lane: 'settings',
84
+ basis: 'estimated',
85
+ tokens: p.tokens * r.scanned.sessions,
86
+ changes,
87
+ baseline: { perStart: p.tokens },
88
+ ...(copies.length ? { copies } : {}),
89
+ saw: `${p.skills} unused skills load every session (~${k(p.tokens)} tokens)`,
90
+ doing: kept.length ? `Copy ${kept.join(' and ')} to your skills, turn ${name} off. Undo restores it` : `Turn ${name} off. Undo restores it`,
91
+ checkShort: `New sessions start ~${k(p.tokens)} tokens smaller`,
92
+ ...(start ? { chart: { title: 'What a session start costs, in tokens', bars: [{ label: 'Now', value: start }, { label: 'After', value: Math.max(0, start - p.tokens), highlight: true }], note: `${Math.round((p.tokens / start) * 100) || '<1'}% off every session start, ${r.scanned.sessions} sessions a month.` } } : {}),
93
+ check: `It worked if sessions start ~${k(p.tokens)} tokens smaller${start ? ` (now ~${k(start)})` : ''}${kept.length ? ` and ${kept.join(' and ')} still work${kept.length === 1 ? 's' : ''}` : ''}.`,
94
+ };
95
+ const say = {
96
+ ...f,
97
+ say: kept.length
98
+ ? `You used ${kept.length} of ${p.skills + kept.length} ${name} skills (${kept.join(', ')}) in ${r.scanned.sessions} sessions. The other ${p.skills} add ~${k(p.tokens)} tokens every session start.`
99
+ : `None of the ${p.skills} ${name} skills used in ${r.scanned.sessions} sessions: ~${k(p.tokens)} tokens every session start.`,
100
+ notProve: kept.length ? `${f.notProve} Your copies won't get the plugin's updates (Undo brings them back).` : f.notProve,
101
+ };
102
+ const what = [
103
+ copies.length ? `**First, keep the ones you use:** ${copies.map((c) => `copy \`${tilde(c.from)}\` to \`${tilde(c.to)}\``).join('; ')}. If a folder is already there, nothing is applied.` : '',
104
+ settingsWhat(changes),
105
+ ].filter(Boolean).join('\n\n');
106
+ out.push({
107
+ title: kept.length ? `Turn off ${name}, keep ${kept.join(' and ')}` : `Turn off ${name} (${p.skills} unused skills)`,
108
+ idea: `~${k(p.tokens)} tokens off every session start.`,
109
+ cwd: home,
110
+ plan: plan(say, a, what),
111
+ advice: a,
112
+ });
113
+ }
114
+ const synced = f.targets?.synced ?? [];
115
+ if (synced.length) {
116
+ const a = { key: 'S3:synced', rule: 'S3', lane: 'manual', basis: 'estimated', baseline: { names: synced }, check: 'It worked if these no longer load.', saw: `${synced.length} skills synced from claude.ai, never used`, doing: 'Turn them off in claude.ai settings, then press "I\'ve done it"', checkShort: 'They no longer load' };
117
+ const what = `**Do (only you can, in claude.ai settings):** turn off the ones you don't use: ${synced.join(', ')}. Then press "I've done it".`;
118
+ out.push({ title: `Turn off ${synced.length} unused synced skills`, idea: `In claude.ai settings: ${synced.slice(0, 5).join(', ')}${synced.length > 5 ? ', …' : ''}`, cwd: home, plan: plan({ ...f, say: `${synced.length} skills synced from claude.ai, unused in ${r.scanned.sessions} sessions.` }, a, what), advice: a });
119
+ }
120
+ const yours = f.targets?.yours ?? [];
121
+ if (yours.length) {
122
+ const a = { key: 'S3:yours', rule: 'S3', lane: 'manual', basis: 'estimated', baseline: { names: yours.map((y) => y.name) }, check: 'It worked if these no longer load.', saw: `${yours.length} of your own skills, never used`, doing: 'Move them out of ~/.claude/skills', checkShort: 'They no longer load' };
123
+ const what = `**Do:** move these out of \`~/.claude/skills\` (\`_archived\` inside still loads): ${yours.map((y) => y.name).join(', ')}.`;
124
+ out.push({ title: `Archive ${yours.length} unused skills of yours`, idea: yours.slice(0, 5).map((y) => y.name).join(', ') + (yours.length > 5 ? ', …' : ''), cwd: home, plan: plan(f, a, what), advice: a });
125
+ }
126
+ }
127
+ else if (f.rule === 'S2') {
128
+ const file = f.say.match(/^(\S+CLAUDE\.md)/)?.[1]?.replace(/^~/, home) ?? '';
129
+ const repo = file && basename(file) === 'CLAUDE.md' ? gitRoot(join(file, '..')) : null;
130
+ let size;
131
+ try {
132
+ const text = readFileSync(file, 'utf8');
133
+ size = { lines: text.split('\n').length, tokens: Math.ceil(text.length / 4) };
134
+ }
135
+ catch { }
136
+ const a = { key: `S2:${file}`, rule: 'S2', lane: repo ? 'work' : 'manual', basis: f.basis, ...(f.tokens ? { tokens: f.tokens } : {}), ...(size ? { baseline: size } : {}), check: 'It worked if it is under 200 lines and ~2k tokens, with no rule lost.', saw: `${size ? `${size.lines} lines (~${k(size.tokens)} tokens)` : 'A long file'}, loaded every session there`, doing: 'Keep rules and key paths; move workflows into skills', checkShort: 'Under 200 lines and ~2k tokens' };
137
+ if (repo)
138
+ out.push({ title: `Shorten ${tilde(file)}`, idea: `${f.fix} File: ${file}.`, cwd: repo, plan: null, advice: a });
139
+ else
140
+ out.push({ title: `Shorten ${tilde(file)}`, idea: f.fix, cwd: home, plan: plan(f, a, `**Do:** ${f.fix}`), advice: a });
141
+ }
142
+ else if (f.rule === 'S4' || f.rule === 'S5') {
143
+ const a = { key: `${f.rule}:${f.say.slice(0, 80)}`, rule: f.rule, lane: 'manual', basis: f.basis, check: 'It worked if detect no longer finds it.', saw: f.say.split(':')[0], doing: f.fix.replace(/\.$/, ''), checkShort: 'detect no longer finds it' };
144
+ out.push({ title: f.title, idea: f.fix, cwd: home, plan: plan(f, a, `**Do:** ${f.fix}`), advice: a });
145
+ }
146
+ }
147
+ return out;
148
+ }
149
+ /** Keys you dropped (not ones that expired unseen): those never come back. */
150
+ function droppedKeys() {
151
+ const path = homePath('archive.jsonl');
152
+ const keys = new Set();
153
+ if (!existsSync(path))
154
+ return keys;
155
+ for (const line of readFileSync(path, 'utf8').split('\n')) {
156
+ try {
157
+ const c = JSON.parse(line);
158
+ if (c.advice?.key && !c.expired)
159
+ keys.add(c.advice.key);
160
+ }
161
+ catch { }
162
+ }
163
+ return keys;
164
+ }
165
+ /** Add new advice as suggested cards, refresh the evidence on ones still suggested, skip ones you dealt with. */
166
+ export function upsertAdvice(board, drafts, now) {
167
+ const dropped = droppedKeys();
168
+ const added = [];
169
+ const updated = [];
170
+ let skipped = 0;
171
+ for (const d of drafts) {
172
+ const had = board.cards.find((c) => c.advice?.key === d.advice.key);
173
+ if (had) {
174
+ if (had.column === 'suggested') {
175
+ had.title = d.title;
176
+ had.idea = d.idea;
177
+ if (d.plan)
178
+ had.blueprint = d.plan;
179
+ had.advice = { ...d.advice };
180
+ had.updatedAt = now.toISOString();
181
+ updated.push(had);
182
+ }
183
+ else
184
+ skipped++;
185
+ continue;
186
+ }
187
+ if (dropped.has(d.advice.key)) {
188
+ skipped++;
189
+ continue;
190
+ }
191
+ const c = addCard(board, d.idea, d.cwd, now, 'suggested', d.advice.lane === 'work' ? null : 'advice');
192
+ c.title = d.title;
193
+ c.blueprint = d.plan;
194
+ c.source = 'detect';
195
+ c.why = `chompyy detect, rule ${d.advice.rule}${d.advice.tokens ? `: ${d.advice.basis === 'estimated' ? '~' : ''}${k(d.advice.tokens)} tokens` : ''}`;
196
+ c.advice = { ...d.advice };
197
+ added.push(c);
198
+ }
199
+ return { added, updated, skipped };
200
+ }
201
+ export function runAdvise(board, now, r = detect({ now })) {
202
+ return upsertAdvice(board, adviceFrom(r, { nudgeOn: nudgeInstalled() }), now);
203
+ }
204
+ // ---------- approving, applying, undoing ----------
205
+ /** What approving an advice card does (the board already checked it's suggested or later). */
206
+ export function approveAdvice(c, now) {
207
+ const a = c.advice;
208
+ const at = now.toISOString();
209
+ c.updatedAt = at;
210
+ c.approvedAt = at;
211
+ if (a.lane === 'settings') {
212
+ c.column = 'approved';
213
+ a.state = 'waiting';
214
+ a.note = 'Applies once no Claude Code session has run for 10 minutes.';
215
+ return `✅ #${c.id} approved. Applies once no Claude Code session has run for 10 minutes.`;
216
+ }
217
+ c.column = 'done';
218
+ a.since = at;
219
+ a.state = a.lane === 'habit' ? 'trying' : 'done';
220
+ return a.lane === 'habit' ? `✅ #${c.id}: trying it from today. ${a.check}` : `✅ #${c.id} done. ${a.check}`;
221
+ }
222
+ /** When a Claude Code session last wrote its transcript (ms), so settings never change under an open conversation. */
223
+ export function lastSessionActivity(root = projectsDir()) {
224
+ let last = 0;
225
+ try {
226
+ for (const folder of readdirSync(root)) {
227
+ if (isAutomated(folder))
228
+ continue;
229
+ try {
230
+ for (const f of readdirSync(join(root, folder))) {
231
+ if (f.endsWith('.jsonl'))
232
+ last = Math.max(last, statSync(join(root, folder, f)).mtimeMs);
233
+ }
234
+ }
235
+ catch { }
236
+ }
237
+ }
238
+ catch { }
239
+ return last;
240
+ }
241
+ function getAt(obj, key) {
242
+ let cur = obj;
243
+ for (const p of key)
244
+ cur = cur && typeof cur === 'object' ? cur[p] : undefined;
245
+ return cur;
246
+ }
247
+ function setAt(obj, key, value) {
248
+ let cur = obj;
249
+ for (const p of key.slice(0, -1)) {
250
+ if (!cur[p] || typeof cur[p] !== 'object')
251
+ cur[p] = {};
252
+ cur = cur[p];
253
+ }
254
+ if (value === undefined)
255
+ delete cur[key.at(-1)];
256
+ else
257
+ cur[key.at(-1)] = value;
258
+ }
259
+ const same = (a, b) => JSON.stringify(a) === JSON.stringify(b);
260
+ /** Write `changes` (or undo them): every value must still be what we expect, or nothing is written. */
261
+ function writeChanges(changes, undo, backupTag) {
262
+ const files = [...new Set(changes.map((c) => c.file))];
263
+ const backups = [];
264
+ const edited = new Map();
265
+ for (const file of files) {
266
+ let json = {};
267
+ if (existsSync(file)) {
268
+ try {
269
+ json = JSON.parse(readFileSync(file, 'utf8'));
270
+ }
271
+ catch {
272
+ throw new Error(`${tilde(file)} isn't valid JSON, so Chompyy left it alone.`);
273
+ }
274
+ }
275
+ for (const c of changes.filter((x) => x.file === file)) {
276
+ const now = getAt(json, c.key);
277
+ const expect = undo ? c.to : c.from;
278
+ const target = undo ? c.from : c.to;
279
+ if (same(now, target))
280
+ continue;
281
+ if (!same(now, expect))
282
+ throw new Error(`${c.key.join('.')} in ${tilde(file)} is ${JSON.stringify(now ?? '(not set)')} now, not ${JSON.stringify(expect ?? '(not set)')}: it changed since, so Chompyy left it alone.`);
283
+ setAt(json, c.key, target);
284
+ }
285
+ edited.set(file, json);
286
+ }
287
+ for (const [file, json] of edited) {
288
+ if (existsSync(file)) {
289
+ const backup = homePath('backups', `${backupTag}-${basename(file)}`);
290
+ copyFileSync(file, backup);
291
+ backups.push(backup);
292
+ }
293
+ writeFileSync(file, JSON.stringify(json, null, 2) + '\n');
294
+ }
295
+ return backups;
296
+ }
297
+ /** Apply approved settings advice, if no session has been active for 10 minutes. Returns what happened. */
298
+ export function applyDue(board, now, lastActivity = lastSessionActivity()) {
299
+ const due = board.cards.filter((c) => c.advice?.lane === 'settings' && c.column === 'approved' && c.advice.state === 'waiting');
300
+ if (!due.length)
301
+ return [];
302
+ const idle = now.getTime() - lastActivity;
303
+ if (idle < IDLE_BEFORE_APPLY_MS) {
304
+ const mins = Math.ceil((IDLE_BEFORE_APPLY_MS - idle) / 60_000);
305
+ for (const c of due)
306
+ c.advice.note = `Waiting: a session ran ${Math.floor(idle / 60_000)} min ago. Retries in ~${mins} min.`;
307
+ return due.map((c) => `#${c.id} waits: a Claude Code session is active.`);
308
+ }
309
+ return due.map((c) => {
310
+ const a = c.advice;
311
+ c.updatedAt = now.toISOString();
312
+ try {
313
+ const clash = (a.copies ?? []).find((x) => existsSync(x.to));
314
+ if (clash)
315
+ throw new Error(`${tilde(clash.to)} already exists, so Chompyy changed nothing. Move it away and approve again, or drop the card.`);
316
+ const missing = (a.copies ?? []).find((x) => !existsSync(x.from));
317
+ if (missing)
318
+ throw new Error(`${tilde(missing.from)} is gone (the plugin was updated?), so Chompyy changed nothing. Run chompyy advise again.`);
319
+ for (const x of a.copies ?? [])
320
+ cpSync(x.from, x.to, { recursive: true });
321
+ try {
322
+ a.backups = writeChanges(a.changes ?? [], false, `card-${c.id}-${now.getTime()}`);
323
+ }
324
+ catch (e) {
325
+ for (const x of a.copies ?? [])
326
+ rmSync(x.to, { recursive: true, force: true });
327
+ throw e;
328
+ }
329
+ a.state = 'applied';
330
+ a.since = now.toISOString();
331
+ a.note = 'Applied. New sessions pick it up.';
332
+ c.column = 'done';
333
+ return `#${c.id} applied: ${c.title}`;
334
+ }
335
+ catch (e) {
336
+ a.state = 'failed';
337
+ a.note = e.message;
338
+ c.column = 'done';
339
+ return `#${c.id} not applied: ${a.note}`;
340
+ }
341
+ });
342
+ }
343
+ /** Undo an applied settings card (only if nothing changed the values since), or stop trying a habit. */
344
+ export function undoAdvice(c, now) {
345
+ const a = c.advice;
346
+ c.updatedAt = now.toISOString();
347
+ // Undone: there is nothing left to measure.
348
+ delete a.result;
349
+ if (a.lane === 'settings' && a.state === 'applied') {
350
+ a.backups = [...(a.backups ?? []), ...writeChanges(a.changes ?? [], true, `card-${c.id}-undo-${now.getTime()}`)];
351
+ // The plugin is back on, so the copies would load twice: move them into Chompyy's backups (in case you edited them).
352
+ for (const x of a.copies ?? []) {
353
+ if (!existsSync(x.to))
354
+ continue;
355
+ const kept = homePath('backups', `card-${c.id}-undo-${now.getTime()}-${basename(x.to)}`);
356
+ renameSync(x.to, kept);
357
+ a.backups.push(kept);
358
+ }
359
+ a.state = 'undone';
360
+ a.note = 'Put back. New sessions pick it up.';
361
+ return `↩️ #${c.id} undone: old settings back.`;
362
+ }
363
+ if (a.lane === 'settings' && a.state === 'waiting') {
364
+ a.state = 'undone';
365
+ a.note = 'Cancelled before it was applied.';
366
+ c.column = 'done';
367
+ return `↩️ #${c.id} cancelled: nothing changed.`;
368
+ }
369
+ a.state = 'undone';
370
+ a.note = 'You stopped this one.';
371
+ return `↩️ #${c.id} stopped.`;
372
+ }
373
+ export function adviseText(res) {
374
+ const lines = [];
375
+ if (!res.added.length && !res.updated.length)
376
+ return `Nothing new to suggest${res.skipped ? ` (${res.skipped} you already dealt with)` : ''}.`;
377
+ lines.push('Approve or drop on the board, or: chompyy approve <id> / chompyy drop <id>', '');
378
+ if (res.added.length)
379
+ lines.push(`${res.added.length} new:`, ...res.added.slice(0, 5).map((c) => ` #${c.id} ${c.title}`), ...(res.added.length > 5 ? [` …and ${res.added.length - 5} more on the board`] : []));
380
+ if (res.updated.length)
381
+ lines.push(`${res.updated.length} updated with fresh numbers.`);
382
+ return lines.join('\n');
383
+ }
package/dist/away.js CHANGED
@@ -2,6 +2,7 @@
2
2
  import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
3
3
  import { join } from 'node:path';
4
4
  import { awayQueue, ensureCardDir, loadBoard, recoverRunning, updateBoard, getCard } from './board.js';
5
+ import { continuationPrompt } from './blueprint.js';
5
6
  import { formatDuration } from './duration.js';
6
7
  import { budgetGate } from './gate.js';
7
8
  import { homePath } from './home.js';
@@ -109,7 +110,9 @@ Original idea: ${card.idea}
109
110
  # Blueprint (agreed scope)
110
111
 
111
112
  ${card.blueprint ?? ''}
112
- ${card.answers?.length ? `
113
+ ${card.cycles?.length ? `
114
+ ${continuationPrompt(card)}
115
+ ` : ''}${card.answers?.length ? `
113
116
  # Your earlier questions have been answered
114
117
 
115
118
  The previous run left QUESTIONS.md. The user's answers:
package/dist/blueprint.js CHANGED
@@ -51,6 +51,51 @@ can make, say so in Out of scope and plan to write that question to QUESTIONS.md
51
51
  Working directory: ${card.cwd}
52
52
  Idea: ${card.idea}`;
53
53
  }
54
+ /** Longest earlier-cycle summary put in a prompt, so a long research write-up doesn't eat the run's context. */
55
+ export const CYCLE_SUMMARY_MAX = 3000;
56
+ function whereWorkIs(y) {
57
+ if (y.outcome === 'kept')
58
+ return 'its work was kept, so it is already in the code you start from';
59
+ if (y.outcome === 'undone')
60
+ return 'its work was thrown away (undone), so it is NOT in the code you start from';
61
+ return 'its work may not be in the code you start from';
62
+ }
63
+ /**
64
+ * The part of the task prompt for a continued card (`chompyy continue`): what the earlier cycles did, and the
65
+ * user's note on what is still missing. Empty for a card on its first cycle.
66
+ */
67
+ export function continuationPrompt(card) {
68
+ const cycles = card.cycles ?? [];
69
+ if (!cycles.length)
70
+ return '';
71
+ const last = cycles[cycles.length - 1];
72
+ const earlier = cycles.map((y, i) => {
73
+ const summary = y.summary.length > CYCLE_SUMMARY_MAX ? y.summary.slice(0, CYCLE_SUMMARY_MAX).trimEnd() + ' …(cut)' : y.summary;
74
+ return `## Cycle ${i + 1} (${y.status}; ${whereWorkIs(y)})
75
+
76
+ Files it changed: ${y.files.length ? y.files.join(', ') : 'none (no code change)'}
77
+
78
+ What the agent said it did:
79
+ ${summary || '(nothing recorded)'}${y.note && y !== last ? `
80
+
81
+ What the user said was still missing then: ${y.note}` : ''}`;
82
+ });
83
+ return `# This is cycle ${cycles.length + 1}: a continuation
84
+
85
+ This card already ran ${cycles.length === 1 ? 'once' : `${cycles.length} times`}. The user read the result and decided it did only part of
86
+ the job, so they sent it back for another cycle. Below is what was already done. Don't redo it: build on it.
87
+ If an earlier cycle only researched or planned, use what it found and now make the change itself.
88
+
89
+ ${earlier.join('\n\n')}
90
+
91
+ # What is still missing (the user's note)
92
+
93
+ ${last.note || 'The user did not say. Compare the original idea and the blueprint with what was already done, and do what is still missing.'}
94
+
95
+ This cycle's scope is the original idea and the blueprint's goal, finished as the note asks. Where the note asks
96
+ for more than the blueprint's Scope (for example code changes after a research-only cycle), follow the note.
97
+ The blueprint's Out of scope and the rules above still hold: nothing outward.`;
98
+ }
54
99
  /** Keep a copy of the card's blueprint in its folder (`<store>/<workspace>/<id>/blueprint.md`). Returns the path. */
55
100
  export function writeBlueprintFile(card, text) {
56
101
  const path = join(ensureCardDir(card), 'blueprint.md');
package/dist/board.js CHANGED
@@ -1,4 +1,3 @@
1
- // The board (spec §5.3): cards in columns, stored in ~/.chompyy/board.json.
2
1
  import { mkdirSync } from 'node:fs';
3
2
  import { formatTokens } from './tokens.js';
4
3
  import { join } from 'node:path';
@@ -103,6 +102,54 @@ export function moveCard(board, id, to, now) {
103
102
  card.approvedAt = card.updatedAt;
104
103
  return card;
105
104
  }
105
+ /** Which cycle the card is on: 1 for a card that was never continued. */
106
+ export function cycleOf(card) {
107
+ return (card.cycles?.length ?? 0) + 1;
108
+ }
109
+ /**
110
+ * Send a finished card back for another cycle: it only did part of the job (say it only researched). The run
111
+ * that just finished is saved as a Cycle, with its summary and files, and the card goes back to approved with
112
+ * its blueprint, so the next away run picks it up and its prompt says what was done and what is missing.
113
+ * `prior` overrides the saved summary and files (the CLI passes the full output from the log).
114
+ */
115
+ export function continueCard(board, id, note, now, prior = {}) {
116
+ const card = getCard(board, id);
117
+ if (card.column !== 'done') {
118
+ const hint = card.column === 'review' ? ' Keep or undo it first.' : '';
119
+ throw new Error(`Card #${card.id} is in ${card.column}; only finished cards (done) can be continued.${hint}`);
120
+ }
121
+ const run = card.run;
122
+ if (!run)
123
+ throw new Error(`Card #${card.id} never ran, so there is nothing to continue from.`);
124
+ if (!card.blueprint?.trim())
125
+ throw new Error(`Card #${card.id} has no blueprint. Run \`chompyy blueprint ${card.id}\` first.`);
126
+ const at = now.toISOString();
127
+ const cycle = {
128
+ at,
129
+ note: note.trim(),
130
+ status: run.status,
131
+ ...(card.outcome ? { outcome: card.outcome } : {}),
132
+ summary: (prior.summary ?? run.summary).trim(),
133
+ files: prior.files ?? run.files ?? [],
134
+ ...(run.branch ? { branch: run.branch } : {}),
135
+ ...(run.checks ? { checks: run.checks } : {}),
136
+ ...(card.rating ? { rating: card.rating } : {}),
137
+ ...(card.answers?.length ? { answers: card.answers } : {}),
138
+ };
139
+ card.cycles = [...(card.cycles ?? []), cycle];
140
+ card.column = 'approved';
141
+ card.approvedAt = at;
142
+ card.updatedAt = at;
143
+ // The new cycle starts clean: these belonged to the run that just ended (and are kept in the Cycle).
144
+ delete card.run;
145
+ delete card.outcome;
146
+ delete card.rating;
147
+ delete card.answers;
148
+ delete card.fiveStarOptions;
149
+ delete card.refresh;
150
+ delete card.keepWhenRefreshed;
151
+ return card;
152
+ }
106
153
  /** Remove a card from the board; it is kept in archive.jsonl in case you want it back. */
107
154
  export function dropCard(board, id, now) {
108
155
  const card = getCard(board, id);
@@ -214,7 +261,8 @@ export function recoverRunning(board, now, where = () => ({ dir: '' }), why = 'T
214
261
  return stuck.map((c) => c.id);
215
262
  }
216
263
  export function awayQueue(board) {
217
- return cardsIn(board, 'approved').sort((a, b) => (a.approvedAt ?? '').localeCompare(b.approvedAt ?? ''));
264
+ // Advice cards wait for their own lane (settings are applied by Chompyy, habits by you); only work-lane advice runs.
265
+ return cardsIn(board, 'approved').filter((c) => !c.advice || c.advice.lane === 'work').sort((a, b) => (a.approvedAt ?? '').localeCompare(b.approvedAt ?? ''));
218
266
  }
219
267
  function shortPath(p) {
220
268
  const home = process.env.HOME;
@@ -225,6 +273,8 @@ function cardLine(c) {
225
273
  if (c.column === 'later' || c.column === 'suggested') {
226
274
  marks.push(c.blueprint ? 'blueprint ✓' : c.blueprintError ? 'blueprint failed' : c.blueprintWaiting ? 'waiting for quota' : 'no blueprint');
227
275
  }
276
+ if (c.cycles?.length)
277
+ marks.push(`cycle ${cycleOf(c)}`);
228
278
  if (c.run)
229
279
  marks.push(c.run.status);
230
280
  if (c.rating)
@@ -267,6 +317,15 @@ export function formatCard(c) {
267
317
  if (c.idea !== c.title)
268
318
  lines.push('', c.idea);
269
319
  lines.push('', c.blueprint ?? (c.blueprintError ? `(blueprint failed: ${c.blueprintError})` : c.blueprintWaiting ? `(no blueprint yet: ${c.blueprintWaiting})` : '(no blueprint yet)'));
320
+ if (c.cycles?.length) {
321
+ lines.push('', `cycle ${cycleOf(c)}: continues ${c.cycles.length} earlier cycle${c.cycles.length === 1 ? '' : 's'}`);
322
+ c.cycles.forEach((y, i) => {
323
+ const files = y.files.length ? `${y.files.length} file${y.files.length === 1 ? '' : 's'}` : 'no files changed';
324
+ lines.push(` cycle ${i + 1}: ${y.status}${y.outcome ? ` · ${y.outcome}` : ''} · ${files}`);
325
+ if (y.note)
326
+ lines.push(` sent back: ${y.note}`);
327
+ });
328
+ }
270
329
  if (c.run) {
271
330
  lines.push('', `last run: ${c.run.status} · ${c.run.workdir}${c.run.branch ? ` · branch ${c.run.branch}` : ''}`);
272
331
  if (c.run.tokens)