chompyy 0.3.0 → 0.4.1

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