chompyy 0.7.0 → 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`) |
@@ -57,3 +57,31 @@ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
57
57
  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
58
58
  SOFTWARE.
59
59
  ```
60
+
61
+ `cli/src/stuck.ts`: the error kinds are adapted from `ERROR_PATTERNS` in [sniffly](https://github.com/chiphuyen/sniffly) (`sniffly/core/constants.py`, MIT, Copyright (c) 2025 Chip Huyen), regrouped and reworded.
62
+
63
+ Its licence, in full:
64
+
65
+ ```
66
+ MIT License
67
+
68
+ Copyright (c) 2025 Chip Huyen
69
+
70
+ Permission is hereby granted, free of charge, to any person obtaining a copy
71
+ of this software and associated documentation files (the "Software"), to deal
72
+ in the Software without restriction, including without limitation the rights
73
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
74
+ copies of the Software, and to permit persons to whom the Software is
75
+ furnished to do so, subject to the following conditions:
76
+
77
+ The above copyright notice and this permission notice shall be included in all
78
+ copies or substantial portions of the Software.
79
+
80
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
81
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
82
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
83
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
84
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
85
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
86
+ SOFTWARE.
87
+ ```
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
@@ -4,13 +4,13 @@ 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, writeFileSync } from 'node:fs';
7
- import { resolve } from 'node:path';
7
+ import { join, resolve } from 'node:path';
8
8
  import { parseArgs } from 'node:util';
9
9
  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';
@@ -39,7 +41,7 @@ import { approvalsPrompt, approvalStats, approvalsText, decisions, featureStats,
39
41
  import { allWindowEnds, archiveWindowEnds, premise, premiseText } from './premise.js';
40
42
  import { keychainAllowed, loadLiveState, refreshLiveQuota } from './livequota.js';
41
43
  import { recentProjects } from './projects.js';
42
- import { cliVersion, installApp } from './macapp.js';
44
+ import { cliVersion, installApp, installedVersion, isNewer } from './macapp.js';
43
45
  import { buildDigest, historyRetention, scanHistory } from './history.js';
44
46
  import { acceptColdStart, forgetColdStart, formatColdStart, loadColdStart, runColdStart } from './coldstart.js';
45
47
  import { keepHistory } from './claudesettings.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' },
@@ -810,9 +811,14 @@ async function main(argv) {
810
811
  return console.log(formatLive(loadLive()));
811
812
  }
812
813
  case 'app': {
813
- console.log(`Downloading Chompyy ${cliVersion()} for Mac…`);
814
- const at = await installApp();
815
- console.log(`Installed ${at} and opened it. Look for the cookie in your menu bar.`);
814
+ const have = installedVersion(join(homedir(), 'Applications'));
815
+ if (!have || !isNewer(have, cliVersion()))
816
+ console.log(`Downloading Chompyy ${cliVersion()} for Mac…`);
817
+ const r = await installApp();
818
+ if (r.kept)
819
+ console.log(`Opened Chompyy ${r.kept}. Kept it: this chompyy command is older (${cliVersion()}).\nUpdate the command: npm install -g chompyy@latest`);
820
+ else
821
+ console.log(`Installed ${r.at} and opened it. Look for the cookie in your menu bar.`);
816
822
  return;
817
823
  }
818
824
  case 'history': {
@@ -1077,59 +1083,6 @@ async function main(argv) {
1077
1083
  return;
1078
1084
  }
1079
1085
  case 'blueprint': {
1080
- if (values['all-later']) {
1081
- await freshQuota();
1082
- if (!claudeAvailable(loadConfig().claudeBin))
1083
- throw new Error('claude CLI not found: drafting needs it.');
1084
- // Same rule as background drafting (card #20): with 0% left, every draft would only hit the limit.
1085
- const waiting = quotaEmpty(now);
1086
- if (waiting) {
1087
- updateBoard((b) => claimDrafts(b, now, waiting)); // marks the later cards "waiting for quota"
1088
- console.log(`Nothing drafted: ${waiting}. They draft on their own once quota is back.`);
1089
- return;
1090
- }
1091
- const plan = draftAllPlan(loadBoard(), windowActive(now), now);
1092
- if (!plan.ids.length) {
1093
- console.log(plan.message);
1094
- return;
1095
- }
1096
- // Mark them all first so background drafting and the app don't start a second draft of the same card.
1097
- updateBoard((b) => {
1098
- for (const id of plan.ids)
1099
- getCard(b, id).draftingAt = new Date().toISOString();
1100
- });
1101
- const failed = [];
1102
- for (const [i, id] of plan.ids.entries()) {
1103
- updateBoard((b) => {
1104
- getCard(b, id).draftingAt = new Date().toISOString(); // fresh, so a long queue doesn't look stale
1105
- });
1106
- if (!values.quiet)
1107
- console.log(`Drafting #${id} (${i + 1} of ${plan.ids.length})…`);
1108
- try {
1109
- await blueprintCard(id, values.model); // a failure is kept on the card as blueprintError
1110
- }
1111
- catch (err) {
1112
- const message = err instanceof Error ? err.message : String(err);
1113
- if (isUsageLimit(message)) {
1114
- // Out of quota mid-way: the rest would fail the same way. They wait for the reset instead (card #20).
1115
- const left = plan.ids.slice(i + 1);
1116
- updateBoard((b) => { for (const l of left)
1117
- delete getCard(b, l).draftingAt; claimDrafts(b, new Date(), quotaEmpty(new Date()) ?? 'waiting for quota: the usage limit was hit'); });
1118
- 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.`);
1119
- process.exitCode = i === 0 ? 1 : 0;
1120
- return;
1121
- }
1122
- failed.push(id);
1123
- if (!values.quiet)
1124
- console.log(` #${id} failed: ${message}`);
1125
- }
1126
- }
1127
- const done = plan.ids.length - failed.length;
1128
- 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)` : ''}.`);
1129
- if (done === 0)
1130
- process.exitCode = 1;
1131
- return;
1132
- }
1133
1086
  const id = need(args[0], 'chompyy blueprint <id> [--model haiku]');
1134
1087
  const text = await blueprintCard(id, values.model);
1135
1088
  if (!values.quiet)
@@ -1300,7 +1253,10 @@ async function main(argv) {
1300
1253
  const line = { offer: `Leave it to me tonight? ${cap.cards} card(s) could run at ${cap.bedtime}: chompyy nightcap on ${cap.bedtime}`,
1301
1254
  armed: `Tonight at ${cap.bedtime}: ${cap.cards} card(s) run while you sleep. Skip: chompyy nightcap skip`,
1302
1255
  skipped: `Skipping tonight. Back on: chompyy nightcap unskip`, running: 'Running your cards. Sleep well.' }[cap.phase];
1303
- return console.log(`🌙 ${line}`);
1256
+ console.log(`🌙 ${line}`);
1257
+ if (cap.room)
1258
+ console.log(` ${roomLine(cap.cards, cap.room)}`);
1259
+ return;
1304
1260
  }
1305
1261
  case 'demon': {
1306
1262
  // Demon mode: run approved cards in the last hour of a window that would otherwise reset unused.
@@ -1332,6 +1288,14 @@ async function main(argv) {
1332
1288
  console.log(`Every window: ${auto ? 'on' : 'off (chompyy demon on)'}`);
1333
1289
  return;
1334
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
+ }
1335
1299
  case 'bedtime': {
1336
1300
  const v = need(args[0], 'chompyy bedtime <23:30|off>');
1337
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');
package/dist/detect.js CHANGED
@@ -8,6 +8,7 @@ import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs';
8
8
  import { homedir } from 'node:os';
9
9
  import { basename, dirname, join } from 'node:path';
10
10
  import { projectsDir } from './dream.js';
11
+ import { errorKind, ruleStuck } from './stuck.js';
11
12
  /**
12
13
  * Folders under ~/.claude/projects made by automated runs in temp folders (benchmarks, sandboxes, Chompyy's own
13
14
  * cards): not your sessions, so they don't count for or against you.
@@ -21,11 +22,15 @@ export function readSession(file) {
21
22
  const skills = new Map();
22
23
  const commands = new Map();
23
24
  const mcp = new Map();
25
+ const errors = new Map();
26
+ let failed = 0;
27
+ let interrupts = 0;
24
28
  // What changed since the last request: read back when the next request says the tool list changed.
25
29
  let loaded = [];
26
30
  let after = '';
27
31
  for (const line of readFileSync(file, 'utf8').split('\n')) {
28
- if (!line.includes('"assistant"') && !line.includes('<command-name>') && !line.includes('deferred_tools_record'))
32
+ const stuckLine = line.includes('"is_error":true') || line.includes('[Request interrupted');
33
+ if (!stuckLine && !line.includes('"assistant"') && !line.includes('<command-name>') && !line.includes('deferred_tools_record'))
29
34
  continue;
30
35
  let e;
31
36
  try {
@@ -54,6 +59,21 @@ export function readSession(file) {
54
59
  after = `/${m[1]}`;
55
60
  }
56
61
  }
62
+ if (stuckLine && e.type === 'user' && !e.isSidechain) {
63
+ const blocks = typeof content === 'string' ? [{ type: 'text', text: content }] : Array.isArray(content) ? content : [];
64
+ for (const b of blocks) {
65
+ if (b?.type === 'text' && typeof b.text === 'string' && b.text.startsWith('[Request interrupted'))
66
+ interrupts += 1;
67
+ if (b?.type !== 'tool_result' || b.is_error !== true)
68
+ continue;
69
+ failed += 1;
70
+ const text = typeof b.content === 'string' ? b.content : Array.isArray(b.content) ? b.content.map((x) => (typeof x?.text === 'string' ? x.text : '')).join(' ') : '';
71
+ const kind = errorKind(text.slice(0, 2000));
72
+ if (kind)
73
+ errors.set(kind, (errors.get(kind) ?? 0) + 1);
74
+ }
75
+ continue;
76
+ }
57
77
  if (e.type !== 'assistant' || !msg?.usage || e.isSidechain)
58
78
  continue;
59
79
  if (Array.isArray(content)) {
@@ -102,7 +122,7 @@ export function readSession(file) {
102
122
  cwd,
103
123
  turns: [...turns.values()].filter((t) => t.at).sort((a, b) => a.at - b.at),
104
124
  };
105
- return Object.assign(session, { skills, commands, mcp });
125
+ return Object.assign(session, { skills, commands, mcp, errors, failed, interrupts });
106
126
  }
107
127
  const sessionMemo = new Map();
108
128
  /** Your sessions from the last `days` days (by file time), automated runs left out. */
@@ -110,7 +130,7 @@ export function scan(opts = {}) {
110
130
  const now = (opts.now ?? new Date()).getTime();
111
131
  const since = now - (opts.days ?? 30) * 86_400_000;
112
132
  const root = opts.root ?? projectsDir();
113
- const out = { sessions: [], skills: new Map(), commands: new Map(), mcp: new Map(), firstAt: Infinity, lastAt: 0 };
133
+ const out = { sessions: [], skills: new Map(), commands: new Map(), mcp: new Map(), firstAt: Infinity, lastAt: 0, errors: new Map(), failed: 0, interrupts: 0 };
114
134
  if (!existsSync(root))
115
135
  return { ...out, firstAt: 0 };
116
136
  for (const folder of readdirSync(root)) {
@@ -151,6 +171,10 @@ export function scan(opts = {}) {
151
171
  out.skills.set(k, (out.skills.get(k) ?? 0) + v);
152
172
  for (const [k, v] of s.commands)
153
173
  out.commands.set(k, (out.commands.get(k) ?? 0) + v);
174
+ for (const [k, v] of s.errors)
175
+ out.errors.set(k, (out.errors.get(k) ?? 0) + v);
176
+ out.failed += s.failed;
177
+ out.interrupts += s.interrupts;
154
178
  for (const [k, v] of s.mcp) {
155
179
  const m = out.mcp.get(k) ?? { calls: 0, projects: new Set() };
156
180
  m.calls += v;
@@ -514,6 +538,7 @@ export function detect(opts = {}) {
514
538
  ...ruleS2(s, opts.claudeDir),
515
539
  ...ruleS4(s, servers),
516
540
  ...ruleS5(opts.root),
541
+ ...ruleStuck(s),
517
542
  ];
518
543
  // Baselines for the checks advice cards register before a fix: what a session start costs, and last week's cold returns.
519
544
  const starts = s.sessions.map((x) => x.turns[0]).map((t) => t.cacheRead + t.cacheWrite).filter((n) => n > 0);
@@ -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/macapp.js CHANGED
@@ -32,11 +32,42 @@ const defaultDeps = () => ({
32
32
  platform: process.platform,
33
33
  appsDir: join(homedir(), 'Applications'),
34
34
  });
35
- /** Install (or update) Chompyy.app. Returns where it went. */
35
+ /** The version in an installed Chompyy.app's Info.plist, or null when there's no app or no readable version. */
36
+ export function installedVersion(appsDir) {
37
+ try {
38
+ const plist = readFileSync(join(appsDir, 'Chompyy.app', 'Contents', 'Info.plist'), 'utf8');
39
+ return plist.match(/<key>CFBundleShortVersionString<\/key>\s*<string>([^<]+)<\/string>/)?.[1]?.trim() ?? null;
40
+ }
41
+ catch {
42
+ return null;
43
+ }
44
+ }
45
+ /** True when version `a` is newer than `b` (plain x.y.z; a missing part counts as 0). */
46
+ export function isNewer(a, b) {
47
+ const pa = a.split('.').map((n) => parseInt(n, 10) || 0);
48
+ const pb = b.split('.').map((n) => parseInt(n, 10) || 0);
49
+ for (let i = 0; i < Math.max(pa.length, pb.length); i++) {
50
+ const d = (pa[i] ?? 0) - (pb[i] ?? 0);
51
+ if (d)
52
+ return d > 0;
53
+ }
54
+ return false;
55
+ }
56
+ /**
57
+ * Install (or update) Chompyy.app. Returns where it is, and `kept` when a newer app was already there:
58
+ * an old `chompyy` command once replaced a 0.7.0 app with 0.5.0, so a newer app is opened as it is, never downgraded.
59
+ */
36
60
  export async function installApp(opts = {}, deps = defaultDeps()) {
37
61
  if (deps.platform !== 'darwin')
38
62
  throw new Error('The Chompyy app is macOS only for now. The CLI works everywhere: `chompyy help`.');
39
63
  const version = opts.version ?? cliVersion();
64
+ const have = installedVersion(deps.appsDir);
65
+ if (have && isNewer(have, version)) {
66
+ const at = join(deps.appsDir, 'Chompyy.app');
67
+ if (opts.open !== false)
68
+ deps.exec('open', [at]);
69
+ return { at, kept: have };
70
+ }
40
71
  const url = appZipUrl(version);
41
72
  const res = await deps.fetch(url);
42
73
  if (!res.ok)
@@ -73,7 +104,7 @@ export async function installApp(opts = {}, deps = defaultDeps()) {
73
104
  renameSync(unpacked, target);
74
105
  if (opts.open !== false)
75
106
  deps.exec('open', [target]);
76
- return target;
107
+ return { at: target };
77
108
  }
78
109
  finally {
79
110
  rmSync(tmp, { recursive: true, force: true });
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/stuck.js ADDED
@@ -0,0 +1,36 @@
1
+ export const KINDS = [
2
+ { id: 'rejected', label: 'actions you turned down', re: /user doesn't want to (proceed|take this action)|\[Request interrupted/i, fix: 'Say what you want up front, or put the rule in CLAUDE.md: you turned these down after Claude started them.' },
3
+ { id: 'not-read', label: 'writes before reading the file', re: /File has not been read yet/i, fix: 'Ask Claude to read a file before it edits it.' },
4
+ { id: 'stale', label: 'edits on stale text', re: /File has been modified since read|String to replace not found|String not found in file|replace_all is false/i, fix: 'Have Claude read the file again before editing: the text it tried to replace had changed or appears twice.' },
5
+ { id: 'path', label: 'wrong paths', re: /No such file or directory|File does not exist|ENOENT|No module named|Cannot find module/i, fix: 'Have Claude list the folder before opening files, or add the project layout to CLAUDE.md.' },
6
+ { id: 'blocked', label: 'blocked by permissions', re: /Permission denied|was blocked|Operation not permitted|not allowed/i, fix: 'Allow the commands you trust with /permissions, or tell Claude in CLAUDE.md what it may not run.' },
7
+ { id: 'missing-tool', label: 'commands not installed', re: /command not found/i, fix: 'Install the missing command, or tell Claude in CLAUDE.md what to use instead.' },
8
+ { id: 'timeout', label: 'timeouts', re: /timed out/i, fix: 'Ask Claude to run long commands in the background.' },
9
+ { id: 'input', label: 'malformed tool calls', re: /InputValidationError|SyntaxError|syntax error|jq: error/i, fix: 'Mostly the model\'s slip: nothing to change unless one tool keeps failing.' },
10
+ ];
11
+ /** The kind of one failed tool call's text; null when no pattern names it (a plain non-zero exit, say). */
12
+ export function errorKind(text) {
13
+ return KINDS.find((k) => k.re.test(text))?.id ?? null;
14
+ }
15
+ /** Fewer named failures than this in the scan: not a pattern worth a line. */
16
+ export const MIN_ERRORS = 10;
17
+ /** L2 · Where Claude gets stuck. Counts, not tokens: L1 already prices recovering from failures. */
18
+ export function ruleStuck(s) {
19
+ const ranked = [...(s.errors ?? new Map())].filter(([id]) => id !== 'rejected').sort((a, b) => b[1] - a[1]);
20
+ const named = ranked.reduce((a, [, n]) => a + n, 0);
21
+ if (named < MIN_ERRORS)
22
+ return [];
23
+ const top = ranked.slice(0, 3).map(([id, n]) => `${n} ${KINDS.find((k) => k.id === id).label}`);
24
+ const turnedDown = s.errors?.get('rejected') ?? 0;
25
+ const stopped = (s.interrupts ?? 0) + turnedDown;
26
+ const fix = KINDS.find((k) => k.id === ranked[0][0]).fix;
27
+ return [{
28
+ rule: 'L2',
29
+ title: 'Where Claude gets stuck',
30
+ say: `${s.failed ?? named} failed tool calls. Most named: ${top.join(', ')}.${stopped ? ` You stopped or turned down Claude ${stopped} times.` : ''}`,
31
+ basis: 'measured',
32
+ notProve: 'Counts what failed, not what it cost; some failures are quick tries.',
33
+ fix,
34
+ lane: 'habit',
35
+ }];
36
+ }
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.0",
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",