chompyy 0.4.0 → 0.4.2

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
@@ -4,13 +4,14 @@ import { execFileSync, spawn } from 'node:child_process';
4
4
  import { backfillTokens, median } from './tokenstore.js';
5
5
  import { compact, formatTokens, totalTokens } from './tokens.js';
6
6
  import { closeSync, existsSync, openSync, readFileSync } from 'node:fs';
7
+ import { resolve } from 'node:path';
7
8
  import { parseArgs } from 'node:util';
8
9
  import { away, runCard } from './away.js';
9
10
  import { formatPreflight, loadProfile, preflight, saveProfile } from './preflight.js';
10
11
  import { verifyCard } from './verifycard.js';
11
12
  import { parsePermission, recordNeeds } from './permissions.js';
12
13
  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';
14
+ import { addCard, awayQueue, claimDrafts, COLUMNS, continueCard, cycleOf, dropCard, expireSuggested, formatBoard, formatCard, getCard, loadBoard, moveCard, noteDraftFailure, quotaWaitReason, recoverRunning, titleFrom, updateBoard } from './board.js';
14
15
  import { loadConfig, setConfig } from './config.js';
15
16
  import { formatDuration, parseDuration } from './duration.js';
16
17
  import { budgetGate } from './gate.js';
@@ -22,6 +23,8 @@ import { changedFiles, diffCard, keepCard, overlaps, questionsOf, undoCard } fro
22
23
  import { CappedText, ClaudeRunner, claudeAvailable } from './runner.js';
23
24
  import { branchOf, commitLeftovers, gitRoot, planWorkspace, prepareWorkspace } from './workspace.js';
24
25
  import { answerCard, appState, cardView, currentBranch, editBlueprint, editIdea, recordCliLocation } from './appstate.js';
26
+ import { detect, detectText } from './detect.js';
27
+ import { allWindowEnds, archiveWindowEnds, premise, premiseText } from './premise.js';
25
28
  import { keychainAllowed, loadLiveState, refreshLiveQuota } from './livequota.js';
26
29
  import { recentProjects } from './projects.js';
27
30
  import { cliVersion, installApp } from './macapp.js';
@@ -31,11 +34,14 @@ import { keepHistory } from './claudesettings.js';
31
34
  import { blueprintHash, drawPicture } from './picture.js';
32
35
  import { costRange, formatCostRange, readRuns, trendLines } from './costs.js';
33
36
  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';
37
+ import { cachedWorkspaces, dream, dreamDue, formatDream, formatWorkspaces, projectsDir, readLogPath, setTicked } from './dream.js';
35
38
  import { byKind, compare, formatExtras, formatUsage, loadLedger, periodDays, PERIODS, prCosts, usageView } from './usage.js';
36
39
  import { formatTrace, traceSession } from './trace.js';
37
40
  import { homedir } from 'node:os';
38
41
  import { clashOf, refreshCard, refreshGate, refreshClashing, withRefreshLock } from './refresh.js';
42
+ import { adviseText, applyDue, approveAdvice, runAdvise, undoAdvice } from './advice.js';
43
+ import { checkWorked, nudgeProof, nudgeProofText, workedText } from './didwork.js';
44
+ import { coldWarningText, hookCommand, impact, loadNudges, nudgeInstalled, nudgeText, runHook, setNudge, setProjectMode, takeGoingCold } from './nudge.js';
39
45
  import { formatLive, keepAffectsLive, liveOff, liveSet, liveUpdateLocked, loadLive, startLiveUpdate } from './live.js';
40
46
  import { agentInstalled, awayRunning, bedtimeKey, decideTrigger, installAgent, loadTriggerState, markFired, noteTick, parseClock, takeAwayLock, uninstallAgent } from './triggers.js';
41
47
  const HELP = `chompyy: use the 5-hour window capacity that would reset unused
@@ -45,6 +51,18 @@ Quota
45
51
  chompyy status % left, time to reset, pace, weekly used, staleness
46
52
  chompyy quota [--refresh] read live quota from Anthropic now (uses Claude Code's saved login; sends no message)
47
53
  chompyy quota --allow-keychain | --no-keychain allow (or stop) reading that login from the macOS Keychain
54
+ chompyy detect [--days 30] [--all] [--json] what wastes tokens in your setup and habits, ranked, on one screen (--all: evidence and every fix)
55
+ chompyy advise [--json] turn detect's findings into suggested cards to approve or drop: settings changes are
56
+ applied (backed up, undoable) once no Claude Code session is active; habits are tracked
57
+ chompyy advise apply apply approved settings advice now, if no session has been active for 10 minutes
58
+ chompyy worked [--json] did it work? measure each approved advice card against the check on its card
59
+ chompyy nudge on|off live suggestions while you work: stops the first message to a big conversation
60
+ whose cache expired, with the price and the cheaper ways (Claude Code hook)
61
+ chompyy nudge strict|quiet|learn [dir] in this project: always stop me, only a heads-up, or learn (default:
62
+ after 3 stops in a row you sent anyway, a heads-up instead)
63
+ chompyy nudge on or off, and what the stops saved
64
+ chompyy nudge due [--json] conversations 45-60 min into a pause, about to go cold (each reported once; the app notifies; only while nudge is on)
65
+ chompyy premise [--json] how often a 5-hour window reset with capacity left while the week still had room
48
66
  chompyy eat-tokens show leftover quota and cards you could choose to run (read-only)
49
67
 
50
68
  Board
@@ -73,6 +91,8 @@ Back
73
91
  chompyy undo <id> throw it away (removes its branch; yours are untouched)
74
92
  chompyy answer <id> answer the run's questions (stdin); the card goes back to approved
75
93
  chompyy redo <id> throw this attempt away and run it again from your latest code
94
+ chompyy continue <id> ["note"] a done card did only part of the job: run another cycle that builds on it
95
+ (the next run is told what was done and, from the note, what is still missing)
76
96
  chompyy rate <id> <1-5> ["why"] [--to-five "change" ...] rate a result; --to-five = what would have made it a 5
77
97
  chompyy five-star <id> options for "what would have made it a 5?" (JSON)
78
98
  chompyy signals [--json] everything Chompyy has recorded from you: ratings, edits, answers
@@ -236,7 +256,7 @@ function draftPending(now) {
236
256
  return;
237
257
  const toDraw = updateBoard((b) => {
238
258
  const due = b.cards.filter((c) => ['suggested', 'later', 'approved'].includes(c.column) &&
239
- c.blueprint && !c.draftingAt && !c.pictureError &&
259
+ c.blueprint && !c.draftingAt && !c.pictureError && (!c.advice || c.advice.lane === 'work') &&
240
260
  (!c.picture || c.picture.blueprintHash !== blueprintHash(c.blueprint)) &&
241
261
  (!c.drawingAt || Date.parse(c.drawingAt) < now.getTime() - 6 * 60_000));
242
262
  for (const c of due)
@@ -294,9 +314,12 @@ async function distillNow(now, force = false) {
294
314
  /** Keep a card: merge it, record it, update the live app, and bring the other cards in review up to date. */
295
315
  function keepNow(id, now) {
296
316
  const kept = getCard(loadBoard(), id);
317
+ const files = changedFiles(kept); // read before Keep removes the branch
297
318
  console.log(keepCard(kept));
298
319
  updateBoard((b) => {
299
320
  const card = getCard(b, id);
321
+ if (card.run)
322
+ card.run.files = files;
300
323
  card.outcome = 'kept';
301
324
  card.column = 'done';
302
325
  delete card.keepWhenRefreshed;
@@ -471,7 +494,8 @@ async function main(argv) {
471
494
  const [command, ...args] = values.help ? ["help"] : positionals;
472
495
  const now = new Date();
473
496
  const json = (data) => console.log(JSON.stringify(data, null, 2));
474
- if (command !== 'statusline')
497
+ // detect and premise only read: run once through npx, they must not point the app at npx's temporary copy.
498
+ if (command !== 'statusline' && command !== 'detect' && command !== 'premise' && command !== 'hook')
475
499
  recordCliLocation();
476
500
  /** Fresh quota before anything that reads it (at most every 5 minutes unless forced). */
477
501
  const freshQuota = async (force = false) => {
@@ -886,6 +910,16 @@ async function main(argv) {
886
910
  const bad = allow.filter((a) => !parsePermission(a));
887
911
  if (bad.length)
888
912
  throw new Error(`Not a permission: ${bad.join(', ')}. Use network:<domain> or "command:<program> *".`);
913
+ // Advice cards (chompyy advise): what approving does depends on the lane, not an away run.
914
+ const adv = getCard(loadBoard(), id);
915
+ if (adv.advice && adv.advice.lane !== 'work') {
916
+ if (adv.column !== 'suggested' && adv.column !== 'later')
917
+ throw new Error(`Card #${adv.id} is in ${adv.column}; only a suggested card can be approved.`);
918
+ console.log(updateBoard((b) => approveAdvice(getCard(b, id), now)));
919
+ for (const line of updateBoard((b) => applyDue(b, now)))
920
+ console.log(` ${line}`);
921
+ return;
922
+ }
889
923
  const card = updateBoard((b) => {
890
924
  const c = moveCard(b, id, 'approved', now);
891
925
  if (allow.length)
@@ -941,6 +975,18 @@ async function main(argv) {
941
975
  // Run by the LaunchAgent every 5 minutes. Prints one line per tick to tick.log.
942
976
  await freshQuota();
943
977
  const config = loadConfig();
978
+ // Approved settings advice goes in once no Claude Code session is active.
979
+ try {
980
+ updateBoard((b) => applyDue(b, now));
981
+ }
982
+ catch { }
983
+ // Did it work? Re-measure applied advice once an hour (a transcript scan, so not every tick).
984
+ if (now.getMinutes() < 5) {
985
+ try {
986
+ updateBoard((b) => checkWorked(b, now));
987
+ }
988
+ catch { }
989
+ }
944
990
  const board = loadBoard();
945
991
  // Refreshes that waited for quota (refresh.ts) go as soon as there is some again.
946
992
  if (board.cards.some((c) => c.column === 'review' && c.refresh?.state === 'waiting') && !refreshGate(loadSnapshot(), now)) {
@@ -1091,6 +1137,78 @@ async function main(argv) {
1091
1137
  console.log(await distillNow(now, Boolean(values.force)));
1092
1138
  return;
1093
1139
  }
1140
+ case 'detect': {
1141
+ const r = detect({ days: values.days ? Number(values.days) : 30, now });
1142
+ if (values.json)
1143
+ return json(r);
1144
+ console.log(detectText(r, { all: Boolean(values.all), projects: projectsDir().replace(homedir(), '~') }).join('\n'));
1145
+ return;
1146
+ }
1147
+ case 'advise': {
1148
+ // The detective, step 3: findings become suggested cards. `advise apply`: apply approved settings advice
1149
+ // once no Claude Code session is active (the app asks every minute).
1150
+ if (args[0] === 'apply') {
1151
+ const lines = updateBoard((b) => applyDue(b, now));
1152
+ if (values.json)
1153
+ return json(lines);
1154
+ return console.log(lines.length ? lines.join('\n') : 'Nothing waiting to be applied.');
1155
+ }
1156
+ const res = updateBoard((b) => runAdvise(b, now));
1157
+ if (values.json)
1158
+ return json({ added: res.added.map((c) => c.id), updated: res.updated.map((c) => c.id), skipped: res.skipped });
1159
+ return console.log(adviseText(res));
1160
+ }
1161
+ case 'worked': {
1162
+ // The detective, step 5: each applied/tried advice card against the check it registered (didwork.ts).
1163
+ const cards = updateBoard((b) => checkWorked(b, now));
1164
+ const proof = nudgeInstalled() || loadNudges().length ? nudgeProof(now) : null;
1165
+ if (values.json)
1166
+ return json({ cards: cards.map((c) => ({ id: c.id, title: c.title, rule: c.advice.rule, lane: c.advice.lane, ...c.advice.result })), nudge: proof });
1167
+ if (!cards.length && proof)
1168
+ return console.log(nudgeProofText(proof).join('\n'));
1169
+ return console.log([workedText(cards), ...(proof ? ['', ...nudgeProofText(proof)] : [])].join('\n'));
1170
+ }
1171
+ case 'hook': {
1172
+ // Claude Code's UserPromptSubmit hook. Must never fail loudly or stop a prompt by accident.
1173
+ if (args[0] !== 'prompt')
1174
+ return;
1175
+ try {
1176
+ const out = runHook(await readStdin());
1177
+ if (out)
1178
+ console.log(out);
1179
+ }
1180
+ catch {
1181
+ /* let the prompt through */
1182
+ }
1183
+ return;
1184
+ }
1185
+ case 'nudge': {
1186
+ const sub = args[0];
1187
+ if (sub === 'on' || sub === 'off')
1188
+ return console.log(setNudge(sub === 'on', sub === 'on' ? hookCommand() : undefined));
1189
+ // Per project: always stop me here, never stop me (a heads-up only), or learn from what I do (the default).
1190
+ if (sub === 'strict' || sub === 'quiet' || sub === 'learn')
1191
+ return console.log(setProjectMode(sub, resolve(args[1] ?? process.cwd())));
1192
+ if (sub === 'due') {
1193
+ // The app asks every minute; each conversation going cold is reported once.
1194
+ const due = (nudgeInstalled() ? takeGoingCold(now.getTime()) : []).map((d) => ({ ...d, ...coldWarningText(d) }));
1195
+ if (values.json)
1196
+ return json(due);
1197
+ return console.log(due.length ? due.map((d) => `${d.title}\n ${d.body}`).join('\n') : 'Nothing about to go cold.');
1198
+ }
1199
+ if (values.json)
1200
+ return json(impact());
1201
+ return console.log([nudgeText(nudgeInstalled()), impact().line].join('\n'));
1202
+ }
1203
+ case 'premise': {
1204
+ const ends = allWindowEnds(loadSamples(), now.getTime());
1205
+ archiveWindowEnds(loadSamples(), now.getTime());
1206
+ const p = premise(ends);
1207
+ if (values.json)
1208
+ return json({ ...p, windows: ends });
1209
+ console.log(premiseText(p).join('\n'));
1210
+ return;
1211
+ }
1094
1212
  case 'trends': {
1095
1213
  const lines = trendLines(readRuns(), readSignals(), now);
1096
1214
  console.log(lines.length ? lines.join('\n') : 'Not enough runs yet for trends (needs 3).');
@@ -1145,9 +1263,15 @@ async function main(argv) {
1145
1263
  }
1146
1264
  case 'undo': {
1147
1265
  const id = need(args[0], 'chompyy undo <id>');
1148
- console.log(undoCard(getCard(loadBoard(), id)));
1266
+ const undone = getCard(loadBoard(), id);
1267
+ if (undone.advice && undone.advice.lane !== 'work')
1268
+ return console.log(updateBoard((b) => undoAdvice(getCard(b, id), now)));
1269
+ const files = changedFiles(undone); // read before Undo removes the branch
1270
+ console.log(undoCard(undone));
1149
1271
  updateBoard((b) => {
1150
1272
  const card = getCard(b, id);
1273
+ if (card.run)
1274
+ card.run.files = files;
1151
1275
  card.outcome = 'undone';
1152
1276
  card.column = 'done';
1153
1277
  card.updatedAt = now.toISOString();
@@ -1175,6 +1299,15 @@ async function main(argv) {
1175
1299
  console.log(`🔁 #${card.id} back in approved; it runs again from your latest code on the next away run.`);
1176
1300
  return;
1177
1301
  }
1302
+ case 'continue': {
1303
+ const id = need(args[0], 'chompyy continue <id> ["what is still missing"]');
1304
+ const note = args.slice(1).join(' ').trim();
1305
+ const before = getCard(loadBoard(), id);
1306
+ const prior = { summary: fullOutput(before) ?? before.run?.summary, files: before.run?.files ?? changedFiles(before) };
1307
+ const card = updateBoard((b) => continueCard(b, id, note, now, prior));
1308
+ console.log(`🔁 #${card.id} back in approved as cycle ${cycleOf(card)}; the next away run gets what cycle ${cycleOf(card) - 1} did${note ? ' and your note' : ''}.`);
1309
+ return;
1310
+ }
1178
1311
  case 'rate': {
1179
1312
  const usage = 'chompyy rate <id> <1-5> ["optional reason"]';
1180
1313
  const id = need(args[0], usage);