chompyy 0.7.1 → 0.8.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/README.md CHANGED
@@ -163,6 +163,7 @@ Each card in a git repo runs in its own worktree at `~/.chompyy/worktrees/<id>`
163
163
  | `chompyy demon [on\|off]` | Demon mode: in the last 90 minutes of a window that would reset 20%+ unused, run approved cards to eat it (`on` = every window, via the last-hour trigger) |
164
164
  | `chompyy receipt [--json]` | Your week as a bake-sale receipt: cards baked and their API value, kept, burnt (undone), tokens, resent less than last week. No names, safe to share |
165
165
  | `chompyy bedtime <23:30\|off>` / `chompyy last-hour <on\|off>` / `chompyy missed-reset <on\|off>` | Turn the bedtime, last-hour-before-reset and missed-reset (first tick after an unused reset, default off) triggers on or off |
166
+ | `chompyy settings [<key> <value>] [--json]` | The settings in the Mac app's Settings window: `language` (en, zh-Hant, system), `bedtime`, `run-model` (default, haiku, sonnet, opus), `keep-free` (% of the 5-hour window a card leaves) |
166
167
  | `chompyy quota [--refresh] [--allow-keychain\|--no-keychain]` | Read the live quota now and show `status`. The keychain flags allow or stop reading your Claude sign-in from the macOS keychain |
167
168
  | `chompyy usage [--period today\|7d\|30d\|month] [--days 7] [--json]` | Tokens and cost by day, project and kind of work, pull request costs, and how your plan compares with API prices |
168
169
  | `chompyy trace <conversation id> [--json]` | Where one conversation's tokens went (ids: `chompyy usage --json`) |
package/dist/appstate.js CHANGED
@@ -2,6 +2,7 @@
2
2
  // The app holds no logic of its own: it shows this JSON and calls chompyy commands.
3
3
  import { daytimeState } from './daytime.js';
4
4
  import { execFileSync } from 'node:child_process';
5
+ import { createHash } from 'node:crypto';
5
6
  import { readFileSync, existsSync } from 'node:fs';
6
7
  import { clashOf } from './refresh.js';
7
8
  import { join } from 'node:path';
@@ -9,7 +10,7 @@ import { getCard, titleFrom } from './board.js';
9
10
  import { budgetGate } from './gate.js';
10
11
  import { appendJsonl, homePath, readJson, writeJson } from './home.js';
11
12
  import { keychainAsk, loadLiveState } from './livequota.js';
12
- import { windowView } from './quota.js';
13
+ import { loadSnapshot, windowView } from './quota.js';
13
14
  import { loadSamples, pacing } from './pacing.js';
14
15
  import { changedFiles } from './review.js';
15
16
  import { loadColdStart } from './coldstart.js';
@@ -19,7 +20,7 @@ import { cachedWorkspaces, loadDream } from './dream.js';
19
20
  import { learning } from './learning.js';
20
21
  import { describeSignal, loadStore, nextQuestion, readSignals, receipts } from './taste.js';
21
22
  import { agentInstalled, awayRunning, loadTriggerState } from './triggers.js';
22
- import { nightcap } from './nightcap.js';
23
+ import { nextBedtime, nightcap, roomTonight, typicalCardPct } from './nightcap.js';
23
24
  import { punchcard } from './punchcard.js';
24
25
  import { loadLedger } from './usage.js';
25
26
  import { demonOffer } from './demon.js';
@@ -36,7 +37,7 @@ import { parseQuestions } from './questions.js';
36
37
  export function cardView(card, runs = readRuns()) {
37
38
  const qPath = card.run ? join(card.run.workdir, 'QUESTIONS.md') : '';
38
39
  const questionsText = qPath && existsSync(qPath) ? readFileSync(qPath, 'utf8') : null;
39
- return {
40
+ const view = {
40
41
  ...card,
41
42
  files: card.run ? changedFiles(card) : [],
42
43
  questionsText,
@@ -47,6 +48,9 @@ export function cardView(card, runs = readRuns()) {
47
48
  clashFiles: card.column === 'review' ? clashOf(card)?.files ?? [] : [],
48
49
  permissionPlan: ['later', 'suggested', 'approved'].includes(card.column) ? permissionPlanFor(card) : [],
49
50
  };
51
+ // Not updatedAt: a finished picture, a failed blueprint and other background changes don't bump it, so a
52
+ // tile compared by updatedAt kept saying "Drawing…" after the picture was done (#60).
53
+ return { ...view, rev: createHash('sha1').update(JSON.stringify(view)).digest('hex').slice(0, 12) };
50
54
  }
51
55
  /** The card's permission plan: earlier runs' blocks in its repo, preflight's network needs, the blueprint's Needs. */
52
56
  function permissionPlanFor(card) {
@@ -129,6 +133,22 @@ export function providersState(config, now) {
129
133
  };
130
134
  }
131
135
  export function nightcapNow(board, config, now) {
136
+ const cap = nightcapPhase(board, config, now);
137
+ if (!cap || (cap.phase !== 'offer' && cap.phase !== 'armed'))
138
+ return cap;
139
+ try {
140
+ // The 5-hour window as it will be at bedtime: what's left then, or a fresh 100% once it has reset.
141
+ const at = new Date(now.getTime() + nextBedtime(now, cap.bedtime, config.bedtimeWindowMin).inMin * 60_000);
142
+ const five = windowView(loadSnapshot()?.fiveHour, at);
143
+ const left = five.known ? five.leftPct : five.reason === 'stale' ? 100 : null;
144
+ const room = roomTonight(cap.cards, typicalCardPct(readRuns()), left, config.min5hLeftPct);
145
+ return room ? { ...cap, room } : cap;
146
+ }
147
+ catch {
148
+ return cap;
149
+ }
150
+ }
151
+ function nightcapPhase(board, config, now) {
132
152
  return nightcap({
133
153
  now,
134
154
  bedtime: config.bedtime,
package/dist/away.js CHANGED
@@ -310,6 +310,8 @@ export async function runCard(id, timeoutMs, deps, trigger) {
310
310
  ws = deps.prepare(card);
311
311
  if (ws.base)
312
312
  out(` from ${ws.base.ref} @ ${ws.base.commit.slice(0, 7)}`);
313
+ if (ws.caughtUp)
314
+ out(` its earlier copy: ${ws.caughtUp}`);
313
315
  for (const s of ws.setup ?? [])
314
316
  if (s.source !== 'kept')
315
317
  out(` deps in ${s.dir}: ${s.source}${s.note ? ` (${s.note})` : ''}`);
package/dist/blueprint.js CHANGED
@@ -1,5 +1,6 @@
1
1
  // Blueprint (spec §5.4): the scope agreed before a card runs, drafted by a cheap model.
2
2
  import { writeFileSync } from 'node:fs';
3
+ import { inYourLanguage } from './language.js';
3
4
  import { join } from 'node:path';
4
5
  import { ensureCardDir } from './board.js';
5
6
  export const BLUEPRINT_SECTIONS = ['Goal', 'Scope', 'Out of scope', 'Shape', "How it's checked"];
@@ -112,7 +113,7 @@ export function cleanBlueprint(output) {
112
113
  }
113
114
  export async function draftBlueprint(card, runner, opts) {
114
115
  const result = await runner.run({
115
- prompt: blueprintPrompt(card),
116
+ prompt: inYourLanguage(blueprintPrompt(card)),
116
117
  cwd: opts.cwd,
117
118
  model: opts.model,
118
119
  // Research while drafting: the plan you approve should already be checked against the docs.
@@ -157,7 +158,7 @@ export function cleanTitle(output) {
157
158
  */
158
159
  export async function draftTitle(card, runner, opts) {
159
160
  try {
160
- const result = await runner.run({ prompt: titlePrompt(card.idea), cwd: opts.cwd, model: opts.model, tools: '', timeoutMs: opts.timeoutMs ?? 60_000 });
161
+ const result = await runner.run({ prompt: inYourLanguage(titlePrompt(card.idea)), cwd: opts.cwd, model: opts.model, tools: '', timeoutMs: opts.timeoutMs ?? 60_000 });
161
162
  if (result.exitCode !== 0 || result.timedOut)
162
163
  return card.title;
163
164
  return cleanTitle(result.output) || card.title;
@@ -166,27 +167,6 @@ export async function draftTitle(card, runner, opts) {
166
167
  return card.title;
167
168
  }
168
169
  }
169
- /** A draft that started this long ago and never finished (its process died) counts as not drafting. */
170
- const DRAFT_STALE_MS = 3 * 60_000;
171
- /**
172
- * Later cards "Draft all" should draft: no blueprint yet and not being drafted right now.
173
- * Cards with a blueprint (edited ones too) are left alone; a card whose last draft failed is retried.
174
- */
175
- export function laterToDraft(board, now = new Date()) {
176
- return board.cards.filter((c) => c.column === 'later' &&
177
- !c.blueprint?.trim() &&
178
- (!c.draftingAt || Date.parse(c.draftingAt) < now.getTime() - DRAFT_STALE_MS));
179
- }
180
- /**
181
- * The plan for `chompyy blueprint --all-later`: which cards to draft, or why it drafts nothing.
182
- * Same gate as background drafting: with no active 5-hour window a model call would start a new one.
183
- */
184
- export function draftAllPlan(board, windowActive, now = new Date()) {
185
- if (!windowActive)
186
- return { ids: [], message: 'No active 5-hour window: drafting now would start one. Nothing drafted; try again while you are using Claude Code.' };
187
- const ids = laterToDraft(board, now).map((c) => c.id);
188
- return ids.length ? { ids } : { ids, message: 'Every later card already has a blueprint (or is being drafted).' };
189
- }
190
170
  /**
191
171
  * True when a failed model call ran into the plan's usage limit (out of quota), e.g. Claude Code's
192
172
  * "Claude AI usage limit reached|1763470800", "5-hour limit reached ∙ resets 3pm" or "You've hit your limit".
@@ -214,7 +194,7 @@ ${card.summary ?? '(nothing)'}
214
194
  Files changed: ${(card.files ?? []).join(', ') || '(unknown)'}`;
215
195
  }
216
196
  export async function draftFiveStarOptions(card, runner, opts) {
217
- const result = await runner.run({ prompt: fiveStarPrompt(card), cwd: opts.cwd, model: opts.model, tools: '', timeoutMs: 60_000 });
197
+ const result = await runner.run({ prompt: inYourLanguage(fiveStarPrompt(card)), cwd: opts.cwd, model: opts.model, tools: '', timeoutMs: 60_000 });
218
198
  if (result.exitCode !== 0 || result.timedOut)
219
199
  throw new Error('could not draft options');
220
200
  const lines = result.output
package/dist/cli.js CHANGED
@@ -10,7 +10,7 @@ import { away, runCard } from './away.js';
10
10
  import { formatPreflight, loadProfile, preflight, saveProfile } from './preflight.js';
11
11
  import { verifyCard } from './verifycard.js';
12
12
  import { parsePermission, recordNeeds } from './permissions.js';
13
- import { draftAllPlan, draftBlueprint, draftFiveStarOptions, draftTitle, GENERIC_FIVE_STAR, isUsageLimit, writeBlueprintFile } from './blueprint.js';
13
+ import { draftBlueprint, draftFiveStarOptions, draftTitle, GENERIC_FIVE_STAR, isUsageLimit, writeBlueprintFile } from './blueprint.js';
14
14
  import { addCard, awayQueue, claimDrafts, COLUMNS, continueCard, cycleOf, dropCard, expireSuggested, formatBoard, formatCard, getCard, loadBoard, moveCard, noteDraftFailure, quotaWaitReason, recoverRunning, titleFrom, updateBoard } from './board.js';
15
15
  import { loadConfig, setConfig } from './config.js';
16
16
  import { formatDuration, parseDuration } from './duration.js';
@@ -25,6 +25,8 @@ import { recipeOf } from './recipe.js';
25
25
  import { CappedText, ClaudeRunner, claudeAvailable } from './runner.js';
26
26
  import { branchOf, commitLeftovers, gitRoot, planWorkspace, prepareWorkspace } from './workspace.js';
27
27
  import { answerCard, appState, cardView, currentBranch, editBlueprint, editIdea, nightcapNow, providersState, recordCliLocation, tasteState } from './appstate.js';
28
+ import { roomLine } from './nightcap.js';
29
+ import { changeSetting, settingsText, settingsView } from './settings.js';
28
30
  import { codexInstalled, refreshCodexQuota } from './codexquota.js';
29
31
  import { refreshAgents } from './agentusage.js';
30
32
  import { stampCard } from './stamps.js';
@@ -95,7 +97,6 @@ Board
95
97
  chompyy board [--column c] cards by column (suggested later approved running review done)
96
98
  chompyy show <id> one card: blueprint, last run, what the agent said
97
99
  chompyy blueprint <id> (re)draft the blueprint with a cheap model [--model haiku]
98
- --all-later draft every later card that has no blueprint yet, one at a time
99
100
  chompyy picture <id> (re)draw the card's picture: a diagram of what it will do (diagram-design skill)
100
101
  chompyy approve <id> later → approved (needs a blueprint)
101
102
  chompyy edit-blueprint <id> replace the blueprint with text from stdin
@@ -160,6 +161,7 @@ Triggers (start away runs on their own; the budget gate still decides every card
160
161
  chompyy demon [on|off] eat what's left of a window before it resets: run approved cards (on = every window)
161
162
  chompyy receipt [--json] your week as a bake-sale receipt: cards baked, kept, burnt, tokens; safe to share
162
163
  chompyy bedtime <23:30|off> run approved cards at bedtime (with the window that is left)
164
+ chompyy settings [<key> <value>] [--json] language, bedtime, overnight model, how much of the window to keep free
163
165
  chompyy last-hour <on|off> run approved cards in the last hour before a 5-hour reset
164
166
  chompyy missed-reset <on|off> run approved cards on the first tick after a reset nothing used (default off)
165
167
  chompyy tick check the triggers once (what the LaunchAgent runs)
@@ -509,7 +511,6 @@ async function main(argv) {
509
511
  allowPositionals: true,
510
512
  options: {
511
513
  'no-blueprint': { type: 'boolean' },
512
- 'all-later': { type: 'boolean' },
513
514
  clashing: { type: 'boolean' },
514
515
  wait: { type: 'boolean' },
515
516
  'dry-run': { type: 'boolean' },
@@ -1082,59 +1083,6 @@ async function main(argv) {
1082
1083
  return;
1083
1084
  }
1084
1085
  case 'blueprint': {
1085
- if (values['all-later']) {
1086
- await freshQuota();
1087
- if (!claudeAvailable(loadConfig().claudeBin))
1088
- throw new Error('claude CLI not found: drafting needs it.');
1089
- // Same rule as background drafting (card #20): with 0% left, every draft would only hit the limit.
1090
- const waiting = quotaEmpty(now);
1091
- if (waiting) {
1092
- updateBoard((b) => claimDrafts(b, now, waiting)); // marks the later cards "waiting for quota"
1093
- console.log(`Nothing drafted: ${waiting}. They draft on their own once quota is back.`);
1094
- return;
1095
- }
1096
- const plan = draftAllPlan(loadBoard(), windowActive(now), now);
1097
- if (!plan.ids.length) {
1098
- console.log(plan.message);
1099
- return;
1100
- }
1101
- // Mark them all first so background drafting and the app don't start a second draft of the same card.
1102
- updateBoard((b) => {
1103
- for (const id of plan.ids)
1104
- getCard(b, id).draftingAt = new Date().toISOString();
1105
- });
1106
- const failed = [];
1107
- for (const [i, id] of plan.ids.entries()) {
1108
- updateBoard((b) => {
1109
- getCard(b, id).draftingAt = new Date().toISOString(); // fresh, so a long queue doesn't look stale
1110
- });
1111
- if (!values.quiet)
1112
- console.log(`Drafting #${id} (${i + 1} of ${plan.ids.length})…`);
1113
- try {
1114
- await blueprintCard(id, values.model); // a failure is kept on the card as blueprintError
1115
- }
1116
- catch (err) {
1117
- const message = err instanceof Error ? err.message : String(err);
1118
- if (isUsageLimit(message)) {
1119
- // Out of quota mid-way: the rest would fail the same way. They wait for the reset instead (card #20).
1120
- const left = plan.ids.slice(i + 1);
1121
- updateBoard((b) => { for (const l of left)
1122
- delete getCard(b, l).draftingAt; claimDrafts(b, new Date(), quotaEmpty(new Date()) ?? 'waiting for quota: the usage limit was hit'); });
1123
- 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.`);
1124
- process.exitCode = i === 0 ? 1 : 0;
1125
- return;
1126
- }
1127
- failed.push(id);
1128
- if (!values.quiet)
1129
- console.log(` #${id} failed: ${message}`);
1130
- }
1131
- }
1132
- const done = plan.ids.length - failed.length;
1133
- 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)` : ''}.`);
1134
- if (done === 0)
1135
- process.exitCode = 1;
1136
- return;
1137
- }
1138
1086
  const id = need(args[0], 'chompyy blueprint <id> [--model haiku]');
1139
1087
  const text = await blueprintCard(id, values.model);
1140
1088
  if (!values.quiet)
@@ -1305,7 +1253,10 @@ async function main(argv) {
1305
1253
  const line = { offer: `Leave it to me tonight? ${cap.cards} card(s) could run at ${cap.bedtime}: chompyy nightcap on ${cap.bedtime}`,
1306
1254
  armed: `Tonight at ${cap.bedtime}: ${cap.cards} card(s) run while you sleep. Skip: chompyy nightcap skip`,
1307
1255
  skipped: `Skipping tonight. Back on: chompyy nightcap unskip`, running: 'Running your cards. Sleep well.' }[cap.phase];
1308
- return console.log(`🌙 ${line}`);
1256
+ console.log(`🌙 ${line}`);
1257
+ if (cap.room)
1258
+ console.log(` ${roomLine(cap.cards, cap.room)}`);
1259
+ return;
1309
1260
  }
1310
1261
  case 'demon': {
1311
1262
  // Demon mode: run approved cards in the last hour of a window that would otherwise reset unused.
@@ -1337,6 +1288,14 @@ async function main(argv) {
1337
1288
  console.log(`Every window: ${auto ? 'on' : 'off (chompyy demon on)'}`);
1338
1289
  return;
1339
1290
  }
1291
+ case 'settings': {
1292
+ if (args[0])
1293
+ return console.log(changeSetting(args[0], args[1]));
1294
+ const view = settingsView(loadConfig());
1295
+ if (values.json)
1296
+ return json(view);
1297
+ return console.log(settingsText(view));
1298
+ }
1340
1299
  case 'bedtime': {
1341
1300
  const v = need(args[0], 'chompyy bedtime <23:30|off>');
1342
1301
  if (v === 'off') {
package/dist/coldstart.js CHANGED
@@ -2,6 +2,7 @@
2
2
  // taste.md and a few suggested cards. Nothing is added until you accept it. Every proposal must cite your
3
3
  // sessions, and the citations are checked against the digest, so the model can't invent evidence.
4
4
  import { existsSync, rmSync, writeFileSync } from 'node:fs';
5
+ import { inYourLanguage } from './language.js';
5
6
  import { addCard, updateBoard } from './board.js';
6
7
  import { appendJsonl, homePath, readJson, writeJson } from './home.js';
7
8
  import { buildDigest, pickPrompts } from './history.js';
@@ -108,7 +109,7 @@ export async function runColdStart(scan, runner, opts) {
108
109
  if (!scan.sessions.length)
109
110
  throw new Error('No Claude Code sessions found to learn from yet. Use Claude Code for a while, then try again.');
110
111
  const { text, included } = buildDigest(scan.sessions, opts.maxChars);
111
- const result = await runner.run({ prompt: coldStartPrompt(text, opts.existing), cwd: opts.cwd, model: opts.model, tools: '', timeoutMs: 240_000 });
112
+ const result = await runner.run({ prompt: inYourLanguage(coldStartPrompt(text, opts.existing)), cwd: opts.cwd, model: opts.model, tools: '', timeoutMs: 240_000 });
112
113
  if (result.timedOut)
113
114
  throw new Error('Reading your history timed out. Try again.');
114
115
  if (result.exitCode !== 0)
package/dist/config.js CHANGED
@@ -1,5 +1,7 @@
1
1
  // User settings: ~/.chompyy/config.json, merged over these defaults.
2
2
  import { homePath, readJson, writeJson } from './home.js';
3
+ /** Languages Chompyy is translated into, as BCP 47 tags (the names macOS uses for its .lproj folders). */
4
+ export const LANGUAGES = { en: 'English', 'zh-Hant': '繁體中文' };
3
5
  export const DEFAULT_CONFIG = {
4
6
  claudeBin: 'claude',
5
7
  blueprintModel: 'haiku',
@@ -79,6 +81,7 @@ export const DEFAULT_CONFIG = {
79
81
  bedtime: null,
80
82
  bedtimeWindowMin: 60,
81
83
  missedReset: false,
84
+ language: null,
82
85
  };
83
86
  export function configPath() {
84
87
  return homePath('config.json');
@@ -0,0 +1,16 @@
1
+ // The language you picked (`chompyy settings language`) for what the models write that a person reads: blueprints,
2
+ // card titles, suggested tasks, cold-start proposals and pictures. Away runs, the nightly read and taste distilling
3
+ // stay in English: they write code and rules for agents, not words for you.
4
+ import { LANGUAGES, loadConfig } from './config.js';
5
+ /** The note added to a prompt; empty for English. Code parses headings and JSON keys, so those stay as they are. */
6
+ export function languageNote(language) {
7
+ if (!language || language === 'en')
8
+ return '';
9
+ const name = language === 'zh-Hant' ? 'Traditional Chinese (繁體中文, as used in Taiwan)' : LANGUAGES[language];
10
+ return (`\n\nWrite every word a person reads in ${name}. Keep these exactly as they are, in English: markdown headings ` +
11
+ 'that start with ##, JSON keys, code, file names, commands, and names of tools and products.');
12
+ }
13
+ /** A prompt with the language note for the language in config.json. */
14
+ export function inYourLanguage(prompt) {
15
+ return prompt + languageNote(loadConfig().language);
16
+ }
package/dist/nightcap.js CHANGED
@@ -4,6 +4,25 @@
4
4
  * Skip tonight. The bedtime trigger (triggers.ts) does the running; this only decides what the panel says.
5
5
  */
6
6
  import { bedtimeKey, parseClock } from './triggers.js';
7
+ /**
8
+ * Room left tonight. The Dec 5 night ran 7 cards on about 15% of the window and 60% reset unused: this says so
9
+ * before bed, while you can still approve more. `perCardPct` is a typical card's share (typicalCardPct),
10
+ * `leftPct` what the window has at bedtime (100 when it will have reset). The budget gate still decides each card.
11
+ */
12
+ export function roomTonight(cards, perCardPct, leftPct, minLeftPct) {
13
+ if (perCardPct === null || leftPct === null || perCardPct <= 0)
14
+ return null;
15
+ const spare = leftPct - minLeftPct - cards * perCardPct;
16
+ return { usesPct: Math.max(1, Math.round(cards * perCardPct)), more: Math.max(0, Math.floor(spare / perCardPct)) };
17
+ }
18
+ /** A typical card's share of the 5-hour window: the median of the last 30 measured runs, once there are 3. */
19
+ export function typicalCardPct(runs) {
20
+ const known = runs.filter((r) => r.fiveHourPct !== null && r.status !== 'error').slice(-30).map((r) => r.fiveHourPct).sort((a, b) => a - b);
21
+ if (known.length < 3)
22
+ return null;
23
+ const mid = Math.floor(known.length / 2);
24
+ return known.length % 2 ? known[mid] : (known[mid - 1] + known[mid]) / 2;
25
+ }
7
26
  /** The nightcap goes on this long before bedtime. */
8
27
  const EVENING_MIN = 3 * 60;
9
28
  /** With no bedtime set, offer from 20:00 to 00:59. */
@@ -70,3 +89,8 @@ export function nightcap(i) {
70
89
  const bedtime = offeredBedtime(i.now, quiet);
71
90
  return { phase: 'offer', bedtime, cards: i.approved, key, ...(quiet !== null && bedtime === `${pad(quiet)}:00` ? { quiet: true } : {}) };
72
91
  }
92
+ /** "7 cards use about 28% of the 5-hour window. Room for about 9 more: approve some in Suggested." */
93
+ export function roomLine(cards, room) {
94
+ const uses = `${cards} card${cards === 1 ? '' : 's'} use${cards === 1 ? 's' : ''} about ${room.usesPct}% of the 5-hour window.`;
95
+ return room.more > 0 ? `${uses} Room for about ${room.more} more: approve some in Suggested.` : `${uses} That fills tonight.`;
96
+ }
package/dist/picture.js CHANGED
@@ -2,6 +2,7 @@
2
2
  // the diagram-design skill (vendored in cli/vendor/diagram-design, MIT). One HTML + SVG file per card,
3
3
  // in Chompyy's skin; the dark copy is made by swapping tokens (the skill's inversion rule), no second call.
4
4
  import { createHash } from 'node:crypto';
5
+ import { inYourLanguage } from './language.js';
5
6
  import { spawnSync } from 'node:child_process';
6
7
  import { existsSync, writeFileSync } from 'node:fs';
7
8
  import { dirname, join } from 'node:path';
@@ -107,7 +108,7 @@ export async function drawPicture(card, runner, opts) {
107
108
  if (!existsSync(join(skillDir(), 'SKILL.md')))
108
109
  throw new Error('The diagram-design skill is missing from this install.');
109
110
  const suggested = suggestTypes(card);
110
- const result = await runner.run({ prompt: picturePrompt(card, suggested), cwd: skillDir(), model: opts.model, tools: 'Read,Glob,Grep', timeoutMs: opts.timeoutMs ?? 300_000 });
111
+ const result = await runner.run({ prompt: inYourLanguage(picturePrompt(card, suggested)), cwd: skillDir(), model: opts.model, tools: 'Read,Glob,Grep', timeoutMs: opts.timeoutMs ?? 300_000 });
111
112
  if (result.timedOut)
112
113
  throw new Error('Drawing the picture timed out.');
113
114
  if (result.exitCode !== 0)
@@ -0,0 +1,69 @@
1
+ // `chompyy settings`: the few settings people change, in one place (the Mac app's Settings window reads and writes
2
+ // these). Everything else stays in ~/.chompyy/config.json.
3
+ import { LANGUAGES, setConfig } from './config.js';
4
+ import { agentInstalled, installAgent, parseClock } from './triggers.js';
5
+ /** Models an overnight run can use; "default" = Claude Code's own default. */
6
+ export const RUN_MODELS = ['default', 'haiku', 'sonnet', 'opus'];
7
+ export function settingsView(c) {
8
+ return {
9
+ language: c.language,
10
+ languages: { ...LANGUAGES },
11
+ bedtime: c.bedtime,
12
+ runModel: c.runModel ?? 'default',
13
+ keepFreePct: c.min5hLeftPct,
14
+ };
15
+ }
16
+ export const SETTINGS_USAGE = 'chompyy settings language <en|zh-Hant|system> | bedtime <23:30|off> | run-model <default|haiku|sonnet|opus> | keep-free <0-50>';
17
+ /** Change one setting; returns the line to show. Throws with the usage when the key or value is wrong. */
18
+ export function changeSetting(key, value) {
19
+ if (value === undefined)
20
+ throw new Error(`Usage: ${SETTINGS_USAGE}`);
21
+ switch (key) {
22
+ case 'language': {
23
+ if (value === 'system') {
24
+ setConfig('language', null);
25
+ return 'Language: English.';
26
+ }
27
+ if (!(value in LANGUAGES))
28
+ throw new Error(`Pick one of: ${Object.keys(LANGUAGES).join(', ')}, system`);
29
+ setConfig('language', value);
30
+ return `Language: ${LANGUAGES[value]}.`;
31
+ }
32
+ case 'bedtime': {
33
+ if (value === 'off') {
34
+ setConfig('bedtime', null);
35
+ return 'Bedtime off: nothing runs at night.';
36
+ }
37
+ parseClock(value);
38
+ setConfig('bedtime', value);
39
+ // A bedtime does nothing without the 5-minute check that starts the run.
40
+ if (!agentInstalled())
41
+ installAgent();
42
+ return `Bedtime ${value}: approved cards run then.`;
43
+ }
44
+ case 'run-model': {
45
+ if (!RUN_MODELS.includes(value))
46
+ throw new Error(`Pick one of: ${RUN_MODELS.join(', ')}`);
47
+ setConfig('runModel', value === 'default' ? null : value);
48
+ return value === 'default' ? "Overnight runs use Claude Code's default model." : `Overnight runs use ${value}.`;
49
+ }
50
+ case 'keep-free': {
51
+ const n = Number(value);
52
+ if (!Number.isInteger(n) || n < 0 || n > 50)
53
+ throw new Error('Pick a whole number from 0 to 50.');
54
+ setConfig('min5hLeftPct', n);
55
+ return `A card won't start with less than ${n}% of the 5-hour window left.`;
56
+ }
57
+ default:
58
+ throw new Error(`Usage: ${SETTINGS_USAGE}`);
59
+ }
60
+ }
61
+ export function settingsText(s) {
62
+ return [
63
+ `language ${s.language ? LANGUAGES[s.language] : 'English'}`,
64
+ `bedtime ${s.bedtime ?? 'off'}`,
65
+ `run model ${s.runModel}`,
66
+ `keep free ${s.keepFreePct}% of the 5-hour window`,
67
+ `Change one: ${SETTINGS_USAGE}`,
68
+ ].join('\n');
69
+ }
package/dist/suggest.js CHANGED
@@ -5,6 +5,7 @@
5
5
  // Every task must name its source, and the source is checked against the digest, so the model can't invent one
6
6
  // (the same rule as the history cold start). Nothing runs: the cards land in Suggested for you to approve.
7
7
  import { spawnSync } from 'node:child_process';
8
+ import { inYourLanguage } from './language.js';
8
9
  import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs';
9
10
  import { basename, join } from 'node:path';
10
11
  import { addCard } from './board.js';
@@ -148,7 +149,7 @@ export async function suggestTasks(repo, runner, opts) {
148
149
  const count = opts.count ?? 5;
149
150
  const digest = repoDigest(repo, { existing: opts.existing, issues: opts.issues ?? openIssues(repo) });
150
151
  const text = opts.approvals ? `${digest.text}\n\n${opts.approvals}` : digest.text;
151
- const result = await runner.run({ prompt: suggestPrompt(text, count), cwd: opts.cwd, model: opts.model, tools: '', timeoutMs: 240_000 });
152
+ const result = await runner.run({ prompt: inYourLanguage(suggestPrompt(text, count)), cwd: opts.cwd, model: opts.model, tools: '', timeoutMs: 240_000 });
152
153
  if (result.timedOut)
153
154
  throw new Error('Suggesting tasks timed out. Try again.');
154
155
  if (result.exitCode !== 0)
package/dist/taste.js CHANGED
@@ -440,13 +440,19 @@ export async function distill(board, runner, opts) {
440
440
  .flatMap((p) => p.evidence.map((e) => byId.get(e)).filter(Boolean));
441
441
  const shown = [...new Map([...context, ...fresh].map((s) => [s.id, s])).values()].sort((a, b) => Number(a.id.slice(1)) - Number(b.id.slice(1)));
442
442
  const result = await runner.run({ prompt: distillPrompt(shown, store.prefs), cwd: opts.cwd, model: opts.model, tools: '', timeoutMs: 180_000 });
443
- if (result.timedOut)
444
- throw new Error('The distiller timed out.');
445
- if (result.exitCode !== 0)
446
- throw new Error(`claude exited with ${result.exitCode}: ${result.stderr.trim().slice(0, 300)}`);
443
+ if (result.timedOut || result.exitCode !== 0) {
444
+ const message = result.timedOut ? 'The distiller timed out.' : `claude exited with ${result.exitCode}: ${result.stderr.trim().slice(0, 300)}`;
445
+ // Remember the failure, and why, so the next tick doesn't spend the same call again (distillDue).
446
+ store.lastDistillFailAt = opts.now.toISOString();
447
+ store.lastDistillError = `${message}${result.timedOut && result.stderr.trim() ? ` stderr: ${result.stderr.trim().slice(-500)}` : ''}`;
448
+ saveStore(store);
449
+ throw new Error(message);
450
+ }
447
451
  const changes = applyDistill(store, parseJson(result.output), shown, opts.now);
448
452
  store.seenThrough = Math.max(store.seenThrough ?? 0, ...signals.map((s) => Number(s.id.slice(1))));
449
453
  store.lastDistillAt = opts.now.toISOString();
454
+ delete store.lastDistillFailAt;
455
+ delete store.lastDistillError;
450
456
  saveStore(store);
451
457
  syncTasteFile(opts.now);
452
458
  return { changes, read: fresh.length };
@@ -579,6 +585,8 @@ export function formatPrefs(store, signals) {
579
585
  out.push('', `Why: chompyy taste why <id> · answer: taste yes|not-now|never <id> · retire: taste retire <id>`);
580
586
  if (store.lastDistillAt)
581
587
  out.push(`Last distilled ${store.lastDistillAt.slice(0, 16).replace('T', ' ')}.`);
588
+ if (store.lastDistillFailAt)
589
+ out.push(`Last try failed ${store.lastDistillFailAt.slice(0, 16).replace('T', ' ')}: ${store.lastDistillError ?? 'no reason saved'} It tries again next night, or run \`chompyy distill\` now.`);
582
590
  return out.join('\n');
583
591
  }
584
592
  /** "Why do you think that?": every card, edit and quote behind a preference. */
@@ -616,9 +624,14 @@ export function tasteChangesSince(store, since) {
616
624
  };
617
625
  }
618
626
  /** Distill only when there is something new and it hasn't run in a while. */
627
+ /** After a failed distil, wait this long before trying again on its own (about a night). */
628
+ export const RETRY_AFTER_FAIL_MS = 12 * 3600_000;
619
629
  export function distillDue(board, now, minGapMs = 6 * 3600_000) {
620
630
  const store = loadStore();
621
631
  if (store.lastDistillAt && now.getTime() - Date.parse(store.lastDistillAt) < minGapMs)
622
632
  return false;
633
+ // A failed try waits for the next night: the Dec 5 night retried a hanging call every 8 minutes.
634
+ if (store.lastDistillFailAt && now.getTime() - Date.parse(store.lastDistillFailAt) < RETRY_AFTER_FAIL_MS)
635
+ return false;
623
636
  return newSignals(store, readSignals(), governedCards(board.cards)).length > 0;
624
637
  }
package/dist/workspace.js CHANGED
@@ -93,9 +93,13 @@ export function prepareWorkspace(card, opts = {}) {
93
93
  const root = gitRoot(card.cwd);
94
94
  const branch = plan.branch;
95
95
  const gitDir = git(root, ['rev-parse', '--path-format=absolute', '--git-common-dir']);
96
- // A rerun keeps working in the same worktree, from the same base as before.
97
- if (existsSync(plan.dir))
98
- return { ...plan, gitDir, ...(card.run?.base ? { base: card.run.base } : {}) };
96
+ // A rerun keeps working in the same worktree. It may be days old (a card that waited on your answer), so it
97
+ // first catches up with the latest main when that merges cleanly (#49 resumed on a 4-day-old start, Dec 5).
98
+ if (existsSync(plan.dir)) {
99
+ const caught = catchUp(root, plan.dir, gitDir, card, opts.fetch ?? true);
100
+ const base = caught.base ?? card.run?.base;
101
+ return { ...plan, gitDir, ...(base ? { base } : {}), caughtUp: caught.note };
102
+ }
99
103
  // Same code as prompting Claude directly: a new card starts from the latest main (fetched), not from whatever
100
104
  // this folder has checked out. On a rerun after the folder was removed, it reuses its branch.
101
105
  const base = latestMain(root, opts.fetch ?? true);
@@ -106,6 +110,27 @@ export function prepareWorkspace(card, opts = {}) {
106
110
  const setup = setupDependencies(root, plan.dir, repoKey, { env: { npm_config_cache: homePath('cache', 'tools', 'npm') } });
107
111
  return { ...plan, gitDir, base: { ref: base.ref, commit: base.commit, branch: local === 'HEAD' ? '' : local }, setup };
108
112
  }
113
+ /**
114
+ * Merge the latest main into an existing copy, so a resumed card works on today's code. Only when the copy has no
115
+ * uncommitted work and the merge is clean; otherwise the copy stays as it was (Keep's refresh handles clashes later).
116
+ */
117
+ function catchUp(root, dir, gitDir, card, fetch) {
118
+ restoreGitLink(dir, gitDir); // never run git through a link the agent could have changed (#24)
119
+ if (uncommittedWork(dir).length)
120
+ return { note: 'left as it was: it has uncommitted work' };
121
+ const latest = latestMain(root, fetch);
122
+ const branch = latest.ref.replace(/^origin\//, '');
123
+ const base = { ref: latest.ref, commit: latest.commit, branch: branch === 'HEAD' ? '' : branch };
124
+ const short = latest.commit.slice(0, 7);
125
+ if (tryGit(dir, ['merge-base', '--is-ancestor', latest.commit, 'HEAD']) !== null)
126
+ return { base, note: `already has ${branch} @ ${short}` };
127
+ const ident = ['-c', 'user.name=Chompyy', '-c', 'user.email=chompyy@localhost'];
128
+ if (tryGit(dir, [...ident, 'merge', '--no-edit', '-m', `Bring Chompyy card #${card.id} up to date with ${branch}`, latest.commit]) !== null) {
129
+ return { base, note: `brought up to date with ${branch} @ ${short}` };
130
+ }
131
+ tryGit(dir, ['merge', '--abort']);
132
+ return { note: `left on its old start: the latest ${branch} clashes with it` };
133
+ }
109
134
  /** Files a run may leave that never belong in the user's repo. */
110
135
  export const NEVER_COMMIT = ['QUESTIONS.md', '.claude'];
111
136
  /** OS clutter that appears when you open the card's copy in Finder or Explorer; never committed. */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "chompyy",
3
- "version": "0.7.1",
3
+ "version": "0.8.0",
4
4
  "description": "Chompyy: runs the tasks you approve with the Claude Code 5-hour window you'd otherwise lose, then lets you review, keep and send them to GitHub. CLI behind the Chompyy Mac menu bar app.",
5
5
  "keywords": [
6
6
  "claude-code",