chompyy 0.3.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
@@ -1,12 +1,16 @@
1
1
  #!/usr/bin/env node
2
2
  // chompyy: park ideas, blueprint them, run approved cards while you're away.
3
- import { spawn } from 'node:child_process';
4
- import { existsSync, readFileSync } from 'node:fs';
5
- import { join, relative } from 'node:path';
3
+ import { execFileSync, spawn } from 'node:child_process';
4
+ import { backfillTokens, median } from './tokenstore.js';
5
+ import { compact, formatTokens, totalTokens } from './tokens.js';
6
+ import { closeSync, existsSync, openSync, readFileSync } from 'node:fs';
6
7
  import { parseArgs } from 'node:util';
7
- import { away, cacheEnv, runCard } from './away.js';
8
- import { draftBlueprint, draftFiveStarOptions, GENERIC_FIVE_STAR } from './blueprint.js';
9
- import { addCard, awayQueue, COLUMNS, dropCard, expireSuggested, formatBoard, formatCard, getCard, loadBoard, moveCard, recoverRunning, updateBoard } from './board.js';
8
+ import { away, runCard } from './away.js';
9
+ import { formatPreflight, loadProfile, preflight, saveProfile } from './preflight.js';
10
+ import { verifyCard } from './verifycard.js';
11
+ import { parsePermission, recordNeeds } from './permissions.js';
12
+ import { draftAllPlan, draftBlueprint, draftFiveStarOptions, draftTitle, GENERIC_FIVE_STAR, isUsageLimit, writeBlueprintFile } from './blueprint.js';
13
+ import { addCard, awayQueue, claimDrafts, COLUMNS, dropCard, expireSuggested, formatBoard, formatCard, getCard, loadBoard, moveCard, noteDraftFailure, quotaWaitReason, recoverRunning, titleFrom, updateBoard } from './board.js';
10
14
  import { loadConfig, setConfig } from './config.js';
11
15
  import { formatDuration, parseDuration } from './duration.js';
12
16
  import { budgetGate } from './gate.js';
@@ -16,10 +20,9 @@ import { loadSamples } from './pacing.js';
16
20
  import { cardsSince, formatReport, lastReportAt, markReported, morningLine, rateCard, readTaste } from './report.js';
17
21
  import { changedFiles, diffCard, keepCard, overlaps, questionsOf, undoCard } from './review.js';
18
22
  import { CappedText, ClaudeRunner, claudeAvailable } from './runner.js';
19
- import { commitLeftovers, gitRoot, planWorkspace, prepareWorkspace } from './workspace.js';
20
- import { verifyRun } from './verify.js';
21
- import { answerCard, appState, cardView, editBlueprint, recordCliLocation } from './appstate.js';
22
- import { refreshLiveQuota } from './livequota.js';
23
+ import { branchOf, commitLeftovers, gitRoot, planWorkspace, prepareWorkspace } from './workspace.js';
24
+ import { answerCard, appState, cardView, currentBranch, editBlueprint, editIdea, recordCliLocation } from './appstate.js';
25
+ import { keychainAllowed, loadLiveState, refreshLiveQuota } from './livequota.js';
23
26
  import { recentProjects } from './projects.js';
24
27
  import { cliVersion, installApp } from './macapp.js';
25
28
  import { buildDigest, historyRetention, scanHistory } from './history.js';
@@ -28,6 +31,12 @@ import { keepHistory } from './claudesettings.js';
28
31
  import { blueprintHash, drawPicture } from './picture.js';
29
32
  import { costRange, formatCostRange, readRuns, trendLines } from './costs.js';
30
33
  import { answerPreference, distill, distillDue, formatPrefs, formatQuestion, formatWhy, getPref, loadStore, nextQuestion, readSignals, recordOutcome, retirePreference, syncTasteFile, tasteChangesSince, } from './taste.js';
34
+ import { cachedWorkspaces, dream, dreamDue, formatDream, formatWorkspaces, readLogPath, setTicked } from './dream.js';
35
+ import { byKind, compare, formatExtras, formatUsage, loadLedger, periodDays, PERIODS, prCosts, usageView } from './usage.js';
36
+ import { formatTrace, traceSession } from './trace.js';
37
+ import { homedir } from 'node:os';
38
+ import { clashOf, refreshCard, refreshGate, refreshClashing, withRefreshLock } from './refresh.js';
39
+ import { formatLive, keepAffectsLive, liveOff, liveSet, liveUpdateLocked, loadLive, startLiveUpdate } from './live.js';
31
40
  import { agentInstalled, awayRunning, bedtimeKey, decideTrigger, installAgent, loadTriggerState, markFired, noteTick, parseClock, takeAwayLock, uninstallAgent } from './triggers.js';
32
41
  const HELP = `chompyy: use the 5-hour window capacity that would reset unused
33
42
 
@@ -35,6 +44,7 @@ Quota
35
44
  chompyy statusline Claude Code statusLine command: reads JSON on stdin, saves a snapshot
36
45
  chompyy status % left, time to reset, pace, weekly used, staleness
37
46
  chompyy quota [--refresh] read live quota from Anthropic now (uses Claude Code's saved login; sends no message)
47
+ chompyy quota --allow-keychain | --no-keychain allow (or stop) reading that login from the macOS Keychain
38
48
  chompyy eat-tokens show leftover quota and cards you could choose to run (read-only)
39
49
 
40
50
  Board
@@ -43,9 +53,11 @@ Board
43
53
  chompyy board [--column c] cards by column (suggested later approved running review done)
44
54
  chompyy show <id> one card: blueprint, last run, what the agent said
45
55
  chompyy blueprint <id> (re)draft the blueprint with a cheap model [--model haiku]
56
+ --all-later draft every later card that has no blueprint yet, one at a time
46
57
  chompyy picture <id> (re)draw the card's picture: a diagram of what it will do (diagram-design skill)
47
58
  chompyy approve <id> later → approved (needs a blueprint)
48
59
  chompyy edit-blueprint <id> replace the blueprint with text from stdin
60
+ chompyy edit-idea <id> replace a later card's idea with text from stdin
49
61
  chompyy drop <id> remove a card (kept in archive.jsonl)
50
62
 
51
63
  Away
@@ -56,16 +68,25 @@ Away
56
68
  Back
57
69
  chompyy report [--all] what ran, and the one thing to do about each
58
70
  chompyy diff <id> the change it made
59
- chompyy keep <id> merge its branch into your current branch
71
+ chompyy keep <id> merge its branch into the branch it started from (and update the live app, if set)
72
+ chompyy refresh [<id>] bring cards in review up to date with main (Chompyy does this by itself after each Keep)
60
73
  chompyy undo <id> throw it away (removes its branch; yours are untouched)
61
74
  chompyy answer <id> answer the run's questions (stdin); the card goes back to approved
62
75
  chompyy redo <id> throw this attempt away and run it again from your latest code
63
76
  chompyy rate <id> <1-5> ["why"] [--to-five "change" ...] rate a result; --to-five = what would have made it a 5
64
77
  chompyy five-star <id> options for "what would have made it a 5?" (JSON)
65
78
  chompyy signals [--json] everything Chompyy has recorded from you: ratings, edits, answers
79
+ chompyy tokens [--json] exact tokens and API-value cost of each run
66
80
  chompyy trends last 7 days vs the 7 before: cost per card, keep rate, rating, blueprint edits
67
81
 
68
82
  Taste (learned from what you keep, undo, edit and rate)
83
+ chompyy trace <id> one conversation turn by turn: cost per turn, context size, what ate the tokens
84
+ chompyy plan-price <usd|auto> what your plan costs a month, for "your plan did N× its price"
85
+ chompyy usage [--period today|7d|30d|month] tokens and API-value cost of every Claude Code conversation on this Mac
86
+ chompyy dream the nightly read: learn how you like to work from your coding sessions
87
+ (--dry-run shows exactly what it would read; --since 3d to re-read)
88
+ chompyy dream workspaces the folders and apps it can read, ticked or not
89
+ chompyy dream tick|untick <folder> choose what it learns from (coding folders start ticked)
69
90
  chompyy taste show taste.md
70
91
  chompyy taste list every preference: to ask, in taste.md, candidates, declined, retired
71
92
  chompyy taste why <id> the cards, edits and quotes behind a preference
@@ -78,6 +99,7 @@ Triggers (start away runs on their own; the budget gate still decides every card
78
99
  chompyy triggers what is set, and what the last tick decided
79
100
  chompyy bedtime <23:30|off> run approved cards at bedtime (with the window that is left)
80
101
  chompyy last-hour <on|off> run approved cards in the last hour before a 5-hour reset
102
+ chompyy missed-reset <on|off> run approved cards on the first tick after a reset nothing used (default off)
81
103
  chompyy tick check the triggers once (what the LaunchAgent runs)
82
104
 
83
105
  Get to know you (cold start)
@@ -88,6 +110,8 @@ Get to know you (cold start)
88
110
 
89
111
  App
90
112
  chompyy app install (or update) the Mac app in ~/Applications and open it
113
+ chompyy live [set <repo>|update|off] for Chompyy's own developers: the app runs from ~/.chompyy/live, which follows
114
+ main and rebuilds (CLI, and the app if its code changed) after every Keep on main
91
115
  chompyy version this CLI's version
92
116
  chompyy projects [--json] recent project folders (from Claude Code history and past cards)
93
117
  chompyy state --json everything the Mac app shows, in one JSON (board, show, status also take --json)
@@ -114,16 +138,25 @@ async function blueprintCard(id, model) {
114
138
  const config = loadConfig();
115
139
  const card = getCard(loadBoard(), id);
116
140
  try {
117
- const text = await draftBlueprint(card, new ClaudeRunner(config.claudeBin), {
141
+ const runner = new ClaudeRunner(config.claudeBin);
142
+ const opts = {
118
143
  model: model ?? config.blueprintModel,
119
144
  // Run in the card's folder so the model can read the repo (read-only tools only).
120
145
  cwd: existsSync(card.cwd) ? card.cwd : chompyyHome(),
121
- });
146
+ };
147
+ const text = await draftBlueprint(card, runner, opts);
148
+ // Retitle only cards still named by the first words of the prompt: a title the model already wrote
149
+ // (cold start, or an earlier draft) is kept, so redrafting a blueprint costs no extra call.
150
+ const title = card.title === titleFrom(card.idea) ? await draftTitle(card, runner, opts) : card.title;
122
151
  updateBoard((b) => {
123
152
  const c = getCard(b, id);
124
153
  c.blueprint = text;
154
+ c.title = title;
125
155
  delete c.blueprintError;
156
+ delete c.blueprintWaiting;
157
+ delete c.blueprintWaitUntil;
126
158
  delete c.draftingAt;
159
+ writeBlueprintFile(c, text);
127
160
  c.updatedAt = new Date().toISOString();
128
161
  });
129
162
  if (config.pictures && windowActive(new Date()))
@@ -132,14 +165,15 @@ async function blueprintCard(id, model) {
132
165
  }
133
166
  catch (err) {
134
167
  const message = err instanceof Error ? err.message : String(err);
135
- updateBoard((b) => {
136
- const c = getCard(b, id);
137
- c.blueprintError = message;
138
- delete c.draftingAt;
139
- });
168
+ updateBoard((b) => noteDraftFailure(b, id, message, isUsageLimit(message), retryAfterLimit(new Date())));
140
169
  throw err;
141
170
  }
142
171
  }
172
+ /** When to retry a draft that hit the usage limit: at the 5-hour reset if known, else in 30 minutes. */
173
+ function retryAfterLimit(now) {
174
+ const five = windowView(loadSnapshot()?.fiveHour, now);
175
+ return five.known ? new Date(five.resetsAt * 1000) : new Date(now.getTime() + 30 * 60_000);
176
+ }
143
177
  /** Draw (or redraw) a card's picture with the diagram-design skill. Errors are kept on the card. */
144
178
  async function pictureCard(id, model) {
145
179
  const config = loadConfig();
@@ -178,6 +212,10 @@ function fullOutput(card) {
178
212
  function windowActive(now) {
179
213
  return windowView(loadSnapshot()?.fiveHour, now).known;
180
214
  }
215
+ /** Why a draft must wait (the running window has 0% left), or null. A draft then would only hit the limit. */
216
+ function quotaEmpty(now) {
217
+ return quotaWaitReason(windowView(loadSnapshot()?.fiveHour, now));
218
+ }
181
219
  /**
182
220
  * Draft blueprints that are waiting, but only while a window is active: drafting is a model call, and
183
221
  * with no active window it would start a new 5-hour window. Called whenever quota is fresh.
@@ -188,17 +226,13 @@ function draftPending(now) {
188
226
  updateBoard((b) => expireSuggested(b, now, days));
189
227
  if (!windowActive(now) || !claudeAvailable(loadConfig().claudeBin))
190
228
  return;
191
- const stale = now.getTime() - 3 * 60_000;
192
- const ids = updateBoard((b) => {
193
- const due = b.cards.filter((c) => (c.column === 'later' || c.column === 'suggested') && !c.blueprint && !c.blueprintError && !c.noAutoDraft && (!c.draftingAt || Date.parse(c.draftingAt) < stale));
194
- for (const c of due)
195
- c.draftingAt = now.toISOString();
196
- return due.map((c) => c.id);
197
- });
229
+ // With 0% left the cards wait (and say so) instead of failing; they stay due and draft after the reset.
230
+ const waiting = quotaEmpty(now);
231
+ const ids = updateBoard((b) => claimDrafts(b, now, waiting));
198
232
  for (const id of ids)
199
233
  blueprintInBackground(id);
200
234
  // Pictures for cards whose blueprint is ready but not drawn yet, or changed since (an edit or a redraw).
201
- if (!loadConfig().pictures)
235
+ if (!loadConfig().pictures || waiting)
202
236
  return;
203
237
  const toDraw = updateBoard((b) => {
204
238
  const due = b.cards.filter((c) => ['suggested', 'later', 'approved'].includes(c.column) &&
@@ -225,6 +259,24 @@ function blueprintInBackground(id) {
225
259
  });
226
260
  child.unref();
227
261
  }
262
+ /** The nightly read, then distil: inside an active window only (a model call would otherwise start one). */
263
+ async function dreamNow(now, opts = {}) {
264
+ const config = loadConfig();
265
+ if (opts.dryRun) {
266
+ const r = await dream(new ClaudeRunner(config.claudeBin), { model: config.dreamModel, now, dryRun: true, sinceMs: opts.sinceMs });
267
+ return `Would read ${r.sessions} session${r.sessions === 1 ? '' : 's'} (~${Math.round(r.readTokens / 1000)}k tokens) in ${r.chunks} call${r.chunks === 1 ? '' : 's'} with ${config.dreamModel}. Exactly what it would read: ${readLogPath(now)}`;
268
+ }
269
+ if (!opts.force && !windowActive(now))
270
+ return 'No active 5-hour window: reading now would start one. It runs after your next away, or add --force.';
271
+ if (!claudeAvailable(config.claudeBin))
272
+ return `Can't find Claude Code (\`${config.claudeBin}\`).`;
273
+ const r = await dream(new ClaudeRunner(config.claudeBin), { model: config.dreamModel, now, sinceMs: opts.sinceMs });
274
+ const lines = [formatDream(r, config.dreamModel)];
275
+ if (r.signals)
276
+ lines.push(`Taste: ${await distillNow(new Date(), true)}`);
277
+ lines.push(`What it read: ${readLogPath(now)}`);
278
+ return lines.join('\n');
279
+ }
228
280
  /** Distil taste from new signals, but only inside an active window (a model call would otherwise start one). */
229
281
  async function distillNow(now, force = false) {
230
282
  const config = loadConfig();
@@ -239,6 +291,52 @@ async function distillNow(now, force = false) {
239
291
  const parts = [`${c.added.length} new`, `${c.extended.length} with more evidence`, `${c.ready.length} ready to ask`, `${c.retired.length} retired`];
240
292
  return `Read ${r.read} new signal(s): ${parts.join(', ')}${c.dropped ? ` (${c.dropped} thrown out for weak evidence)` : ''}. See \`chompyy taste list\`.`;
241
293
  }
294
+ /** Keep a card: merge it, record it, update the live app, and bring the other cards in review up to date. */
295
+ function keepNow(id, now) {
296
+ const kept = getCard(loadBoard(), id);
297
+ console.log(keepCard(kept));
298
+ updateBoard((b) => {
299
+ const card = getCard(b, id);
300
+ card.outcome = 'kept';
301
+ card.column = 'done';
302
+ delete card.keepWhenRefreshed;
303
+ card.updatedAt = now.toISOString();
304
+ recordOutcome(card, 'kept', now);
305
+ return card;
306
+ });
307
+ // If this landed on what the app runs from, bring the app up to date by itself (live.ts).
308
+ const landedOn = kept.run?.base?.branch ?? currentBranch(kept.cwd);
309
+ if (keepAffectsLive(loadLive(), kept.cwd, landedOn)) {
310
+ startLiveUpdate();
311
+ console.log('Updating the app with it in the background: the CLI in seconds, the Mac app in 1–2 minutes if its code changed (`chompyy live` shows progress).');
312
+ }
313
+ // Main moved: cards still in review may clash with it now. Checking each one costs git time per card, so
314
+ // that happens in the background job that also brings them up to date (refresh.ts); Keep returns at once.
315
+ const waiting = loadBoard().cards.filter((c) => c.id !== id && c.column === 'review' && c.run?.branch);
316
+ if (waiting.length) {
317
+ startBackground(['refresh', '--clashing'], 'refresh.log');
318
+ console.log(`Checking ${waiting.map((c) => '#' + c.id).join(', ')} against it in the background; any that clash get brought up to date.`);
319
+ }
320
+ }
321
+ /** Run a chompyy command in the background, detached, so it outlives this process (and an app restart). */
322
+ function startBackground(args, logName) {
323
+ const out = openSync(homePath(logName), 'a');
324
+ spawn(process.execPath, [process.argv[1], ...args], { detached: true, stdio: ['ignore', out, out] }).unref();
325
+ closeSync(out);
326
+ }
327
+ function refreshDeps(config, freshQuota) {
328
+ const a = awayDeps(config, freshQuota);
329
+ return {
330
+ runner: a.runner,
331
+ config,
332
+ now: () => new Date(),
333
+ snapshot: loadSnapshot,
334
+ out: (line) => console.log(`${new Date().toISOString().slice(0, 16)} ${line}`),
335
+ ...(a.verify ? { verify: a.verify } : {}),
336
+ ...(a.repoChecks ? { repoChecks: a.repoChecks } : {}),
337
+ keep: (id) => keepNow(id, new Date()),
338
+ };
339
+ }
242
340
  /** An away run: one at a time (lock), then distil what the run taught, if anything. */
243
341
  /** What an away run (and each card's worker) needs from the real world. */
244
342
  function awayDeps(config, freshQuota) {
@@ -250,26 +348,32 @@ function awayDeps(config, freshQuota) {
250
348
  plan: planWorkspace,
251
349
  prepare: prepareWorkspace,
252
350
  commitLeftovers,
351
+ wait: (ms) => new Promise((resolve) => setTimeout(resolve, Math.max(0, ms))),
352
+ recordNeeds: (card, needs) => {
353
+ const root = gitRoot(card.cwd);
354
+ if (!root)
355
+ return;
356
+ const p = loadProfile(root) ?? { root, checks: [], updatedAt: new Date().toISOString() };
357
+ saveProfile({ ...p, needs: recordNeeds(p.needs ?? [], needs, card.id, new Date().toISOString()) });
358
+ },
359
+ repoChecks: (card) => {
360
+ const root = gitRoot(card.cwd);
361
+ const p = root ? loadProfile(root) : null;
362
+ return (p?.preflight?.results ?? []).filter((r) => r.verdict === 'ready').map((r) => ({ dir: r.check.dir, label: r.check.label }));
363
+ },
253
364
  refreshQuota: async () => {
254
365
  await freshQuota(true);
255
366
  },
256
367
  ...(config.independentCheck
257
368
  ? {
258
- verify: (ws, card) => {
369
+ verify: async (ws, card) => {
370
+ // Chompyy's own measurement: the repo's checks on the card and on the main it started from.
259
371
  const root = gitRoot(card.cwd);
260
372
  const cacheDir = homePath('cache', 'tools');
261
- // A card made in a subfolder (e.g. cli/ of a repo) is checked there, with that folder's node_modules.
262
- const sub = root ? relative(root, card.cwd) : '';
263
- return verifyRun({
264
- dir: sub && !sub.startsWith('..') ? join(ws.dir, sub) : ws.dir,
265
- repoRoot: sub && !sub.startsWith('..') ? card.cwd : root,
266
- cacheDir,
267
- env: cacheEnv(cacheDir),
268
- denyRead: config.denyReadPaths,
269
- timeoutMs: config.checkTimeoutMin * 60_000,
270
- override: root ? config.checkCommands[root] : undefined,
271
- now: () => new Date(),
272
- });
373
+ if (!root || ws.kind !== 'worktree')
374
+ return undefined;
375
+ const baseCommit = ws.base?.commit ?? execFileSync('git', ['-C', root, 'merge-base', 'HEAD', ws.branch], { encoding: 'utf8' }).trim();
376
+ return verifyCard({ root, dir: ws.dir, baseCommit, cacheDir, denyRead: config.denyReadPaths, timeoutMs: config.checkTimeoutMin * 60_000, now: () => new Date() });
273
377
  },
274
378
  }
275
379
  : {}),
@@ -312,6 +416,15 @@ async function runAway(ms, opts, now, freshQuota) {
312
416
  finally {
313
417
  release();
314
418
  }
419
+ // After the cards (they come first): the nightly read of your everyday sessions, once a day.
420
+ if (!opts.dryRun && config.dream && dreamDue(new Date())) {
421
+ try {
422
+ console.log(`Nightly read: ${await dreamNow(new Date())}`);
423
+ }
424
+ catch (err) {
425
+ console.log(`Nightly read: couldn't run (${err instanceof Error ? err.message : err})`);
426
+ }
427
+ }
315
428
  if (!opts.dryRun && config.distillAfterAway && distillDue(loadBoard(), new Date(), 0)) {
316
429
  try {
317
430
  console.log(`Taste: ${await distillNow(new Date())}`);
@@ -327,6 +440,8 @@ async function main(argv) {
327
440
  allowPositionals: true,
328
441
  options: {
329
442
  'no-blueprint': { type: 'boolean' },
443
+ 'all-later': { type: 'boolean' },
444
+ clashing: { type: 'boolean' },
330
445
  wait: { type: 'boolean' },
331
446
  'dry-run': { type: 'boolean' },
332
447
  force: { type: 'boolean' },
@@ -337,12 +452,20 @@ async function main(argv) {
337
452
  help: { type: 'boolean', short: 'h' },
338
453
  json: { type: 'boolean' },
339
454
  refresh: { type: 'boolean' },
455
+ 'allow-keychain': { type: 'boolean' },
456
+ 'no-keychain': { type: 'boolean' },
340
457
  'to-five': { type: 'string', multiple: true },
341
458
  digest: { type: 'boolean' },
342
459
  taste: { type: 'string' },
343
460
  cards: { type: 'string' },
461
+ ref: { type: 'string' },
462
+ allow: { type: 'string', multiple: true },
344
463
  timeout: { type: 'string' },
345
464
  trigger: { type: 'string' },
465
+ since: { type: 'string' },
466
+ days: { type: 'string' },
467
+ app: { type: 'boolean' },
468
+ period: { type: 'string' },
346
469
  },
347
470
  });
348
471
  const [command, ...args] = values.help ? ["help"] : positionals;
@@ -355,7 +478,8 @@ async function main(argv) {
355
478
  if (loadConfig().quotaSource !== 'api')
356
479
  return null;
357
480
  try {
358
- return await refreshLiveQuota({ force });
481
+ const config = loadConfig();
482
+ return await refreshLiveQuota({ force, allowKeychain: keychainAllowed(config), keychainOff: config.allowKeychain === false });
359
483
  }
360
484
  catch {
361
485
  return null;
@@ -384,7 +508,11 @@ async function main(argv) {
384
508
  return;
385
509
  }
386
510
  case 'quota': {
387
- const r = await freshQuota(Boolean(values.refresh));
511
+ if (values['allow-keychain'])
512
+ setConfig('allowKeychain', true);
513
+ if (values['no-keychain'])
514
+ setConfig('allowKeychain', false);
515
+ const r = await freshQuota(Boolean(values.refresh || values['allow-keychain']));
388
516
  if (r)
389
517
  console.log(r.message);
390
518
  else if (loadConfig().quotaSource !== 'api')
@@ -402,6 +530,28 @@ async function main(argv) {
402
530
  const quotaRefresh = values.refresh ? (refreshed ? { ok: refreshed.ok, message: refreshed.message } : { ok: false, message: 'Live quota reading is off (quotaSource in config.json).' }) : null;
403
531
  return json({ ...appState(loadBoard(), loadSnapshot(), loadConfig(), now), quotaRefresh });
404
532
  }
533
+ case 'live': {
534
+ const sub = args[0] ?? 'status';
535
+ if (sub === 'set') {
536
+ const live = liveSet(need(args[1], 'chompyy live set <your Chompyy checkout> [branch]'), args[2] ?? 'main');
537
+ console.log(`Live copy at ${live.dir}, following ${live.branch}. Building it now…`);
538
+ liveUpdateLocked();
539
+ return console.log(formatLive(loadLive()));
540
+ }
541
+ if (sub === 'off') {
542
+ liveOff();
543
+ return console.log('The app no longer follows the live copy; it uses whichever chompyy CLI runs next.');
544
+ }
545
+ if (sub === 'update') {
546
+ const state = liveUpdateLocked();
547
+ if (!state)
548
+ console.log('An update is already running; it will pick up the newest main when it finishes.');
549
+ if (state?.error)
550
+ process.exitCode = 1;
551
+ return;
552
+ }
553
+ return console.log(formatLive(loadLive()));
554
+ }
405
555
  case 'app': {
406
556
  console.log(`Downloading Chompyy ${cliVersion()} for Mac…`);
407
557
  const at = await installApp();
@@ -536,6 +686,15 @@ async function main(argv) {
536
686
  console.log(`✏️ #${card.id} blueprint updated.`);
537
687
  return;
538
688
  }
689
+ case 'edit-idea': {
690
+ const id = need(args[0], 'chompyy edit-idea <id> (new idea on stdin)');
691
+ const text = await readStdin();
692
+ const card = updateBoard((b) => editIdea(b, id, text, now));
693
+ console.log(`✏️ #${card.id} idea updated: ${card.title}`);
694
+ if (card.blueprint)
695
+ console.log(` Its blueprint was drafted from the old idea; redraft with: chompyy blueprint ${card.id}`);
696
+ return;
697
+ }
539
698
  case 'answer': {
540
699
  const id = need(args[0], 'chompyy answer <id> (answers on stdin)');
541
700
  const text = args.slice(1).join(' ').trim() || (await readStdin());
@@ -571,7 +730,7 @@ async function main(argv) {
571
730
  }
572
731
  case 'later': {
573
732
  const idea = need(args.join(' ').trim(), 'chompyy later "<idea>"');
574
- const card = updateBoard((b) => addCard(b, idea, process.cwd(), now));
733
+ const card = updateBoard((b) => addCard(b, idea, process.cwd(), now, 'later', branchOf(process.cwd())));
575
734
  console.log(`📥 #${card.id} parked in later: ${card.title}`);
576
735
  if (values['no-blueprint']) {
577
736
  updateBoard((b) => {
@@ -597,6 +756,14 @@ async function main(argv) {
597
756
  console.log(' the blueprint waits until your 5-hour window is active (drafting now would start a new window)');
598
757
  return;
599
758
  }
759
+ const waiting = quotaEmpty(now);
760
+ if (waiting) {
761
+ updateBoard((b) => {
762
+ getCard(b, card.id).blueprintWaiting = waiting;
763
+ });
764
+ console.log(` ${waiting}`);
765
+ return;
766
+ }
600
767
  updateBoard((b) => {
601
768
  getCard(b, card.id).draftingAt = now.toISOString();
602
769
  });
@@ -625,6 +792,23 @@ async function main(argv) {
625
792
  console.log(`used ${card.run.cost.fiveHourPct}% of the 5h window${card.run.trigger ? ` · started by the ${card.run.trigger} trigger` : ''}`);
626
793
  return;
627
794
  }
795
+ case 'tokens': {
796
+ // Exact tokens per run (tokens.ts). Runs from before 2026-11-19 are filled in from their saved stream logs.
797
+ const filled = backfillTokens();
798
+ const rows = readRuns().filter((r) => r.tokens);
799
+ if (values.json)
800
+ return json(rows.map((r) => ({ at: r.at, card: r.card, title: r.title, status: r.status, ...r.tokens })));
801
+ if (filled)
802
+ console.log(`Filled in exact tokens for ${filled} earlier run(s) from their logs.\n`);
803
+ if (!rows.length)
804
+ return console.log('No runs with exact token counts yet: they are recorded from the next away run on.');
805
+ for (const r of rows.slice(-20))
806
+ console.log(`${r.at.slice(0, 16).replace('T', ' ')} #${r.card.padEnd(4)} ${formatTokens(r.tokens)}\n ${r.title}`);
807
+ const sum = rows.reduce((a, r) => a + r.tokens.costUsd, 0);
808
+ const all = rows.reduce((a, r) => a + totalTokens(r.tokens), 0);
809
+ console.log(`\n${rows.length} run(s): ${compact(all)} tokens, $${sum.toFixed(2)} at API prices (median $${median(rows.map((r) => r.tokens.costUsd)).toFixed(2)} per run)`);
810
+ return;
811
+ }
628
812
  case 'picture': {
629
813
  const id = need(args[0], 'chompyy picture <id> [--model sonnet]');
630
814
  await freshQuota();
@@ -636,6 +820,59 @@ async function main(argv) {
636
820
  return;
637
821
  }
638
822
  case 'blueprint': {
823
+ if (values['all-later']) {
824
+ await freshQuota();
825
+ if (!claudeAvailable(loadConfig().claudeBin))
826
+ throw new Error('claude CLI not found: drafting needs it.');
827
+ // Same rule as background drafting (card #20): with 0% left, every draft would only hit the limit.
828
+ const waiting = quotaEmpty(now);
829
+ if (waiting) {
830
+ updateBoard((b) => claimDrafts(b, now, waiting)); // marks the later cards "waiting for quota"
831
+ console.log(`Nothing drafted: ${waiting}. They draft on their own once quota is back.`);
832
+ return;
833
+ }
834
+ const plan = draftAllPlan(loadBoard(), windowActive(now), now);
835
+ if (!plan.ids.length) {
836
+ console.log(plan.message);
837
+ return;
838
+ }
839
+ // Mark them all first so background drafting and the app don't start a second draft of the same card.
840
+ updateBoard((b) => {
841
+ for (const id of plan.ids)
842
+ getCard(b, id).draftingAt = new Date().toISOString();
843
+ });
844
+ const failed = [];
845
+ for (const [i, id] of plan.ids.entries()) {
846
+ updateBoard((b) => {
847
+ getCard(b, id).draftingAt = new Date().toISOString(); // fresh, so a long queue doesn't look stale
848
+ });
849
+ if (!values.quiet)
850
+ console.log(`Drafting #${id} (${i + 1} of ${plan.ids.length})…`);
851
+ try {
852
+ await blueprintCard(id, values.model); // a failure is kept on the card as blueprintError
853
+ }
854
+ catch (err) {
855
+ const message = err instanceof Error ? err.message : String(err);
856
+ if (isUsageLimit(message)) {
857
+ // Out of quota mid-way: the rest would fail the same way. They wait for the reset instead (card #20).
858
+ const left = plan.ids.slice(i + 1);
859
+ updateBoard((b) => { for (const l of left)
860
+ delete getCard(b, l).draftingAt; claimDrafts(b, new Date(), quotaEmpty(new Date()) ?? 'waiting for quota: the usage limit was hit'); });
861
+ console.log(`Drafted ${i} of ${plan.ids.length}: the usage limit was hit at #${id}. The rest draft on their own once quota is back.`);
862
+ process.exitCode = i === 0 ? 1 : 0;
863
+ return;
864
+ }
865
+ failed.push(id);
866
+ if (!values.quiet)
867
+ console.log(` #${id} failed: ${message}`);
868
+ }
869
+ }
870
+ const done = plan.ids.length - failed.length;
871
+ console.log(`Drafted ${done} of ${plan.ids.length} blueprint${plan.ids.length === 1 ? '' : 's'}${failed.length ? `; failed: ${failed.map((f) => '#' + f).join(', ')} (see each card)` : ''}.`);
872
+ if (done === 0)
873
+ process.exitCode = 1;
874
+ return;
875
+ }
639
876
  const id = need(args[0], 'chompyy blueprint <id> [--model haiku]');
640
877
  const text = await blueprintCard(id, values.model);
641
878
  if (!values.quiet)
@@ -643,8 +880,21 @@ async function main(argv) {
643
880
  return;
644
881
  }
645
882
  case 'approve': {
646
- const card = updateBoard((b) => moveCard(b, need(args[0], 'chompyy approve <id>'), 'approved', now));
647
- console.log(`✅ #${card.id} approved: ${card.title}`);
883
+ const id = need(args[0], 'chompyy approve <id> [--allow network:host] [--allow "command:swiftc *"]');
884
+ // The permission plan: what you allow here is all the run gets beyond the box's defaults (none by default).
885
+ const allow = values.allow ?? [];
886
+ const bad = allow.filter((a) => !parsePermission(a));
887
+ if (bad.length)
888
+ throw new Error(`Not a permission: ${bad.join(', ')}. Use network:<domain> or "command:<program> *".`);
889
+ const card = updateBoard((b) => {
890
+ const c = moveCard(b, id, 'approved', now);
891
+ if (allow.length)
892
+ c.permissions = [...new Set(allow)];
893
+ else
894
+ delete c.permissions;
895
+ return c;
896
+ });
897
+ console.log(`✅ #${card.id} approved: ${card.title}${card.permissions?.length ? `\n allowed: ${card.permissions.join(', ')}` : ''}`);
648
898
  for (const o of overlaps(card, loadBoard().cards)) {
649
899
  console.log(` ⚠️ #${o.id} "${o.title}" may touch the same files (${o.files.slice(0, 3).join(', ')}). Keeping both can conflict; Run again fixes that.`);
650
900
  }
@@ -655,6 +905,21 @@ async function main(argv) {
655
905
  console.log(`🗑 #${card.id} dropped: ${card.title}`);
656
906
  return;
657
907
  }
908
+ case 'preflight': {
909
+ // Run the repo's checks on clean latest main, in the away box and outside it (research/away-readiness.md).
910
+ const root = gitRoot(args[0] ?? process.cwd());
911
+ if (!root)
912
+ throw new Error('Not in a git repo. Usage: chompyy preflight [path-to-repo]');
913
+ const config = loadConfig();
914
+ console.log(`Checking ${root} on its latest main, in the away box and outside it…`);
915
+ const result = await preflight(root, { cacheDir: homePath('cache', 'tools'), denyRead: config.denyReadPaths, timeoutMs: config.checkTimeoutMin * 60_000, ...(values.ref ? { ref: values.ref } : {}) });
916
+ const before = loadProfile(root);
917
+ saveProfile({ root, checks: result.results.map((r) => r.check), updatedAt: result.at, preflight: result, ...(before?.needs ? { needs: before.needs } : {}) });
918
+ if (values.json)
919
+ return json(result);
920
+ console.log(formatPreflight(result));
921
+ return;
922
+ }
658
923
  case 'run-card': {
659
924
  // A worker started by an away run: one card in its own process, so a crash ends only this card.
660
925
  const id = need(args[0], 'chompyy run-card <id> --timeout <ms>');
@@ -677,12 +942,19 @@ async function main(argv) {
677
942
  await freshQuota();
678
943
  const config = loadConfig();
679
944
  const board = loadBoard();
945
+ // Refreshes that waited for quota (refresh.ts) go as soon as there is some again.
946
+ if (board.cards.some((c) => c.column === 'review' && c.refresh?.state === 'waiting') && !refreshGate(loadSnapshot(), now)) {
947
+ await withRefreshLock(() => refreshClashing(refreshDeps(config, freshQuota)));
948
+ }
680
949
  const d = decideTrigger(now, loadSnapshot(), config, loadTriggerState().fired, awayQueue(board).length, Boolean(awayRunning()));
681
950
  const stamp = now.toISOString().slice(0, 16);
682
951
  if (!d.fire) {
683
952
  noteTick(now, d.why);
684
953
  // Nightly consolidation: at bedtime, distil taste even when no card runs.
685
- if (config.bedtime && bedtimeKey(now, config.bedtime, config.bedtimeWindowMin) && !awayRunning() && windowActive(now) && distillDue(board, now, 12 * 3600_000)) {
954
+ if (config.bedtime && config.dream && bedtimeKey(now, config.bedtime, config.bedtimeWindowMin) && !awayRunning() && windowActive(now) && dreamDue(now)) {
955
+ console.log(`${stamp} bedtime · nightly read: ${await dreamNow(now).catch((e) => String(e))}`);
956
+ }
957
+ else if (config.bedtime && bedtimeKey(now, config.bedtime, config.bedtimeWindowMin) && !awayRunning() && windowActive(now) && distillDue(board, now, 12 * 3600_000)) {
686
958
  console.log(`${stamp} bedtime · taste: ${await distillNow(now).catch((e) => String(e))}`);
687
959
  }
688
960
  else if (values.json || process.stdout.isTTY)
@@ -700,7 +972,7 @@ async function main(argv) {
700
972
  const path = installAgent();
701
973
  const c = loadConfig();
702
974
  console.log(`Triggers on: ${path} runs \`chompyy tick\` every 5 minutes.`);
703
- console.log(` last hour before a reset: ${c.lastHourTrigger ? `on (with ≥${c.lastHourMinLeftPct}% left)` : 'off'} · bedtime: ${c.bedtime ?? 'not set (chompyy bedtime 23:30)'}`);
975
+ console.log(` last hour before a reset: ${c.lastHourTrigger ? `on (with ≥${c.lastHourMinLeftPct}% left)` : 'off'} · bedtime: ${c.bedtime ?? 'not set (chompyy bedtime 23:30)'} · missed reset: ${c.missedReset ? 'on' : 'off'}`);
704
976
  return;
705
977
  }
706
978
  if (sub === 'off')
@@ -710,10 +982,11 @@ async function main(argv) {
710
982
  const c = loadConfig();
711
983
  const st = loadTriggerState();
712
984
  if (values.json)
713
- return json({ installed: agentInstalled(), lastHour: c.lastHourTrigger, lastHourMinLeftPct: c.lastHourMinLeftPct, bedtime: c.bedtime, ...st });
985
+ return json({ installed: agentInstalled(), lastHour: c.lastHourTrigger, lastHourMinLeftPct: c.lastHourMinLeftPct, bedtime: c.bedtime, missedReset: c.missedReset, ...st });
714
986
  console.log(`LaunchAgent ${agentInstalled() ? 'on (every 5 minutes)' : 'off (turn on: chompyy triggers on)'}`);
715
987
  console.log(`last hour ${c.lastHourTrigger ? `on, with ≥${c.lastHourMinLeftPct}% of the window left` : 'off'}`);
716
988
  console.log(`bedtime ${c.bedtime ?? 'not set'}`);
989
+ console.log(`missed reset ${c.missedReset ? 'on, approved cards run on the first tick after an unused reset' : 'off'}`);
717
990
  if (st.lastTickAt)
718
991
  console.log(`last tick ${st.lastTickAt.slice(0, 16).replace('T', ' ')}: ${st.lastDecision ?? ''}`);
719
992
  return;
@@ -729,6 +1002,15 @@ async function main(argv) {
729
1002
  console.log(`Bedtime set to ${v}: approved cards run then, with the window that is left.${agentInstalled() ? '' : ' Turn triggers on with `chompyy triggers on`.'}`);
730
1003
  return;
731
1004
  }
1005
+ case 'plan-price': {
1006
+ const v = need(args[0], 'chompyy plan-price <dollars per month | auto>');
1007
+ const n = Number(v);
1008
+ if (v !== 'auto' && !(Number.isFinite(n) && n > 0))
1009
+ throw new Error('Usage: chompyy plan-price <dollars per month | auto>');
1010
+ setConfig('planPriceUsd', v === 'auto' ? null : n);
1011
+ console.log(v === 'auto' ? 'Plan price: the list price for the plan Chompyy sees.' : `Plan price: $${n} a month.`);
1012
+ return;
1013
+ }
732
1014
  case 'last-hour': {
733
1015
  const v = need(args[0], 'chompyy last-hour <on|off>');
734
1016
  if (v !== 'on' && v !== 'off')
@@ -737,6 +1019,74 @@ async function main(argv) {
737
1019
  console.log(`Last-hour trigger ${v}.${v === 'on' && !agentInstalled() ? ' Turn triggers on with `chompyy triggers on`.' : ''}`);
738
1020
  return;
739
1021
  }
1022
+ case 'missed-reset': {
1023
+ const v = need(args[0], 'chompyy missed-reset <on|off>');
1024
+ if (v !== 'on' && v !== 'off')
1025
+ throw new Error('Usage: chompyy missed-reset <on|off>');
1026
+ setConfig('missedReset', v === 'on');
1027
+ console.log(`Missed-reset trigger ${v}.${v === 'on' ? ` Only cards already approved (chompyy approve) run; the budget gate still decides.${agentInstalled() ? '' : ' Turn triggers on with `chompyy triggers on`.'}` : ''}`);
1028
+ return;
1029
+ }
1030
+ case 'trace': {
1031
+ const q = need(args[0], 'chompyy trace <conversation id> [--json] (ids: chompyy usage --json)');
1032
+ const ticked = new Set(cachedWorkspaces(now).filter((w) => w.ticked).map((w) => w.path));
1033
+ const t = traceSession(q, { showPrompts: (ws) => ticked.has(ws) });
1034
+ if (!t)
1035
+ throw new Error(q.startsWith('chompyy-card-') ? 'Away runs keep no transcript (only their recorded totals, in chompyy usage).' : `No conversation "${q}" on this Mac.`);
1036
+ if (values.json)
1037
+ return json(t);
1038
+ console.log(formatTrace(t));
1039
+ return;
1040
+ }
1041
+ case 'usage': {
1042
+ const period = (values.period ?? '');
1043
+ if (values.period && !PERIODS.includes(period))
1044
+ throw new Error(`Usage: chompyy usage [--period ${PERIODS.join('|')}] [--days 7] [--json]`);
1045
+ const days = period ? periodDays(period, now) : values.days ? Number(values.days) : 7;
1046
+ if (!Number.isInteger(days) || days < 1 || days > 400)
1047
+ throw new Error('Usage: chompyy usage [--period today|7d|30d|month] [--days 7] [--json]');
1048
+ // Titles only for workspaces the nightly read may see (your ticks); numbers count everywhere.
1049
+ const ticked = new Set(cachedWorkspaces(now).filter((w) => w.ticked).map((w) => w.path));
1050
+ const canShow = (ws) => ticked.has(ws);
1051
+ const ledger = loadLedger();
1052
+ const view = usageView(ledger, now, days, 25, canShow);
1053
+ const to = now.toISOString();
1054
+ const cmp = compare(ledger, now, { label: loadLiveState().plan ?? null, priceUsd: loadConfig().planPriceUsd });
1055
+ const kinds = byKind(ledger, view.from, to);
1056
+ const prs = prCosts(ledger, view.from, to, canShow);
1057
+ // For the app: 12 weeks of days (the calendar), this week (the menu bar), the chosen period with kinds of
1058
+ // work and pull requests, and the comparisons, in one call.
1059
+ if (values.json && values.app) {
1060
+ const long = usageView(ledger, now, 84, 0, canShow);
1061
+ const week = usageView(ledger, now, 7, 10, canShow);
1062
+ 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 });
1063
+ }
1064
+ if (values.json)
1065
+ return json({ ...view, byKind: kinds, prs, compare: cmp });
1066
+ console.log(formatUsage(view, homedir()));
1067
+ console.log(formatExtras(kinds, prs, cmp));
1068
+ return;
1069
+ }
1070
+ case 'dream': {
1071
+ const sub = args[0];
1072
+ if (sub === 'workspaces') {
1073
+ if (values.json)
1074
+ return json(cachedWorkspaces(now, 0));
1075
+ return console.log(formatWorkspaces(cachedWorkspaces(now, 0)));
1076
+ }
1077
+ if (sub === 'tick' || sub === 'untick') {
1078
+ const w = setTicked(need(args.slice(1).join(' ') || undefined, `chompyy dream ${sub} <folder>`), sub === 'tick', now);
1079
+ return console.log(`${w.ticked ? 'Ticked' : 'Unticked'} ${w.path}: the nightly read ${w.ticked ? 'will learn from' : "won't read"} its sessions.`);
1080
+ }
1081
+ if (sub === 'on' || sub === 'off') {
1082
+ setConfig('dream', sub === 'on');
1083
+ return console.log(`Nightly read ${sub}.`);
1084
+ }
1085
+ if (sub)
1086
+ throw new Error('Usage: chompyy dream [workspaces | tick <folder> | untick <folder> | on | off] [--dry-run] [--force] [--since 7d]');
1087
+ console.log(await dreamNow(now, { force: Boolean(values.force), dryRun: Boolean(values['dry-run']), sinceMs: values.since ? parseDuration(values.since) : undefined }));
1088
+ return;
1089
+ }
740
1090
  case 'distill': {
741
1091
  console.log(await distillNow(now, Boolean(values.force)));
742
1092
  return;
@@ -765,15 +1115,32 @@ async function main(argv) {
765
1115
  }
766
1116
  case 'keep': {
767
1117
  const id = need(args[0], 'chompyy keep <id>');
768
- console.log(keepCard(getCard(loadBoard(), id)));
769
- updateBoard((b) => {
770
- const card = getCard(b, id);
771
- card.outcome = 'kept';
772
- card.column = 'done';
773
- card.updatedAt = now.toISOString();
774
- recordOutcome(card, 'kept', now);
775
- return card;
1118
+ const card = getCard(loadBoard(), id);
1119
+ const clash = clashOf(card);
1120
+ if (clash) {
1121
+ // Don't hand the clash to you: Chompyy brings the card onto the new main, checks it, then keeps it (refresh.ts).
1122
+ updateBoard((b) => {
1123
+ getCard(b, id).keepWhenRefreshed = true;
1124
+ });
1125
+ startBackground(['refresh', '--clashing'], 'refresh.log');
1126
+ console.log(`#${id} clashes with ${clash.branch} (${clash.files.join(', ')}): other cards were kept since it ran. Chompyy is bringing it up to date and will keep it once its checks pass.`);
1127
+ return;
1128
+ }
1129
+ keepNow(id, now);
1130
+ return;
1131
+ }
1132
+ case 'refresh': {
1133
+ const config = loadConfig();
1134
+ const deps = refreshDeps(config, freshQuota);
1135
+ await freshQuota();
1136
+ const ran = await withRefreshLock(async () => {
1137
+ if (args[0])
1138
+ await refreshCard(args[0], deps);
1139
+ else
1140
+ await refreshClashing(deps);
776
1141
  });
1142
+ if (!ran)
1143
+ console.log('A refresh is already running; it will go round again to include this.');
777
1144
  return;
778
1145
  }
779
1146
  case 'undo': {