chompyy 0.4.4 → 0.4.6

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
@@ -132,9 +132,9 @@ Each card in a git repo runs in its own worktree at `~/.chompyy/worktrees/<id>`
132
132
  | `chompyy detect [--days 30] [--all] [--json]` | The detective: what wastes tokens in your setup and habits, from your own files. One screen: the findings ranked by tokens and the fix to start with; `--all` adds each finding's count, measured or estimated, what it doesn't prove, and every fix. A mid-session cache rebuild names its cause (e.g. Tool Search loading an MCP server's tools). Works cold with `npx chompyy detect`, nothing else installed. This version checks startup tax (long CLAUDE.md, unused skills and MCP servers, cut-off MEMORY.md) and cache (cold returns, mid-session rebuilds). Reads only; changes nothing |
133
133
  | `chompyy advise [--json]` | The detective, step 3: turns detect's findings into suggested cards on the board (the app's "Find savings"). Each card's plan shows what Chompyy saw, what it doesn't prove, the exact change and how it will check it worked. Approve a settings card (e.g. turn off a plugin you never use) and Chompyy applies it once no Claude Code session has been active for 10 minutes, backed up first; `chompyy undo <id>` puts it back if nothing changed it since. Habit cards are tracked from the day you approve; some things only you can do (claude.ai-synced skills). Dropped advice never comes back. Advice never runs on an away run |
134
134
  | `chompyy advise apply` | Apply approved settings advice now if no session has been active for 10 minutes (the app and the 5-minute tick do this on their own) |
135
- | `chompyy nudge on\|off` | Live suggestions while you work. Adds a UserPromptSubmit hook to `~/.claude/settings.json` (backed up first; your other hooks stay). When you come back to a conversation of 40k+ tokens after more than an hour, its cache has expired: the hook stops that first message once and says what sending it rebuilds, what a fresh start costs, and the cheaper ways (/clear with a note, or /compact). Send it again and it goes through. Needs a global install (`npm install -g chompyy`); away runs turn hooks off, so it never touches them |
135
+ | `chompyy nudge on\|off` | Live suggestions while you work. Adds a UserPromptSubmit hook to `~/.claude/settings.json` (backed up first; your other hooks stay). When you come back to a conversation of 40k+ tokens after more than an hour, its cache has expired: the hook stops that first message once and says what sending it rebuilds, what a fresh start costs, and the cheaper ways (/clear with a note, or /compact). Send it again and it goes through. A conversation compacted since its last reply (your /compact, or Claude Code's own while you were away) sends a summary, so it isn't stopped. Needs a global install (`npm install -g chompyy`); away runs turn hooks off, so it never touches them |
136
136
  | `chompyy nudge [--json]` | On or off, what the stops and warnings led to (compacted, left, sent anyway), the tokens not written again, and the measured trend: cold returns this week against last week. The menu panel shows the same line |
137
- | `chompyy nudge due [--json]` | Conversations 45-60 minutes into a pause, about to go cold, each reported once (only while nudge is on). The menu bar app asks every minute and sends a notification, while /compact is still cheap |
137
+ | `chompyy nudge due [--json]` | Conversations 45-60 minutes into a pause, about to go cold, each reported once (only while nudge is on). The menu bar app asks every minute and sends a notification, while /compact is still cheap. Skips conversations already compacted |
138
138
  | `chompyy triggers on\|off` | Install or remove the macOS LaunchAgent that runs `chompyy tick` every 5 minutes |
139
139
  | `chompyy bedtime <23:30\|off>` / `last-hour <on\|off>` / `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 |
140
140
 
package/dist/appstate.js CHANGED
@@ -21,6 +21,7 @@ import { planFor } from './permissions.js';
21
21
  import { loadProfile, preflightHosts } from './preflight.js';
22
22
  import { gitRoot } from './workspace.js';
23
23
  import { writeBlueprintFile } from './blueprint.js';
24
+ import { outboxes } from './send.js';
24
25
  export function cardView(card, runs = readRuns()) {
25
26
  const qPath = card.run ? join(card.run.workdir, 'QUESTIONS.md') : '';
26
27
  return {
@@ -71,10 +72,13 @@ export function appState(board, snap, config, now) {
71
72
  },
72
73
  gate: budgetGate(snap, config, now),
73
74
  cards: board.cards.map((c) => cardView(c, runs)),
75
+ /** Kept cards only on this Mac, per landing branch: the Done column's Send button. */
76
+ outbox: outboxes(board.cards),
74
77
  coldStart: coldStartState(),
75
78
  tasteQuestion: tasteQuestion(),
76
79
  taste: tasteState(),
77
80
  dream: dreamState(config, now),
81
+ pictures: config.pictures,
78
82
  triggers: { installed: agentInstalled(), lastHour: config.lastHourTrigger, bedtime: config.bedtime, ...loadTriggerState() },
79
83
  };
80
84
  }
package/dist/away.js CHANGED
@@ -264,6 +264,8 @@ export async function runCard(id, timeoutMs, deps, trigger) {
264
264
  let verified;
265
265
  let tokens;
266
266
  let log = '';
267
+ /** Unset when the run failed before the prompt was built. */
268
+ let tasteApplied;
267
269
  try {
268
270
  ws = deps.prepare(card);
269
271
  if (ws.base)
@@ -274,7 +276,9 @@ export async function runCard(id, timeoutMs, deps, trigger) {
274
276
  const granted = applyPermissions(card.permissions);
275
277
  if (card.permissions?.length)
276
278
  out(` allowed for this card: ${card.permissions.join(', ')}`);
277
- const prompt = taskPrompt(card, ws.dir, (deps.taste ?? tasteForPrompt)(), deps.repoChecks?.(card) ?? []);
279
+ const taste = (deps.taste ?? tasteForPrompt)();
280
+ tasteApplied = taste !== '';
281
+ const prompt = taskPrompt(card, ws.dir, taste, deps.repoChecks?.(card) ?? []);
278
282
  const cacheDir = homePath('cache', 'tools');
279
283
  mkdirSync(cacheDir, { recursive: true });
280
284
  const questionsPath = join(ws.dir, 'QUESTIONS.md');
@@ -388,6 +392,7 @@ export async function runCard(id, timeoutMs, deps, trigger) {
388
392
  durationMs: finishedMs - startedMs,
389
393
  ...cost,
390
394
  ...(tokens ? { tokens } : {}),
395
+ ...(tasteApplied !== undefined ? { tasteApplied } : {}),
391
396
  });
392
397
  out(` → ${status} · ${formatDuration(finishedMs - startedMs)}${cost.fiveHourPct !== null ? ` · used ${cost.fiveHourPct}% of the 5h window` : ''} · log ${logPath}`);
393
398
  return card.id;
package/dist/cli.js CHANGED
@@ -19,7 +19,7 @@ import { chompyyHome, homePath } from './home.js';
19
19
  import { loadSnapshot, mergeSnapshot, parseStatusline, saveSnapshot, statusLineText, statusText as baseStatusText, windowView } from './quota.js';
20
20
  import { loadSamples } from './pacing.js';
21
21
  import { cardsSince, formatReport, lastReportAt, markReported, morningLine, rateCard, readTaste } from './report.js';
22
- import { changedFiles, diffCard, keepCard, overlaps, questionsOf, undoCard } from './review.js';
22
+ import { approvedText, changedFiles, diffCard, keepCard, overlaps, questionsOf, undoCard } from './review.js';
23
23
  import { CappedText, ClaudeRunner, claudeAvailable } from './runner.js';
24
24
  import { branchOf, commitLeftovers, gitRoot, planWorkspace, prepareWorkspace } from './workspace.js';
25
25
  import { answerCard, appState, cardView, currentBranch, editBlueprint, editIdea, recordCliLocation } from './appstate.js';
@@ -32,7 +32,7 @@ import { buildDigest, historyRetention, scanHistory } from './history.js';
32
32
  import { acceptColdStart, forgetColdStart, formatColdStart, loadColdStart, runColdStart } from './coldstart.js';
33
33
  import { keepHistory } from './claudesettings.js';
34
34
  import { blueprintHash, drawPicture } from './picture.js';
35
- import { costRange, formatCostRange, readRuns, trendLines } from './costs.js';
35
+ import { costRange, formatCostRange, readRuns, tasteEffect, tasteEffectLine, trendLines } from './costs.js';
36
36
  import { answerPreference, distill, distillDue, formatPrefs, formatQuestion, formatWhy, getPref, loadStore, nextQuestion, readSignals, recordOutcome, retirePreference, syncTasteFile, tasteChangesSince, } from './taste.js';
37
37
  import { cachedWorkspaces, dream, dreamDue, formatDream, formatWorkspaces, projectsDir, readLogPath, setTicked } from './dream.js';
38
38
  import { byKind, compare, formatExtras, formatUsage, loadLedger, periodDays, PERIODS, prCosts, usageView } from './usage.js';
@@ -41,7 +41,10 @@ import { homedir } from 'node:os';
41
41
  import { clashOf, refreshCard, refreshGate, refreshClashing, withRefreshLock } from './refresh.js';
42
42
  import { adviseText, applyDue, approveAdvice, runAdvise, undoAdvice } from './advice.js';
43
43
  import { checkWorked, nudgeProof, nudgeProofText, shareText, workedText } from './didwork.js';
44
+ import { addSuggested, suggestTasks, suggestText } from './suggest.js';
44
45
  import { coldWarningText, hookCommand, impact, loadNudges, nudgeInstalled, nudgeText, runHook, setNudge, setProjectMode, takeGoingCold } from './nudge.js';
46
+ import { withKeepLock } from './keeplock.js';
47
+ import { sendKept } from './send.js';
45
48
  import { formatLive, keepAffectsLive, liveOff, liveSet, liveUpdateLocked, loadLive, startLiveUpdate } from './live.js';
46
49
  import { agentInstalled, awayRunning, bedtimeKey, decideTrigger, installAgent, loadTriggerState, markFired, noteTick, parseClock, takeAwayLock, uninstallAgent } from './triggers.js';
47
50
  const HELP = `chompyy: use the 5-hour window capacity that would reset unused
@@ -55,8 +58,10 @@ Quota
55
58
  chompyy advise [--json] turn detect's findings into suggested cards to approve or drop: settings changes are
56
59
  applied (backed up, undoable) once no Claude Code session is active; habits are tracked
57
60
  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
61
+ chompyy worked [--all] [--json] did it work? measure each approved advice card against the check on its card
59
62
  chompyy worked --share the same as a summary to paste (no project, skill or file names)
63
+ chompyy suggest [repo] [--force] a few tasks for a repo from its docs, issues and TODOs, as suggested cards
64
+ (one model call; waits for an active 5-hour window unless --force)
60
65
  chompyy nudge on|off live suggestions while you work: stops the first message to a big conversation
61
66
  whose cache expired, with the price and the cheaper ways (Claude Code hook)
62
67
  chompyy nudge strict|quiet|learn [dir] in this project: always stop me, only a heads-up, or learn (default:
@@ -88,6 +93,7 @@ Back
88
93
  chompyy report [--all] what ran, and the one thing to do about each
89
94
  chompyy diff <id> the change it made
90
95
  chompyy keep <id> merge its branch into the branch it started from (and update the live app, if set)
96
+ chompyy send [--json] open one PR on GitHub with every kept card GitHub's main doesn't have yet
91
97
  chompyy refresh [<id>] bring cards in review up to date with main (Chompyy does this by itself after each Keep)
92
98
  chompyy undo <id> throw it away (removes its branch; yours are untouched)
93
99
  chompyy answer <id> answer the run's questions (stdin); the card goes back to approved
@@ -98,7 +104,7 @@ Back
98
104
  chompyy five-star <id> options for "what would have made it a 5?" (JSON)
99
105
  chompyy signals [--json] everything Chompyy has recorded from you: ratings, edits, answers
100
106
  chompyy tokens [--json] exact tokens and API-value cost of each run
101
- chompyy trends last 7 days vs the 7 before: cost per card, keep rate, rating, blueprint edits
107
+ chompyy trends last 7 days vs the 7 before: cost per card, keep rate, rating, blueprint edits; keep rate with taste vs without
102
108
 
103
109
  Taste (learned from what you keep, undo, edit and rate)
104
110
  chompyy trace <id> one conversation turn by turn: cost per turn, context size, what ate the tokens
@@ -313,7 +319,11 @@ async function distillNow(now, force = false) {
313
319
  return `Read ${r.read} new signal(s): ${parts.join(', ')}${c.dropped ? ` (${c.dropped} thrown out for weak evidence)` : ''}. See \`chompyy taste list\`.`;
314
320
  }
315
321
  /** Keep a card: merge it, record it, update the live app, and bring the other cards in review up to date. */
322
+ /** Keep a card: one Keep at a time (keeplock.ts), whether you pressed it or refresh keeps a card it brought up to date. */
316
323
  function keepNow(id, now) {
324
+ withKeepLock(() => keepLocked(id, now));
325
+ }
326
+ function keepLocked(id, now) {
317
327
  const kept = getCard(loadBoard(), id);
318
328
  const files = changedFiles(kept); // read before Keep removes the branch
319
329
  console.log(keepCard(kept));
@@ -930,10 +940,7 @@ async function main(argv) {
930
940
  delete c.permissions;
931
941
  return c;
932
942
  });
933
- console.log(`✅ #${card.id} approved: ${card.title}${card.permissions?.length ? `\n allowed: ${card.permissions.join(', ')}` : ''}`);
934
- for (const o of overlaps(card, loadBoard().cards)) {
935
- console.log(` ⚠️ #${o.id} "${o.title}" may touch the same files (${o.files.slice(0, 3).join(', ')}). Keeping both can conflict; Run again fixes that.`);
936
- }
943
+ console.log(approvedText(card.id, overlaps(card, loadBoard().cards)));
937
944
  return;
938
945
  }
939
946
  case 'drop': {
@@ -1175,7 +1182,24 @@ async function main(argv) {
1175
1182
  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 });
1176
1183
  if (!cards.length && proof)
1177
1184
  return console.log(nudgeProofText(proof).join('\n'));
1178
- return console.log([workedText(cards), ...(proof ? ['', ...nudgeProofText(proof)] : [])].join('\n'));
1185
+ return console.log([workedText(cards, { all: Boolean(values.all) }), ...(proof ? ['', ...nudgeProofText(proof)] : [])].join('\n'));
1186
+ }
1187
+ case 'suggest': {
1188
+ // A few tasks for a repo, from what it wants to become and what its code shows: suggested cards to approve.
1189
+ const repo = gitRoot(resolve(args[0] ?? process.cwd()));
1190
+ if (!repo)
1191
+ throw new Error(`${args[0] ?? 'This folder'} isn't in a git repo. chompyy suggest <repo folder>`);
1192
+ const config = loadConfig();
1193
+ if (!claudeAvailable(config.claudeBin))
1194
+ throw new Error('Suggesting tasks needs the claude command (Claude Code in Terminal). See TRY.md.');
1195
+ if (!values.force && !windowActive(now))
1196
+ throw new Error('No active 5-hour window: suggesting now would start one. Try again while you use Claude Code, or add --force.');
1197
+ const existing = loadBoard().cards.map((c) => c.title);
1198
+ const { tasks, dropped } = await suggestTasks(repo, new ClaudeRunner(config.claudeBin), { model: config.suggestModel, cwd: chompyyHome(), existing });
1199
+ const cards = updateBoard((b) => addSuggested(b, repo, tasks, now));
1200
+ if (values.json)
1201
+ return json({ repo, added: cards.map((c) => ({ id: c.id, title: c.title, why: c.why })), dropped });
1202
+ return console.log(suggestText(repo, cards, dropped));
1179
1203
  }
1180
1204
  case 'hook': {
1181
1205
  // Claude Code's UserPromptSubmit hook. Must never fail loudly or stop a prompt by accident.
@@ -1223,8 +1247,11 @@ async function main(argv) {
1223
1247
  return;
1224
1248
  }
1225
1249
  case 'trends': {
1226
- const lines = trendLines(readRuns(), readSignals(), now);
1250
+ const runs = readRuns();
1251
+ const signals = readSignals();
1252
+ const lines = trendLines(runs, signals, now);
1227
1253
  console.log(lines.length ? lines.join('\n') : 'Not enough runs yet for trends (needs 3).');
1254
+ console.log(tasteEffectLine(tasteEffect(runs, signals)));
1228
1255
  return;
1229
1256
  }
1230
1257
  case 'report': {
@@ -1246,18 +1273,29 @@ async function main(argv) {
1246
1273
  }
1247
1274
  case 'keep': {
1248
1275
  const id = need(args[0], 'chompyy keep <id>');
1249
- const card = getCard(loadBoard(), id);
1250
- const clash = clashOf(card);
1251
- if (clash) {
1252
- // Don't hand the clash to you: Chompyy brings the card onto the new main, checks it, then keeps it (refresh.ts).
1253
- updateBoard((b) => {
1254
- getCard(b, id).keepWhenRefreshed = true;
1255
- });
1256
- startBackground(['refresh', '--clashing'], 'refresh.log');
1257
- console.log(`#${id} clashes with ${clash.branch} (${clash.files.join(', ')}): other cards were kept since it ran. Chompyy is bringing it up to date and will keep it once its checks pass.`);
1258
- return;
1259
- }
1260
- keepNow(id, now);
1276
+ // The clash check reads main too, so it waits behind a Keep that is still changing main.
1277
+ withKeepLock(() => {
1278
+ const card = getCard(loadBoard(), id);
1279
+ if (card.outcome === 'kept')
1280
+ return console.log(`#${id} is already kept.`);
1281
+ const clash = clashOf(card);
1282
+ if (clash) {
1283
+ // Don't hand the clash to you: Chompyy brings the card onto the new main, checks it, then keeps it (refresh.ts).
1284
+ updateBoard((b) => {
1285
+ getCard(b, id).keepWhenRefreshed = true;
1286
+ });
1287
+ startBackground(['refresh', '--clashing'], 'refresh.log');
1288
+ console.log(`#${id} clashes with ${clash.branch} (${clash.files.join(', ')}): other cards were kept since it ran. Chompyy is bringing it up to date and will keep it once its checks pass.`);
1289
+ return;
1290
+ }
1291
+ keepNow(id, now);
1292
+ });
1293
+ return;
1294
+ }
1295
+ case 'send': {
1296
+ // Kept cards live on your local main only; this opens (or updates) one PR with them. Main itself is never pushed.
1297
+ const sent = sendKept(loadBoard().cards);
1298
+ console.log(args.includes('--json') ? JSON.stringify(sent) : sent.message);
1261
1299
  return;
1262
1300
  }
1263
1301
  case 'refresh': {
package/dist/config.js CHANGED
@@ -4,6 +4,7 @@ export const DEFAULT_CONFIG = {
4
4
  claudeBin: 'claude',
5
5
  blueprintModel: 'haiku',
6
6
  coldStartModel: 'sonnet',
7
+ suggestModel: 'sonnet',
7
8
  pictures: true,
8
9
  pictureModel: 'sonnet',
9
10
  runModel: null,
package/dist/costs.js CHANGED
@@ -160,3 +160,46 @@ export function trendLines(runs, signals, now, days = 7) {
160
160
  bits.push(`~${fmtPct(all.costPerRun)}% of a 5h window per card`);
161
161
  return [`📈 So far: ${bits.join(' · ')} (trends once there are two weeks to compare)`];
162
162
  }
163
+ /**
164
+ * Keep rate split by whether taste.md was in the prompt. The last decision per card counts (as periodStats),
165
+ * matched to that card's latest run at or before the decision. Decided cards with no run are left out.
166
+ */
167
+ export function tasteEffect(runs, signals) {
168
+ const decided = new Map();
169
+ for (const s of signals)
170
+ if (s.kind === 'outcome' && s.card)
171
+ decided.set(s.card, { outcome: String(s.raw.outcome), at: Date.parse(s.at) });
172
+ const group = () => ({ n: 0, kept: 0, undone: 0, keepRate: null });
173
+ const out = { withTaste: group(), withoutTaste: group(), unrecorded: group() };
174
+ for (const [card, d] of decided) {
175
+ if (d.outcome !== 'kept' && d.outcome !== 'undone')
176
+ continue;
177
+ let last;
178
+ for (const r of runs) {
179
+ if (r.card !== card || Date.parse(r.at) > d.at)
180
+ continue;
181
+ if (!last || Date.parse(r.at) >= Date.parse(last.at))
182
+ last = r;
183
+ }
184
+ if (!last)
185
+ continue;
186
+ const g = last.tasteApplied === true ? out.withTaste : last.tasteApplied === false ? out.withoutTaste : out.unrecorded;
187
+ g.n++;
188
+ if (d.outcome === 'kept')
189
+ g.kept++;
190
+ else
191
+ g.undone++;
192
+ }
193
+ for (const g of [out.withTaste, out.withoutTaste, out.unrecorded])
194
+ g.keepRate = g.n ? g.kept / g.n : null;
195
+ return out;
196
+ }
197
+ /** One line for `chompyy trends`: both keep rates, or "not enough data" while a group is under MIN_POINTS. */
198
+ export function tasteEffectLine(e) {
199
+ const old = e.unrecorded.n ? ` · ${e.unrecorded.n} older card${e.unrecorded.n === 1 ? '' : 's'} not counted` : '';
200
+ if (e.withTaste.n < MIN_POINTS || e.withoutTaste.n < MIN_POINTS) {
201
+ return `Taste effect: not enough data (need ${MIN_POINTS}+ decided cards per group; with taste ${e.withTaste.n}, without ${e.withoutTaste.n})${old}`;
202
+ }
203
+ const pct = (g) => `${Math.round(g.keepRate * 100)}%`;
204
+ return `Taste effect: keep rate with taste ${pct(e.withTaste)} (n=${e.withTaste.n}) vs without ${pct(e.withoutTaste)} (n=${e.withoutTaste.n})${old}`;
205
+ }
package/dist/didwork.js CHANGED
@@ -360,20 +360,22 @@ export function nudgeProofText(p) {
360
360
  }
361
361
  const ICON = { 'too-early': '⏳', worked: '✅', short: '🟡', 'no-change': '➖', worse: '🔻', 'cant-tell': '❔' };
362
362
  /** One screen: each fix, its verdict, and the saving by method (never added across methods). */
363
- export function workedText(cards) {
363
+ export function workedText(cards, opts = {}) {
364
364
  if (!cards.length)
365
365
  return 'Nothing to measure yet. Approve an advice card: chompyy advise';
366
366
  const lines = [];
367
- for (const c of cards) {
367
+ // Five at most on one screen (cli/STYLE.md), losses first so a cut never hides one; the totals still count every card.
368
+ const shown = cards.filter((c) => c.advice.result).sort((a, b) => Number(b.advice.result.verdict === 'worse') - Number(a.advice.result.verdict === 'worse'));
369
+ for (const c of shown.slice(0, opts.all ? undefined : 5)) {
368
370
  const r = c.advice.result;
369
- if (!r)
370
- continue;
371
371
  lines.push(`${ICON[r.verdict]} #${c.id} ${c.title}`, ` ${r.line}`);
372
372
  if (r.also)
373
373
  lines.push(` ${r.also}`);
374
374
  if (r.verdict === 'worse' && c.advice.lane === 'settings')
375
375
  lines.push(` Put it back: chompyy undo ${c.id}`);
376
376
  }
377
+ if (!opts.all && shown.length > 5)
378
+ lines.push(` …and ${shown.length - 5} more: chompyy worked --all`);
377
379
  const recount = cards.map((c) => c.advice.result).filter((r) => r?.method === 'recount' && r.per === 'session start' && r.saved !== undefined && r.verdict !== 'cant-tell');
378
380
  const weekly = cards.map((c) => c.advice.result).filter((r) => r?.method === 'before-after' && r.per === 'week' && r.saved !== undefined);
379
381
  if (recount.length || weekly.length)
@@ -0,0 +1,72 @@
1
+ // One Keep at a time (2026-11-30): Keep merges into the folder that has main open. Three Keeps pressed within
2
+ // 15 seconds (#31, #39, #37) ran at once there; #37's stopped halfway and left that folder mid-merge, with a
3
+ // staged README that would have undone #39. Keeps now wait in line: each takes this lock, and a second one
4
+ // waits for the first to finish instead of merging alongside it.
5
+ import { closeSync, openSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs';
6
+ import { homePath } from './home.js';
7
+ /** How long a Keep waits for the one ahead of it. Keeps take seconds; this only catches a stuck one. */
8
+ export const KEEP_WAIT_MS = 3 * 60_000;
9
+ const sleep = (ms) => Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
10
+ const alive = (pid) => {
11
+ if (!pid)
12
+ return false;
13
+ try {
14
+ process.kill(pid, 0);
15
+ return true;
16
+ }
17
+ catch (e) {
18
+ // EPERM: it exists, it just isn't ours.
19
+ return e.code === 'EPERM';
20
+ }
21
+ };
22
+ /** Held by this process already (refresh keeps a card from inside its own Keep): don't wait on yourself. */
23
+ let depth = 0;
24
+ /** Run `fn` holding the Keep lock, waiting up to `waitMs` for another Keep to finish. A dead holder's lock is taken over. */
25
+ export function withKeepLock(fn, opts = {}) {
26
+ if (depth > 0) {
27
+ depth++;
28
+ try {
29
+ return fn();
30
+ }
31
+ finally {
32
+ depth--;
33
+ }
34
+ }
35
+ const lock = opts.lock ?? homePath('keep.lock');
36
+ const until = Date.now() + (opts.waitMs ?? KEEP_WAIT_MS);
37
+ let fd;
38
+ while (fd === undefined) {
39
+ try {
40
+ fd = openSync(lock, 'wx');
41
+ }
42
+ catch {
43
+ let holder = 0;
44
+ let age = 0;
45
+ try {
46
+ holder = Number(readFileSync(lock, 'utf8')) || 0;
47
+ age = Date.now() - statSync(lock).mtimeMs;
48
+ }
49
+ catch {
50
+ continue; // released between the two calls
51
+ }
52
+ // A dead holder, or one that never wrote its pid (it writes right after taking the lock): take it over.
53
+ if (holder ? !alive(holder) : age > 5_000) {
54
+ rmSync(lock, { force: true });
55
+ continue;
56
+ }
57
+ if (Date.now() > until)
58
+ throw new Error(`Another Keep is still running after ${Math.round((opts.waitMs ?? KEEP_WAIT_MS) / 60_000)} min, so this one stopped. Press Keep again once it finishes.`);
59
+ sleep(opts.poll ?? 200);
60
+ }
61
+ }
62
+ try {
63
+ writeFileSync(fd, String(process.pid));
64
+ depth++;
65
+ return fn();
66
+ }
67
+ finally {
68
+ depth--;
69
+ closeSync(fd);
70
+ rmSync(lock, { force: true });
71
+ }
72
+ }
package/dist/nudge.js CHANGED
@@ -85,6 +85,20 @@ function replyOf(line) {
85
85
  return null;
86
86
  }
87
87
  }
88
+ function compactionOf(line) {
89
+ if (!line.includes('"compact_boundary"'))
90
+ return null;
91
+ try {
92
+ const e = JSON.parse(line);
93
+ if (e.type !== 'system' || e.subtype !== 'compact_boundary')
94
+ return null;
95
+ const at = Date.parse(String(e.timestamp ?? ''));
96
+ return at ? { at, by: e.compactMetadata?.trigger === 'manual' ? 'you' : 'claude' } : null;
97
+ }
98
+ catch {
99
+ return null;
100
+ }
101
+ }
88
102
  /** Bytes from the start or the end of a file, without reading all of a long transcript. */
89
103
  function slice(file, bytes, fromEnd) {
90
104
  const size = statSync(file).size;
@@ -99,17 +113,24 @@ function slice(file, bytes, fromEnd) {
99
113
  }
100
114
  return buf.toString('utf8');
101
115
  }
102
- /** The conversation's last reply, and its first (about what a fresh conversation costs: tools, CLAUDE.md, memory). */
116
+ /**
117
+ * The conversation's last reply, its first (about what a fresh conversation costs: tools, CLAUDE.md, memory), and
118
+ * a compaction after the last reply, if there was one.
119
+ */
103
120
  export function replies(transcript) {
104
121
  const tail = slice(transcript, 4 << 20, true).split('\n');
105
122
  let last = null;
106
- for (let i = tail.length - 1; i >= 0 && !last; i--)
123
+ let compacted = null;
124
+ for (let i = tail.length - 1; i >= 0 && !last; i--) {
107
125
  last = replyOf(tail[i]);
126
+ if (!last)
127
+ compacted ??= compactionOf(tail[i]);
128
+ }
108
129
  let first = null;
109
130
  for (const line of slice(transcript, 2 << 20, false).split('\n'))
110
131
  if ((first = replyOf(line)))
111
132
  break;
112
- return { last, first };
133
+ return { last, first, compacted };
113
134
  }
114
135
  export function loadNudges() {
115
136
  const path = homePath('nudges.jsonl');
@@ -138,15 +159,17 @@ export function decide(input, now, events = loadNudges(), prefs = loadPrefs()) {
138
159
  return { block: false };
139
160
  let last;
140
161
  let first;
162
+ let compacted;
141
163
  try {
142
164
  if (!existsSync(transcript))
143
165
  return { block: false };
144
- ({ last, first } = replies(transcript));
166
+ ({ last, first, compacted } = replies(transcript));
145
167
  }
146
168
  catch {
147
169
  return { block: false };
148
170
  }
149
- if (!last)
171
+ // Compacted since its last reply (by you, or by Claude Code while you were away): this message sends a summary.
172
+ if (!last || compacted)
150
173
  return { block: false };
151
174
  const idleMs = now - last.at;
152
175
  if (idleMs <= COLD_AFTER_MS || last.context < MIN_CONTEXT)
@@ -226,8 +249,8 @@ export function goingCold(now = Date.now(), dir = projectsDir(), events = loadNu
226
249
  const mtime = statSync(transcript).mtimeMs;
227
250
  if (now - mtime > COLD_AFTER_MS || now - mtime < WARN_AFTER_MS - 60_000)
228
251
  continue;
229
- const { last, first } = replies(transcript);
230
- if (!last || last.context < MIN_CONTEXT)
252
+ const { last, first, compacted } = replies(transcript);
253
+ if (!last || compacted || last.context < MIN_CONTEXT)
231
254
  continue;
232
255
  const idleMs = now - last.at;
233
256
  if (idleMs < WARN_AFTER_MS || idleMs >= COLD_AFTER_MS)
@@ -272,20 +295,25 @@ export function coldWarningText(d) {
272
295
  body: `After ${at} its cache expires and coming back rewrites all ${k(d.context)}. Done with it? Do nothing.`,
273
296
  };
274
297
  }
275
- /** Read each stopped conversation after the stop: sent anyway, carried on small (compacted), or left. */
298
+ /**
299
+ * Read each stopped conversation after the stop: sent anyway, carried on small (compacted), or left. A stop that
300
+ * came after a compaction (Claude Code's own, while you were away) had nothing at stake: it isn't counted.
301
+ */
276
302
  export function outcomes(events = loadNudges()) {
277
303
  const stops = events.filter((e) => e.kind === 'stopped');
278
- return stops.map((event, i) => {
304
+ return stops.flatMap((event, i) => {
305
+ const at = Date.parse(event.at);
279
306
  const next = stops.slice(i + 1).find((s) => s.session === event.session);
280
307
  const until = next ? Date.parse(next.at) : Infinity;
281
- const wasSent = events.some((e) => e.kind === 'sent' && e.session === event.session && Date.parse(e.at) > Date.parse(event.at) && Date.parse(e.at) < until);
282
- if (wasSent)
283
- return { event, did: 'sent', saved: 0 };
284
308
  let after = null;
309
+ let compacted = null;
285
310
  try {
286
311
  for (const line of readFileSync(event.transcript, 'utf8').split('\n')) {
312
+ const c = compactionOf(line);
313
+ if (c && !compacted && c.at > at - event.idleMs && c.at < until)
314
+ compacted = c;
287
315
  const r = replyOf(line);
288
- if (r && r.at > Date.parse(event.at) && r.at < until) {
316
+ if (r && r.at > at && r.at < until) {
289
317
  after = r;
290
318
  break;
291
319
  }
@@ -294,19 +322,30 @@ export function outcomes(events = loadNudges()) {
294
322
  catch {
295
323
  /* transcript gone: count it as left */
296
324
  }
325
+ if (compacted && compacted.at < at)
326
+ return [];
327
+ // After your /compact the hook still sees the old last reply, so the next message is logged as "sent": the reply says what it cost.
328
+ const wasSent = !compacted && events.some((e) => e.kind === 'sent' && e.session === event.session && Date.parse(e.at) > at && Date.parse(e.at) < until);
329
+ if (wasSent)
330
+ return [{ event, did: 'sent', saved: 0 }];
297
331
  if (after)
298
- return { event, did: after.cacheWrite < event.context / 2 ? 'compacted' : 'sent', saved: Math.max(0, event.context - after.cacheWrite) };
299
- return { event, did: 'left', saved: Math.max(0, event.context - (event.fresh ?? 0)) };
332
+ return [{ event, did: after.cacheWrite < event.context / 2 ? 'compacted' : 'sent', saved: Math.max(0, event.context - after.cacheWrite) }];
333
+ return [{ event, did: 'left', saved: Math.max(0, event.context - (event.fresh ?? 0)) }];
300
334
  });
301
335
  }
302
336
  export function warnOutcomes(events = loadNudges()) {
303
337
  return events.filter((e) => e.kind === 'warned').map((event) => {
304
- const coldAt = Date.parse(event.coldAt ?? '') || Date.parse(event.at) + 15 * 60_000;
338
+ const at = Date.parse(event.at);
339
+ const coldAt = Date.parse(event.coldAt ?? '') || at + 15 * 60_000;
305
340
  let next = null;
341
+ let compacted = null;
306
342
  try {
307
343
  for (const line of readFileSync(event.transcript, 'utf8').split('\n')) {
344
+ const c = compactionOf(line);
345
+ if (c && !compacted && c.at > at && c.at < coldAt)
346
+ compacted = c;
308
347
  const r = replyOf(line);
309
- if (r && r.at > Date.parse(event.at)) {
348
+ if (r && r.at > at) {
310
349
  next = r;
311
350
  break;
312
351
  }
@@ -315,8 +354,13 @@ export function warnOutcomes(events = loadNudges()) {
315
354
  catch {
316
355
  /* transcript gone */
317
356
  }
357
+ if (compacted?.by === 'claude')
358
+ return { event, did: 'claude', saved: 0 };
318
359
  if (!next)
319
360
  return { event, did: 'left', saved: 0 };
361
+ // Compacted while warm: coming back later, even cold, rewrote the summary, not the whole conversation.
362
+ if (compacted)
363
+ return { event, did: 'compacted', saved: Math.max(0, event.context - next.context) };
320
364
  if (next.at >= coldAt)
321
365
  return { event, did: 'cold', saved: 0 };
322
366
  if (next.context < event.context / 2)
@@ -382,16 +426,33 @@ const groups = (s) => {
382
426
  };
383
427
  const ours = (g) => (g.hooks ?? []).some((h) => h.command?.includes(MARK));
384
428
  const nudgeInstalledBefore = (raw) => Boolean(raw?.includes(MARK));
385
- /** When live suggestions were turned on: recorded since this version; before that, the settings backup `nudge on` made, else the first event. */
429
+ /**
430
+ * When live suggestions were turned on: the "before" for did-it-work, so it must never move.
431
+ *
432
+ * Recorded at `nudge on` since 0.4.2. Older installs have only clues: the settings backup (but every later settings
433
+ * change rewrites it, so its date only moves later) and the first event. Take the earliest, and while the hook is on,
434
+ * write it down so a later change can't move it.
435
+ */
386
436
  export function nudgeOnSince(events = loadNudges(), path = settingsPath()) {
387
- const at = Date.parse(loadPrefs().onAt ?? '');
437
+ const prefs = loadPrefs();
438
+ const at = Date.parse(prefs.onAt ?? '');
388
439
  if (at)
389
440
  return at;
441
+ const clues = [];
390
442
  try {
391
- return statSync(`${path}.chompyy-backup`).mtimeMs;
443
+ clues.push(statSync(`${path}.chompyy-backup`).mtimeMs);
392
444
  }
393
445
  catch { }
394
- return events.length ? Date.parse(events[0].at) : null;
446
+ if (events.length)
447
+ clues.push(Date.parse(events[0].at));
448
+ const since = clues.filter(Number.isFinite).reduce((a, b) => (a === null ? b : Math.min(a, b)), null);
449
+ if (since !== null && nudgeInstalled(path)) {
450
+ try {
451
+ savePrefs({ ...prefs, onAt: new Date(since).toISOString() });
452
+ }
453
+ catch { }
454
+ }
455
+ return since;
395
456
  }
396
457
  export function nudgeInstalled(path = settingsPath()) {
397
458
  try {
package/dist/pacing.js CHANGED
@@ -123,6 +123,71 @@ export function formatForecast(f) {
123
123
  return 'not enough readings yet to forecast';
124
124
  }
125
125
  }
126
+ // ---------- the week: will it reset unused? ----------
127
+ //
128
+ // The 5-hour forecast says whether this window runs out. The question it can't answer: even running every
129
+ // window, does the week get used? One full 5-hour window is a share of the week that depends on your plan; it's
130
+ // read from your own readings (how far the week moved while a window moved), never assumed.
131
+ /** One full 5-hour window as % of the week, from readings in the same windows. Null until half a window of data. */
132
+ export function windowShareOfWeek(samples) {
133
+ let five = 0;
134
+ let week = 0;
135
+ for (let i = 1; i < samples.length; i++) {
136
+ const a = samples[i - 1];
137
+ const b = samples[i];
138
+ if (!a.five || !b.five || !a.week || !b.week)
139
+ continue;
140
+ if (a.five.resetsAt !== b.five.resetsAt || a.week.resetsAt !== b.week.resetsAt)
141
+ continue;
142
+ const df = b.five.usedPct - a.five.usedPct;
143
+ const dw = b.week.usedPct - a.week.usedPct;
144
+ if (df <= 0 || dw < 0)
145
+ continue;
146
+ five += df;
147
+ week += dw;
148
+ }
149
+ return five >= 50 ? (100 * week) / five : null;
150
+ }
151
+ const dayClock = (ms) => `${new Date(ms).toLocaleDateString('en-US', { weekday: 'short' })} ${clock(ms)}`;
152
+ export function weekForecast(snap, samples, now) {
153
+ const v = windowView(snap?.sevenDay, now);
154
+ if (!v.known)
155
+ return null;
156
+ const elapsed = WEEK - v.msLeft;
157
+ // Too early in the week for an average to mean anything.
158
+ if (elapsed < 12 * 3600_000)
159
+ return null;
160
+ const rate = v.usedPct / elapsed;
161
+ const projected = v.usedPct + rate * v.msLeft;
162
+ const windowPct = windowShareOfWeek(samples);
163
+ const unusedPct = Math.max(0, 100 - projected);
164
+ const windowsLeft = v.msLeft / FIVE_HOURS;
165
+ // Time runs out before the spare does: only the windows that fit count.
166
+ const timeBound = windowPct !== null && windowsLeft * windowPct < unusedPct;
167
+ const spareWindows = windowPct ? Math.min(unusedPct / windowPct, windowsLeft) : null;
168
+ const maxReachablePct = windowPct ? Math.min(100, v.usedPct + windowsLeft * windowPct) : null;
169
+ const resets = v.resetsAt * 1000;
170
+ const head = `Week ${Math.round(v.usedPct)}% used.`;
171
+ let line;
172
+ let runsOutAt;
173
+ if (projected >= 100 && rate > 0) {
174
+ runsOutAt = now.getTime() + (100 - v.usedPct) / rate;
175
+ line = `${head} At your pace it runs out ~${dayClock(runsOutAt)}, before the reset ${dayClock(resets)}.`;
176
+ }
177
+ else {
178
+ const n = spareWindows !== null ? Math.floor(spareWindows) : 0;
179
+ const windows = `${n} full 5-hour window${n === 1 ? '' : 's'}`;
180
+ line = `${head} At your pace ~${Math.round(unusedPct)}% resets unused on ${dayClock(resets)}`;
181
+ if (!timeBound)
182
+ line += n >= 1 ? `: about ${windows}.` : '.';
183
+ else if (n >= 1)
184
+ line += `. Time left for ${windows}: flat out, you'd use ~${Math.round(maxReachablePct)}% of the week.`;
185
+ else
186
+ line += '. Less than one 5-hour window left before then.';
187
+ }
188
+ const short = line.slice(head.length + 1);
189
+ return { usedPct: v.usedPct, resetsAt: v.resetsAt, unusedPct, ...(runsOutAt ? { runsOutAt } : {}), windowPct, spareWindows, maxReachablePct, line, short };
190
+ }
126
191
  // ---------- rolling daily allowance ----------
127
192
  /** The day you're in: from your last bedtime (or midnight) to the next. */
128
193
  export function dayBounds(now, bedtime) {
@@ -188,6 +253,7 @@ export function pacing(snap, samples, now, bedtime) {
188
253
  fiveHourDelta: paceDelta(snap?.fiveHour, FIVE_HOURS, now),
189
254
  weekDelta: paceDelta(snap?.sevenDay, WEEK, now),
190
255
  fiveHourForecast: forecastWindow(snap?.fiveHour, FIVE_HOURS, samples, (s) => s.five, now),
256
+ week: weekForecast(snap, samples, now),
191
257
  today: dailyAllowance(snap?.sevenDay, samples, now, bedtime),
192
258
  models,
193
259
  };
package/dist/quota.js CHANGED
@@ -2,7 +2,7 @@
2
2
  // message: if no window is active, the first message would start a new 5-hour window.
3
3
  import { formatDuration } from './duration.js';
4
4
  import { homePath, readJson, writeJson } from './home.js';
5
- import { FIVE_HOURS, WEEK, dailyAllowance, forecastWindow, formatAllowance, formatDelta, formatForecast, formatForecastShort, paceDelta, recordSample } from './pacing.js';
5
+ import { FIVE_HOURS, WEEK, dailyAllowance, forecastWindow, formatAllowance, formatDelta, formatForecast, formatForecastShort, paceDelta, recordSample, weekForecast } from './pacing.js';
6
6
  function num(v) {
7
7
  if (typeof v === 'number' && Number.isFinite(v))
8
8
  return v;
@@ -133,6 +133,9 @@ export function statusText(snap, now, opts = {}) {
133
133
  lines.push(`forecast ${formatForecast(forecastWindow(snap.fiveHour, FIVE_HOURS, opts.samples ?? [], (s) => s.five, now))}`);
134
134
  if (week.known)
135
135
  lines.push(formatAllowance(dailyAllowance(snap.sevenDay, opts.samples ?? [], now, opts.bedtime ?? null)));
136
+ const wf = weekForecast(snap, opts.samples ?? [], now);
137
+ if (wf)
138
+ lines.push(`week ${wf.short}${wf.spareWindows !== null && wf.spareWindows >= 2 ? ' Fill it: chompyy suggest <repo>' : ''}`);
136
139
  const age = now.getTime() - Date.parse(snap.capturedAt);
137
140
  const stale = !five.known;
138
141
  lines.push(`snapshot taken ${formatDuration(age)} ago${stale ? ' · STALE' : ''}`);
package/dist/review.js CHANGED
@@ -2,7 +2,7 @@
2
2
  // Every git card works on its own branch, so undo is just removing that branch.
3
3
  import { execFileSync } from 'node:child_process';
4
4
  import { existsSync, readFileSync, readdirSync, rmSync } from 'node:fs';
5
- import { join } from 'node:path';
5
+ import { basename, join } from 'node:path';
6
6
  import { homePath } from './home.js';
7
7
  import { commitLeftovers, gitRoot, uncommittedWork } from './workspace.js';
8
8
  /**
@@ -107,6 +107,24 @@ export function overlaps(card, others, changed = changedFiles) {
107
107
  })
108
108
  .filter((o) => o.files.length);
109
109
  }
110
+ /**
111
+ * What approving a run card says: two lines at most (cli/STYLE.md). Overlaps get one line, not one per card: they
112
+ * need nothing from you now, because when a Keep makes another card clash, refresh fits it onto the new main.
113
+ */
114
+ export function approvedText(id, overlapping) {
115
+ const lines = [`✅ #${id} approved. Runs when you're away.`];
116
+ if (overlapping.length) {
117
+ const count = new Map();
118
+ for (const o of overlapping)
119
+ for (const f of new Set(o.files))
120
+ count.set(f, (count.get(f) ?? 0) + 1);
121
+ const top = [...count.entries()].sort((a, b) => b[1] - a[1]).map(([f]) => basename(f));
122
+ const files = top.length > 2 ? `${top.slice(0, 2).join(', ')} and more` : top.join(' and ');
123
+ const n = overlapping.length;
124
+ lines.push(`Shares ${files} with ${n} waiting card${n === 1 ? '' : 's'}. If they clash at Keep, Chompyy fits them together.`);
125
+ }
126
+ return lines.join('\n');
127
+ }
110
128
  export function diffCard(card) {
111
129
  const run = ran(card);
112
130
  if (!run.branch)
package/dist/send.js ADDED
@@ -0,0 +1,240 @@
1
+ // Send kept cards (2026-11-30). Keep merges a card into your local main and stops there, so kept work only
2
+ // reached GitHub when someone pushed it by hand (five cards sat on one Mac that way). Send puts every kept card
3
+ // that GitHub's main doesn't have into one pull request, from Chompyy's own branch chompyy/kept-<main>, for you
4
+ // to merge on GitHub. It never pushes main itself. Sending again with more kept cards updates the same PR.
5
+ import { execFileSync } from 'node:child_process';
6
+ import { realpathSync } from 'node:fs';
7
+ import { resolve } from 'node:path';
8
+ import { homePath, readJson, writeJson } from './home.js';
9
+ import { gitRoot } from './workspace.js';
10
+ const git = (dir, args) => execFileSync('git', ['-C', dir, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim();
11
+ const tryGit = (dir, args) => {
12
+ try {
13
+ return git(dir, args);
14
+ }
15
+ catch {
16
+ return null;
17
+ }
18
+ };
19
+ /** The merge commit Keep makes (review.ts keepCard). */
20
+ const KEEP = /^Keep Chompyy card #(\S+): (.*)$/;
21
+ const sentPath = () => homePath('sent.json');
22
+ /** The repo's one .git folder, as a real path: every folder of the repo (and /var vs /private/var) agrees on it. */
23
+ const commonDir = (repo) => realpathSync(resolve(repo, git(repo, ['rev-parse', '--git-common-dir'])));
24
+ const sentKey = (repo, branch) => `${commonDir(repo)}\n${branch}`;
25
+ /** The branches kept cards landed on: one per repo and branch, however many folders the repo has. */
26
+ export function landings(cards) {
27
+ const roots = new Map();
28
+ const dirs = new Map();
29
+ const out = new Map();
30
+ for (const c of cards) {
31
+ const branch = c.run?.base?.branch;
32
+ if (c.outcome !== 'kept' || !c.run?.branch || !branch)
33
+ continue;
34
+ if (!roots.has(c.cwd))
35
+ roots.set(c.cwd, gitRoot(c.cwd));
36
+ const repo = roots.get(c.cwd);
37
+ if (!repo)
38
+ continue;
39
+ if (!dirs.has(repo))
40
+ dirs.set(repo, tryGit(repo, ['rev-parse', '--git-common-dir']) === null ? '' : commonDir(repo));
41
+ const key = `${dirs.get(repo)}\n${branch}`;
42
+ if (dirs.get(repo) && !out.has(key))
43
+ out.set(key, { repo, branch });
44
+ }
45
+ return [...out.values()];
46
+ }
47
+ /** Where `branch` goes on GitHub: its upstream's remote and branch, or null when it has none. */
48
+ function upstreamOf(repo, branch) {
49
+ const remote = tryGit(repo, ['config', `branch.${branch}.remote`]);
50
+ const merge = tryGit(repo, ['config', `branch.${branch}.merge`]);
51
+ if (!remote || remote === '.' || !merge?.startsWith('refs/heads/'))
52
+ return null;
53
+ return { remote, base: merge.slice('refs/heads/'.length) };
54
+ }
55
+ /** What Send would send from `branch`, from what this Mac last fetched (no network). Null: nothing to compare with. */
56
+ export function outbox(repo, branch) {
57
+ const up = upstreamOf(repo, branch);
58
+ const tip = tryGit(repo, ['rev-parse', '--verify', '-q', `refs/heads/${branch}`]);
59
+ if (!up || !tip || !tryGit(repo, ['rev-parse', '--verify', '-q', `refs/remotes/${up.remote}/${up.base}`]))
60
+ return null;
61
+ return outboxAt(repo, branch, up.remote, up.base, tip);
62
+ }
63
+ function outboxAt(repo, branch, remote, base, tip) {
64
+ const sendBranch = `chompyy/kept-${base}`;
65
+ const upstream = `refs/remotes/${remote}/${base}`;
66
+ const sent = tryGit(repo, ['rev-parse', '--verify', '-q', `refs/remotes/${remote}/${sendBranch}`]);
67
+ // Keep's merges sit on the branch's own line (first parent); a card's work commits hang off them.
68
+ const keeps = (not) => git(repo, ['log', '--first-parent', '--merges', '--reverse', '--format=%s', tip, ...not.map((r) => `^${r}`)])
69
+ .split('\n')
70
+ .map((s) => KEEP.exec(s))
71
+ .filter((m) => m !== null)
72
+ .map((m) => ({ id: m[1], title: m[2] }));
73
+ const cards = keeps([upstream]);
74
+ const fresh = sent ? keeps([upstream, sent]) : cards;
75
+ const own = Number(git(repo, ['rev-list', '--count', '--first-parent', '--no-merges', tip, `^${upstream}`]));
76
+ const rec = readJson(sentPath(), {})[sentKey(repo, branch)];
77
+ const pr = rec && fresh.length < cards.length ? { number: rec.number, url: rec.url } : null;
78
+ return { repo, branch, remote, base, sendBranch, cards, fresh, own, pr };
79
+ }
80
+ /** Every landing branch with kept cards GitHub doesn't have, for the app (`chompyy state`). */
81
+ export function outboxes(cards) {
82
+ const out = [];
83
+ for (const l of landings(cards)) {
84
+ try {
85
+ const o = outbox(l.repo, l.branch);
86
+ if (o?.cards.length)
87
+ out.push(o);
88
+ }
89
+ catch { }
90
+ }
91
+ return out;
92
+ }
93
+ /** Files where `tip` and GitHub's base change the same lines, or [] (git before 2.38 can't tell: then []). */
94
+ export function clashFiles(repo, upstream, tip) {
95
+ try {
96
+ execFileSync('git', ['-C', repo, 'merge-tree', '--write-tree', '--name-only', upstream, tip], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] });
97
+ return [];
98
+ }
99
+ catch (e) {
100
+ const err = e;
101
+ if (err.status !== 1 || !err.stdout)
102
+ return [];
103
+ const files = [];
104
+ for (const line of err.stdout.split('\n').slice(1)) {
105
+ if (!line.trim())
106
+ break; // the conflicted files end at the first blank line; messages follow
107
+ files.push(line.trim());
108
+ }
109
+ return [...new Set(files)];
110
+ }
111
+ }
112
+ /** "owner/repo" from a GitHub remote URL (https or ssh), else null. */
113
+ export function githubRepo(url) {
114
+ return /github\.com[:/]+([^/\s]+\/[^/\s]+?)(?:\.git)?\/?$/.exec(url.trim())?.[1] ?? null;
115
+ }
116
+ const plural = (n, one, many = `${one}s`) => `${n} ${n === 1 ? one : many}`;
117
+ /** No "#31" in GitHub text: GitHub would link card 31 to its own PR or issue #31. */
118
+ export function prTitle(cards) {
119
+ if (cards.length === 1)
120
+ return `Kept card ${cards[0].id}: ${cards[0].title}`;
121
+ const ids = cards.map((c) => c.id);
122
+ if (ids.length > 5)
123
+ return `Kept cards ${ids.slice(0, 5).join(', ')} and ${ids.length - 5} more`;
124
+ return `Kept cards ${ids.slice(0, -1).join(', ')} and ${ids.at(-1)}`;
125
+ }
126
+ export function prBody(o, checks) {
127
+ const lines = [
128
+ `Merge this to land ${plural(o.cards.length, 'card')} kept with Chompyy on ${o.base}. Each one is already on ${o.branch} on the Mac that sent it.`,
129
+ '',
130
+ ...o.cards.map((c) => {
131
+ const result = checks(c.id);
132
+ return `- card ${c.id}: ${c.title}${result ? ` · ${result}` : ''}`;
133
+ }),
134
+ ];
135
+ if (o.own)
136
+ lines.push('', `Also carries ${plural(o.own, 'commit')} of your own from ${o.branch}.`);
137
+ lines.push('', 'Sending again with more kept cards updates this PR (`chompyy send`).');
138
+ return lines.join('\n');
139
+ }
140
+ /** What the card's checks said, for the PR body: Chompyy's own run of the repo's tests first, else the agent's word. */
141
+ export function checksOf(card) {
142
+ const result = card?.run?.verified?.result ?? card?.run?.checks?.result;
143
+ return result === 'passed' ? 'checks passed' : result === 'failed' ? 'checks failed' : null;
144
+ }
145
+ const realGh = (repo, args, input) => execFileSync('gh', args, { cwd: repo, encoding: 'utf8', input, stdio: [input === undefined ? 'ignore' : 'pipe', 'pipe', 'pipe'] }).trim();
146
+ /** Send one landing branch: fetch GitHub's base, check for clashes, push Chompyy's branch, open or update the PR. */
147
+ export function sendOne(repo, branch, cards, deps) {
148
+ const up = upstreamOf(repo, branch);
149
+ if (!up)
150
+ throw new Error(`Link ${branch} to GitHub first (git branch -u origin/${branch}): it has no branch there to merge into. Nothing was sent.`);
151
+ const { remote, base } = up;
152
+ const slug = githubRepo(tryGit(repo, ['config', `remote.${remote}.url`]) ?? '');
153
+ if (!slug)
154
+ throw new Error(`Send works with GitHub only, and ${remote} isn't on GitHub. Nothing was sent.`);
155
+ const sendBranch = `chompyy/kept-${base}`;
156
+ const sendRef = `refs/remotes/${remote}/${sendBranch}`;
157
+ // GitHub's latest first, so the list and the clash check are about what is there now.
158
+ git(repo, ['fetch', '-q', remote, `+refs/heads/${base}:refs/remotes/${remote}/${base}`]);
159
+ try {
160
+ git(repo, ['fetch', '-q', remote, `+refs/heads/${sendBranch}:${sendRef}`]);
161
+ }
162
+ catch {
163
+ tryGit(repo, ['update-ref', '-d', sendRef]); // gone on GitHub (deleted after its PR merged)
164
+ }
165
+ const tip = git(repo, ['rev-parse', `refs/heads/${branch}`]);
166
+ const o = outboxAt(repo, branch, remote, base, tip);
167
+ if (!o.cards.length)
168
+ return { message: `Nothing to send: GitHub's ${base} has every kept card already.`, url: null };
169
+ const clash = clashFiles(repo, `refs/remotes/${remote}/${base}`, tip);
170
+ if (clash.length) {
171
+ const files = clash.slice(0, 3).join(', ') + (clash.length > 3 ? ` and ${clash.length - 3} more` : '');
172
+ throw new Error(`Merge ${remote}/${base} into your ${branch} first: kept cards clash with it in ${files}.\nNothing was sent.`);
173
+ }
174
+ try {
175
+ deps.gh(repo, ['auth', 'status']);
176
+ }
177
+ catch {
178
+ throw new Error("Install GitHub's gh and sign in first: brew install gh, then gh auth login.\nNothing was sent.");
179
+ }
180
+ const lease = tryGit(repo, ['rev-parse', '--verify', '-q', sendRef]) ?? '';
181
+ git(repo, ['push', '-q', `--force-with-lease=refs/heads/${sendBranch}:${lease}`, remote, `${tip}:refs/heads/${sendBranch}`]);
182
+ tryGit(repo, ['update-ref', sendRef, tip]);
183
+ const byId = new Map(cards.map((c) => [c.id, c]));
184
+ const title = prTitle(o.cards);
185
+ const body = prBody(o, (id) => checksOf(byId.get(id)));
186
+ const open = JSON.parse(deps.gh(repo, ['pr', 'list', '--repo', slug, '--head', sendBranch, '--state', 'open', '--json', 'number,url', '--limit', '1']) || '[]');
187
+ let pr = open[0];
188
+ if (pr) {
189
+ deps.gh(repo, ['pr', 'edit', String(pr.number), '--repo', slug, '--title', title, '--body-file', '-'], body);
190
+ }
191
+ else {
192
+ const url = deps.gh(repo, ['pr', 'create', '--repo', slug, '--base', base, '--head', sendBranch, '--title', title, '--body-file', '-'], body).split('\n').pop().trim();
193
+ pr = { number: Number(/\/pull\/(\d+)/.exec(url)?.[1] ?? 0), url };
194
+ }
195
+ const all = readJson(sentPath(), {});
196
+ all[sentKey(repo, branch)] = { number: pr.number, url: pr.url, tip, at: deps.now().toISOString() };
197
+ writeJson(sentPath(), all);
198
+ const lead = `Merge PR #${pr.number} on GitHub`;
199
+ if (!open[0])
200
+ return { message: `${lead} to land ${plural(o.cards.length, 'kept card')} on ${base}.\n${pr.url}`, url: pr.url };
201
+ if (!o.fresh.length)
202
+ return { message: `${lead}: it already has all ${plural(o.cards.length, 'kept card')}.\n${pr.url}`, url: pr.url };
203
+ return { message: `${lead}: added ${plural(o.fresh.length, 'kept card')}, ${o.cards.length} in all.\n${pr.url}`, url: pr.url };
204
+ }
205
+ /** `chompyy send`: every landing branch with kept cards GitHub doesn't have. */
206
+ export function sendKept(cards, deps = {}) {
207
+ const d = { gh: deps.gh ?? realGh, now: deps.now ?? (() => new Date()) };
208
+ const ls = landings(cards);
209
+ if (!ls.length)
210
+ return { message: 'Nothing to send: keep a card first.', url: null };
211
+ const linked = ls.filter((l) => upstreamOf(l.repo, l.branch));
212
+ if (!linked.length)
213
+ throw new Error(`Link ${ls[0].branch} to GitHub first (git branch -u origin/${ls[0].branch}): it has no branch there to merge into. Nothing was sent.`);
214
+ // Skip repos whose kept cards were all on GitHub at the last fetch (no network for those). Never fetched: ask.
215
+ const due = linked.filter((l) => {
216
+ try {
217
+ const o = outbox(l.repo, l.branch);
218
+ return o === null || o.cards.length > 0;
219
+ }
220
+ catch {
221
+ return true;
222
+ }
223
+ });
224
+ const results = [];
225
+ const errors = [];
226
+ for (const l of due) {
227
+ try {
228
+ results.push(sendOne(l.repo, l.branch, cards, d));
229
+ }
230
+ catch (e) {
231
+ errors.push(e.message);
232
+ }
233
+ }
234
+ const sent = results.filter((r) => r.url);
235
+ if (errors.length && !sent.length)
236
+ throw new Error(errors[0]);
237
+ if (!sent.length)
238
+ return results[0] ?? { message: 'Nothing to send: GitHub has every kept card already.', url: null };
239
+ return { message: [...sent.map((r) => r.message), ...errors].join('\n'), url: sent[0].url };
240
+ }
@@ -0,0 +1,175 @@
1
+ // Suggest tasks for a repo: one press, a few cards that would use capacity that otherwise resets unused. One model
2
+ // call over a digest of the repo: what it wants to become (README, roadmap and vision docs, open issues) and what
3
+ // the code shows (TODO/FIXME, recent commits), plus your taste and the cards you already have.
4
+ //
5
+ // Every task must name its source, and the source is checked against the digest, so the model can't invent one
6
+ // (the same rule as the history cold start). Nothing runs: the cards land in Suggested for you to approve.
7
+ import { spawnSync } from 'node:child_process';
8
+ import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs';
9
+ import { basename, join } from 'node:path';
10
+ import { addCard } from './board.js';
11
+ import { readTaste } from './taste.js';
12
+ /** Vision and convention docs, in order of how much they say about where the repo is going. */
13
+ const DOCS = ['README.md', 'VISION.md', 'ROADMAP.md', 'FEATURES.md', 'PLAN.md', 'TODO.md', 'CONTRIBUTING.md', 'CLAUDE.md', 'AGENTS.md'];
14
+ const PER_DOC = 6000;
15
+ const MAX_DIGEST = 40_000;
16
+ /**
17
+ * git in a repo Chompyy didn't make: no hooks, no fsmonitor, nothing inherited from the caller's GIT_* (rulebook
18
+ * T4). Read-only commands only.
19
+ */
20
+ function safeGit(repo, args) {
21
+ const env = Object.fromEntries(Object.entries(process.env).filter(([k]) => !k.startsWith('GIT_')));
22
+ const r = spawnSync('git', ['-c', 'core.fsmonitor=false', '-c', 'core.hooksPath=/dev/null', '-C', repo, ...args], { encoding: 'utf8', env, timeout: 15_000, maxBuffer: 4 << 20 });
23
+ return r.status === 0 ? r.stdout : '';
24
+ }
25
+ /** Open issues through your own `gh`, when the repo is on GitHub and gh is logged in. Optional: [] otherwise. */
26
+ export function openIssues(repo) {
27
+ const r = spawnSync('gh', ['issue', 'list', '--state', 'open', '--limit', '30', '--json', 'number,title'], { cwd: repo, encoding: 'utf8', timeout: 20_000 });
28
+ if (r.status !== 0)
29
+ return [];
30
+ try {
31
+ return JSON.parse(r.stdout).filter((i) => Number.isInteger(i.number) && typeof i.title === 'string');
32
+ }
33
+ catch {
34
+ return [];
35
+ }
36
+ }
37
+ const clip = (text, n) => (text.length > n ? `${text.slice(0, n)}\n[… cut at ${n} characters]` : text);
38
+ export function repoDigest(repo, opts = {}) {
39
+ const sources = new Set();
40
+ const parts = [`# Repository: ${basename(repo)}`];
41
+ const docs = DOCS.filter((d) => existsSync(join(repo, d)));
42
+ // Up to 5 more Markdown files at the top of docs/ (design notes, specs).
43
+ try {
44
+ const dir = join(repo, 'docs');
45
+ if (statSync(dir).isDirectory()) {
46
+ docs.push(...readdirSync(dir).filter((n) => n.endsWith('.md')).sort().slice(0, 5).map((n) => `docs/${n}`));
47
+ }
48
+ }
49
+ catch { }
50
+ for (const d of docs) {
51
+ try {
52
+ parts.push(`## File: ${d}\n${clip(readFileSync(join(repo, d), 'utf8'), PER_DOC)}`);
53
+ sources.add(d);
54
+ }
55
+ catch { }
56
+ }
57
+ const issues = opts.issues ?? [];
58
+ if (issues.length) {
59
+ parts.push(`## Open issues\n${issues.map((i) => `#${i.number} ${i.title}`).join('\n')}`);
60
+ for (const i of issues)
61
+ sources.add(`#${i.number}`);
62
+ }
63
+ const todos = safeGit(repo, ['grep', '-n', '-I', '-w', '-E', 'TODO|FIXME|HACK|XXX', '--', '.', ':!*.min.*', ':!**/vendor/**', ':!**/node_modules/**', ':!*.lock', ':!package-lock.json'])
64
+ .split('\n').filter(Boolean).slice(0, 60);
65
+ if (todos.length) {
66
+ parts.push(`## TODO/FIXME in the code (path:line: text)\n${todos.map((l) => l.slice(0, 200)).join('\n')}`);
67
+ for (const l of todos)
68
+ sources.add(l.split(':')[0]);
69
+ }
70
+ const commits = safeGit(repo, ['log', '--no-merges', '--format=%h %s', '-n', '20']).split('\n').filter(Boolean);
71
+ if (commits.length) {
72
+ parts.push(`## Recent commits\n${commits.join('\n')}`);
73
+ for (const c of commits)
74
+ sources.add(c.split(' ')[0]);
75
+ }
76
+ // Tracked files: a task may also cite one it would change.
77
+ for (const f of safeGit(repo, ['ls-files']).split('\n').filter(Boolean).slice(0, 5000))
78
+ sources.add(f);
79
+ const taste = readTaste().text.trim();
80
+ if (taste)
81
+ parts.push(`## How the owner likes work done (taste.md)\n${clip(taste, 4000)}`);
82
+ if (opts.existing?.length)
83
+ parts.push(`## Cards already on the board (don't repeat these)\n${opts.existing.slice(0, 60).map((t) => `- ${t}`).join('\n')}`);
84
+ parts.push(`## SOURCES you may cite\nAny file path above or tracked in the repo, an issue number like #12 from the list, or a commit hash from the list.`);
85
+ return { text: clip(parts.join('\n\n'), MAX_DIGEST), sources };
86
+ }
87
+ export function suggestPrompt(digest, count) {
88
+ return [
89
+ `You suggest tasks for a coding agent to run unattended in this repository while its owner is away, using plan capacity that would otherwise reset unused.`,
90
+ `Below is a digest of the repository: its docs (what it wants to become), open issues, TODO/FIXME lines, recent commits, the owner's taste, and cards already on the board.`,
91
+ ``,
92
+ `Propose up to ${count} tasks. Mix two kinds:`,
93
+ `- "vision": the next concrete step toward what the docs and issues say the project wants`,
94
+ `- "chore": something the code shows needs doing (a TODO/FIXME, a missing test, a stale doc)`,
95
+ ``,
96
+ `Every task must be:`,
97
+ `- doable unattended in one sitting (well under an hour of agent time), inside this repo, with no network, no publishing, no secrets`,
98
+ `- checkable: the idea says how the result is checked (a test passes, a command runs, a file exists)`,
99
+ `- grounded: "source" is exactly one file path, issue number (#12) or commit hash from the digest`,
100
+ `- new: not the same as a card already on the board`,
101
+ ``,
102
+ `Reply with JSON only, no prose:`,
103
+ `{"tasks":[{"title":"under 60 characters, starts with a verb","idea":"1-2 sentences: what to do and how it's checked","why":"one short line: why this now, from the source","source":"...","size":"small|medium","kind":"vision|chore"}]}`,
104
+ ``,
105
+ digest,
106
+ ].join('\n');
107
+ }
108
+ const norm = (s) => s.toLowerCase().replace(/[^a-z0-9]+/g, ' ').trim();
109
+ /** Keep the tasks that cite a real source, aren't on the board already, and have what a card needs. */
110
+ export function validateTasks(raw, sources, existing, count) {
111
+ const list = Array.isArray(raw?.tasks) ? (raw.tasks) : [];
112
+ const have = new Set(existing.map(norm));
113
+ const tasks = [];
114
+ for (const t of list) {
115
+ const title = typeof t?.title === 'string' ? t.title.trim() : '';
116
+ const idea = typeof t?.idea === 'string' ? t.idea.trim() : '';
117
+ const source = typeof t?.source === 'string' ? t.source.trim().replace(/^`|`$/g, '') : '';
118
+ if (!title || !idea || !sources.has(source) || have.has(norm(title)))
119
+ continue;
120
+ have.add(norm(title));
121
+ tasks.push({
122
+ title: title.slice(0, 80),
123
+ idea,
124
+ why: typeof t.why === 'string' ? t.why.trim() : '',
125
+ source,
126
+ size: t.size === 'medium' ? 'medium' : 'small',
127
+ kind: t.kind === 'chore' ? 'chore' : 'vision',
128
+ });
129
+ if (tasks.length >= count)
130
+ break;
131
+ }
132
+ return { tasks, dropped: list.length - tasks.length };
133
+ }
134
+ function parseJson(text) {
135
+ const m = text.match(/\{[\s\S]*\}/);
136
+ if (!m)
137
+ return {};
138
+ try {
139
+ return JSON.parse(m[0]);
140
+ }
141
+ catch {
142
+ return {};
143
+ }
144
+ }
145
+ export async function suggestTasks(repo, runner, opts) {
146
+ const count = opts.count ?? 5;
147
+ const digest = repoDigest(repo, { existing: opts.existing, issues: opts.issues ?? openIssues(repo) });
148
+ const result = await runner.run({ prompt: suggestPrompt(digest.text, count), cwd: opts.cwd, model: opts.model, tools: '', timeoutMs: 240_000 });
149
+ if (result.timedOut)
150
+ throw new Error('Suggesting tasks timed out. Try again.');
151
+ if (result.exitCode !== 0)
152
+ throw new Error(`claude exited with ${result.exitCode}: ${result.stderr.trim().slice(0, 300)}`);
153
+ return validateTasks(parseJson(result.output), digest.sources, opts.existing, count);
154
+ }
155
+ /** The tasks as suggested cards in that repo, each saying where it came from. */
156
+ export function addSuggested(board, repo, tasks, now) {
157
+ return tasks.map((t) => {
158
+ const c = addCard(board, t.idea, repo, now, 'suggested');
159
+ c.title = t.title;
160
+ c.source = 'suggest';
161
+ c.why = `${t.kind === 'vision' ? 'Next step' : 'Chore'} from ${t.source} · ${t.size}${t.why ? `: ${t.why}` : ''}`;
162
+ return c;
163
+ });
164
+ }
165
+ export function suggestText(repo, cards, dropped) {
166
+ if (!cards.length)
167
+ return `No new tasks for ${basename(repo)}${dropped ? ` (${dropped} dropped: no real source, or already on the board)` : ''}. Try again later, or park one yourself.`;
168
+ return [
169
+ `Approve the ones you want; they run while you're away.`,
170
+ '',
171
+ `${cards.length} suggested for ${basename(repo)}:`,
172
+ ...cards.map((c) => ` #${c.id} ${c.title}\n ${c.why}`),
173
+ ...(dropped ? ['', `${dropped} dropped: no real source, or already on the board.`] : []),
174
+ ].join('\n');
175
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "chompyy",
3
- "version": "0.4.4",
3
+ "version": "0.4.6",
4
4
  "description": "Use Claude Code 5-hour window capacity that would reset unused: park ideas, blueprint them, run approved cards while you're away.",
5
5
  "keywords": [
6
6
  "claude-code",