chompyy 0.4.0 → 0.4.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/nudge.js ADDED
@@ -0,0 +1,438 @@
1
+ // Live suggestions while you work (FEATURES.md, "live evidence-based suggestions"). The first one: coming back
2
+ // to a big conversation after its cache expired. detect's C1 counts what that cost after the fact; this stops the
3
+ // first message once, at the moment it would happen, with the price and the cheaper ways on. Send it again and it
4
+ // goes through. Runs as Claude Code's UserPromptSubmit hook (`chompyy nudge on` installs it); away runs turn
5
+ // hooks off, so it never touches them.
6
+ import { closeSync, existsSync, openSync, readdirSync, readFileSync, readSync, realpathSync, statSync, writeFileSync, mkdirSync } from 'node:fs';
7
+ import { homedir } from 'node:os';
8
+ import { basename, dirname, join } from 'node:path';
9
+ import { formatDuration } from './duration.js';
10
+ import { appendJsonl, homePath } from './home.js';
11
+ import { coldReturns, isAutomated, scan } from './detect.js';
12
+ import { projectsDir } from './dream.js';
13
+ /** The main conversation's cache lives an hour (5 minutes on API keys): past an hour it's cold either way. */
14
+ export const COLD_AFTER_MS = 60 * 60_000;
15
+ /** Below this the rebuild is cheap; not worth stopping you. */
16
+ export const MIN_CONTEXT = 40_000;
17
+ /** Warn this long into a pause: still time to /compact while the cache is warm (reads at a tenth of the price). */
18
+ export const WARN_AFTER_MS = 45 * 60_000;
19
+ const MARK = '# chompyy nudge';
20
+ /** Sent anyway this many stops in a row in one project: stop stopping you there (a heads-up instead). */
21
+ export const QUIET_AFTER = 3;
22
+ const prefsPath = () => homePath('nudge-prefs.json');
23
+ export function loadPrefs() {
24
+ try {
25
+ return JSON.parse(readFileSync(prefsPath(), 'utf8'));
26
+ }
27
+ catch {
28
+ return {};
29
+ }
30
+ }
31
+ export function savePrefs(p) {
32
+ writeFileSync(prefsPath(), JSON.stringify(p, null, 2) + '\n');
33
+ }
34
+ /** `chompyy nudge strict|quiet|learn <dir>`: always stop here, never stop here, or go back to learning. */
35
+ export function setProjectMode(mode, cwd) {
36
+ const p = loadPrefs();
37
+ p.strict = (p.strict ?? []).filter((x) => x !== cwd);
38
+ p.quiet = (p.quiet ?? []).filter((x) => x !== cwd);
39
+ if (mode !== 'learn')
40
+ p[mode] = [...p[mode], cwd];
41
+ savePrefs(p);
42
+ const name = basename(cwd);
43
+ return mode === 'strict' ? `${name}: Chompyy always stops a cold return here.` : mode === 'quiet' ? `${name}: a one-line heads-up only, never a stop.` : `${name}: back to learning from what you do.`;
44
+ }
45
+ /**
46
+ * Should Chompyy stop you in this project, or only give a heads-up? Your choice first; otherwise it learns: after
47
+ * QUIET_AFTER stops in a row here that you sent anyway, being stopped isn't helping you, so it stops stopping.
48
+ */
49
+ export function learnedQuiet(cwd, events, prefs = loadPrefs()) {
50
+ if (prefs.strict?.includes(cwd))
51
+ return { quiet: false, why: 'you', sentInARow: 0 };
52
+ if (prefs.quiet?.includes(cwd))
53
+ return { quiet: true, why: 'you', sentInARow: 0 };
54
+ const here = outcomes(events.filter((e) => e.cwd === cwd));
55
+ let n = 0;
56
+ for (const o of [...here].reverse()) {
57
+ if (o.did !== 'sent')
58
+ break;
59
+ n++;
60
+ }
61
+ return { quiet: n >= QUIET_AFTER, why: n >= QUIET_AFTER ? 'learned' : null, sentInARow: n };
62
+ }
63
+ export function quietText(e, first) {
64
+ const name = basename(e.cwd ?? '');
65
+ return first
66
+ ? `🍪 You sent anyway the last ${QUIET_AFTER} times in ${name}, so Chompyy won't stop you here any more (${k(e.context)} rewritten now). To be stopped again: chompyy nudge strict`
67
+ : `🍪 Cold cache: this message rewrites ${k(e.context)} tokens.`;
68
+ }
69
+ const num = (v) => (typeof v === 'number' && Number.isFinite(v) ? v : 0);
70
+ function replyOf(line) {
71
+ if (!line.includes('"assistant"') || !line.includes('"usage"'))
72
+ return null;
73
+ try {
74
+ const e = JSON.parse(line);
75
+ const u = e.message?.usage;
76
+ if (e.type !== 'assistant' || e.isSidechain || !u)
77
+ return null;
78
+ const at = Date.parse(String(e.timestamp ?? ''));
79
+ if (!at)
80
+ return null;
81
+ const cacheWrite = num(u.cache_creation_input_tokens);
82
+ return { at, context: num(u.input_tokens) + num(u.cache_read_input_tokens) + cacheWrite, cacheWrite };
83
+ }
84
+ catch {
85
+ return null;
86
+ }
87
+ }
88
+ /** Bytes from the start or the end of a file, without reading all of a long transcript. */
89
+ function slice(file, bytes, fromEnd) {
90
+ const size = statSync(file).size;
91
+ const len = Math.min(size, bytes);
92
+ const buf = Buffer.alloc(len);
93
+ const fd = openSync(file, 'r');
94
+ try {
95
+ readSync(fd, buf, 0, len, fromEnd ? size - len : 0);
96
+ }
97
+ finally {
98
+ closeSync(fd);
99
+ }
100
+ return buf.toString('utf8');
101
+ }
102
+ /** The conversation's last reply, and its first (about what a fresh conversation costs: tools, CLAUDE.md, memory). */
103
+ export function replies(transcript) {
104
+ const tail = slice(transcript, 4 << 20, true).split('\n');
105
+ let last = null;
106
+ for (let i = tail.length - 1; i >= 0 && !last; i--)
107
+ last = replyOf(tail[i]);
108
+ let first = null;
109
+ for (const line of slice(transcript, 2 << 20, false).split('\n'))
110
+ if ((first = replyOf(line)))
111
+ break;
112
+ return { last, first };
113
+ }
114
+ export function loadNudges() {
115
+ const path = homePath('nudges.jsonl');
116
+ if (!existsSync(path))
117
+ return [];
118
+ return readFileSync(path, 'utf8').split('\n').flatMap((l) => {
119
+ try {
120
+ return l ? [JSON.parse(l)] : [];
121
+ }
122
+ catch {
123
+ return [];
124
+ }
125
+ });
126
+ }
127
+ const k = (n) => (n >= 1e6 ? `${(n / 1e6).toFixed(1)}M` : `${Math.round(n / 1000)}k`);
128
+ /**
129
+ * What to tell Claude Code about this prompt: a block with the reason, or nothing (let it through).
130
+ * Never throws: any doubt lets the prompt through.
131
+ */
132
+ export function decide(input, now, events = loadNudges(), prefs = loadPrefs()) {
133
+ const prompt = (input.prompt ?? '').trimStart();
134
+ const transcript = input.transcript_path;
135
+ const session = input.session_id ?? '';
136
+ // Commands, shell lines and messages Claude Code sends itself (scheduled tasks, agents reporting back).
137
+ if (!transcript || /^[/!<]/.test(prompt) || process.env.CHOMPYY_NUDGE === '0')
138
+ return { block: false };
139
+ let last;
140
+ let first;
141
+ try {
142
+ if (!existsSync(transcript))
143
+ return { block: false };
144
+ ({ last, first } = replies(transcript));
145
+ }
146
+ catch {
147
+ return { block: false };
148
+ }
149
+ if (!last)
150
+ return { block: false };
151
+ const idleMs = now - last.at;
152
+ if (idleMs <= COLD_AFTER_MS || last.context < MIN_CONTEXT)
153
+ return { block: false };
154
+ const fresh = first && first.context < last.context / 2 ? first.context : undefined;
155
+ let cwd = '';
156
+ try {
157
+ cwd = cwdOf(transcript);
158
+ }
159
+ catch { }
160
+ const base = { session, transcript, idleMs, context: last.context, ...(fresh ? { fresh } : {}), ...(cwd ? { cwd } : {}) };
161
+ // Already stopped once for this break: you chose to send it.
162
+ if (events.some((e) => e.kind === 'stopped' && e.session === session && Date.parse(e.at) > last.at)) {
163
+ return { block: false, event: { at: new Date(now).toISOString(), kind: 'sent', ...base } };
164
+ }
165
+ // Learned per project: if stopping you here never helped, a one-line heads-up instead.
166
+ if (cwd && learnedQuiet(cwd, events, prefs).quiet) {
167
+ const event = { at: new Date(now).toISOString(), kind: 'quiet', ...base };
168
+ const first = !events.some((e) => e.kind === 'quiet' && e.cwd === cwd);
169
+ return { block: false, event, notice: quietText(event, first) };
170
+ }
171
+ const event = { at: new Date(now).toISOString(), kind: 'stopped', ...base };
172
+ return { block: true, reason: reasonText(event), event };
173
+ }
174
+ export function reasonText(e) {
175
+ return [
176
+ `🍪 /compact first: idle ${formatDuration(e.idleMs)}, the cache expired, so sending rewrites all ${k(e.context)} tokens.`,
177
+ `Or /clear and say where you were${e.fresh ? ` (~${k(e.fresh)})` : ''}. Or send again: Chompyy stops once per break.`,
178
+ ].join('\n');
179
+ }
180
+ /** The hook itself: stdin JSON in, a block decision (or nothing) out. Always exits cleanly. */
181
+ export function runHook(stdin, now = Date.now()) {
182
+ let input;
183
+ try {
184
+ input = JSON.parse(stdin);
185
+ }
186
+ catch {
187
+ return '';
188
+ }
189
+ const d = decide(input, now);
190
+ if ('event' in d) {
191
+ try {
192
+ appendJsonl(homePath('nudges.jsonl'), d.event);
193
+ }
194
+ catch {
195
+ /* logging never stops a prompt */
196
+ }
197
+ }
198
+ if (d.block)
199
+ return JSON.stringify({ decision: 'block', reason: d.reason });
200
+ return 'notice' in d && d.notice ? JSON.stringify({ systemMessage: d.notice }) : '';
201
+ }
202
+ /**
203
+ * Conversations 45-60 minutes into a pause, big enough to matter: each break is reported once (logged as `warned`),
204
+ * so the app can notify without keeping its own list. Looks only at transcripts written in the last hour.
205
+ */
206
+ export function goingCold(now = Date.now(), dir = projectsDir(), events = loadNudges()) {
207
+ const out = [];
208
+ let folders = [];
209
+ try {
210
+ folders = readdirSync(dir).filter((f) => !isAutomated(f));
211
+ }
212
+ catch {
213
+ return out;
214
+ }
215
+ for (const folder of folders) {
216
+ let files = [];
217
+ try {
218
+ files = readdirSync(join(dir, folder)).filter((f) => f.endsWith('.jsonl'));
219
+ }
220
+ catch {
221
+ continue;
222
+ }
223
+ for (const f of files) {
224
+ const transcript = join(dir, folder, f);
225
+ try {
226
+ const mtime = statSync(transcript).mtimeMs;
227
+ if (now - mtime > COLD_AFTER_MS || now - mtime < WARN_AFTER_MS - 60_000)
228
+ continue;
229
+ const { last, first } = replies(transcript);
230
+ if (!last || last.context < MIN_CONTEXT)
231
+ continue;
232
+ const idleMs = now - last.at;
233
+ if (idleMs < WARN_AFTER_MS || idleMs >= COLD_AFTER_MS)
234
+ continue;
235
+ const session = f.replace(/\.jsonl$/, '');
236
+ if (events.some((e) => e.kind === 'warned' && e.session === session && Date.parse(e.at) > last.at))
237
+ continue;
238
+ const cwd = cwdOf(transcript);
239
+ const fresh = first && first.context < last.context / 2 ? first.context : undefined;
240
+ out.push({ session, transcript, project: cwd ? basename(cwd) : folder, context: last.context, ...(fresh ? { fresh } : {}), idleMs, coldAt: new Date(last.at + COLD_AFTER_MS).toISOString() });
241
+ }
242
+ catch {
243
+ /* one bad file never hides the others */
244
+ }
245
+ }
246
+ }
247
+ return out;
248
+ }
249
+ function cwdOf(transcript) {
250
+ const m = slice(transcript, 64 << 10, true).match(/"cwd":"((?:[^"\\]|\\.)*)"/g);
251
+ const last = m?.[m.length - 1];
252
+ return last ? JSON.parse(`{${last}}`).cwd : '';
253
+ }
254
+ /** Report each conversation once: log it, return it. */
255
+ export function takeGoingCold(now = Date.now()) {
256
+ const due = goingCold(now);
257
+ for (const d of due) {
258
+ try {
259
+ appendJsonl(homePath('nudges.jsonl'), { at: new Date(now).toISOString(), kind: 'warned', session: d.session, transcript: d.transcript, idleMs: d.idleMs, context: d.context, coldAt: d.coldAt, project: d.project, ...(d.fresh ? { fresh: d.fresh } : {}) });
260
+ }
261
+ catch {
262
+ /* still report it */
263
+ }
264
+ }
265
+ return due;
266
+ }
267
+ /** The notification: what's at stake and the one move that pays now. */
268
+ export function coldWarningText(d) {
269
+ const at = new Date(d.coldAt).toLocaleTimeString('en-US', { hour: '2-digit', minute: '2-digit' });
270
+ return {
271
+ title: `${d.project}: /compact before ${at}`,
272
+ body: `After ${at} its cache expires and coming back rewrites all ${k(d.context)}. Done with it? Do nothing.`,
273
+ };
274
+ }
275
+ /** Read each stopped conversation after the stop: sent anyway, carried on small (compacted), or left. */
276
+ export function outcomes(events = loadNudges()) {
277
+ const stops = events.filter((e) => e.kind === 'stopped');
278
+ return stops.map((event, i) => {
279
+ const next = stops.slice(i + 1).find((s) => s.session === event.session);
280
+ 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
+ let after = null;
285
+ try {
286
+ for (const line of readFileSync(event.transcript, 'utf8').split('\n')) {
287
+ const r = replyOf(line);
288
+ if (r && r.at > Date.parse(event.at) && r.at < until) {
289
+ after = r;
290
+ break;
291
+ }
292
+ }
293
+ }
294
+ catch {
295
+ /* transcript gone: count it as left */
296
+ }
297
+ 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)) };
300
+ });
301
+ }
302
+ export function warnOutcomes(events = loadNudges()) {
303
+ return events.filter((e) => e.kind === 'warned').map((event) => {
304
+ const coldAt = Date.parse(event.coldAt ?? '') || Date.parse(event.at) + 15 * 60_000;
305
+ let next = null;
306
+ try {
307
+ for (const line of readFileSync(event.transcript, 'utf8').split('\n')) {
308
+ const r = replyOf(line);
309
+ if (r && r.at > Date.parse(event.at)) {
310
+ next = r;
311
+ break;
312
+ }
313
+ }
314
+ }
315
+ catch {
316
+ /* transcript gone */
317
+ }
318
+ if (!next)
319
+ return { event, did: 'left', saved: 0 };
320
+ if (next.at >= coldAt)
321
+ return { event, did: 'cold', saved: 0 };
322
+ if (next.context < event.context / 2)
323
+ return { event, did: 'compacted', saved: event.context - next.context };
324
+ return { event, did: 'continued', saved: 0 };
325
+ });
326
+ }
327
+ const WEEK = 7 * 86_400_000;
328
+ export function impact(on = nudgeInstalled(), now = Date.now(), root, events = loadNudges()) {
329
+ const s = scan({ days: 14, now: new Date(now), ...(root ? { root } : {}) });
330
+ const all = coldReturns(s, now - 2 * WEEK);
331
+ const sum = (from, to) => {
332
+ const xs = all.filter((x) => x.at >= from && x.at < to);
333
+ return { count: xs.length, tokens: xs.reduce((a, x) => a + x.tokens, 0) };
334
+ };
335
+ const thisWeek = sum(now - WEEK, Infinity);
336
+ const lastWeek = sum(now - 2 * WEEK, now - WEEK);
337
+ const stops = outcomes(events);
338
+ const warnings = warnOutcomes(events);
339
+ const saved = [...stops, ...warnings].filter((o) => now - Date.parse(o.event.at) < WEEK).reduce((a, o) => a + o.saved, 0);
340
+ const trend = `Cold returns: ${thisWeek.count} this week (${k(thisWeek.tokens)}), ${lastWeek.count} last week (${k(lastWeek.tokens)}).`;
341
+ const line = saved ? `~${k(saved)} tokens saved this week. ${trend}` : trend;
342
+ return { on, thisWeek, lastWeek, stops, warnings, saved, line };
343
+ }
344
+ export function nudgeText(on, list = outcomes(), now = Date.now()) {
345
+ const lines = [on ? 'Live suggestions are on: Chompyy stops the first message to a big conversation whose cache expired.' : 'Live suggestions are off. `chompyy nudge on` turns them on.'];
346
+ const recent = list.filter((o) => now - Date.parse(o.event.at) < 30 * 86_400_000);
347
+ if (!recent.length) {
348
+ lines.push(on ? 'No stops yet. They come when you return to a conversation of 40k+ tokens after more than an hour.' : '');
349
+ return lines.filter(Boolean).join('\n');
350
+ }
351
+ const n = (d) => recent.filter((o) => o.did === d).length;
352
+ const saved = recent.reduce((a, o) => a + o.saved, 0);
353
+ const rebuilt = recent.filter((o) => o.did === 'sent').reduce((a, o) => a + o.event.context, 0);
354
+ lines.push(`Last 30 days: stopped ${recent.length} time${recent.length === 1 ? '' : 's'}. You compacted ${n('compacted')}, left or started fresh ${n('left')}, sent anyway ${n('sent')}.`, `${saved ? `About ${k(saved)} tokens not written again` : 'Nothing saved yet'}${rebuilt ? `; ${k(rebuilt)} rebuilt when you sent anyway` : ''}.`);
355
+ const events = list.map((o) => o.event);
356
+ const prefs = loadPrefs();
357
+ for (const cwd of new Set(events.map((e) => e.cwd).filter((c) => Boolean(c)))) {
358
+ const q = learnedQuiet(cwd, loadNudges(), prefs);
359
+ if (q.quiet)
360
+ lines.push(`Heads-up only in ${basename(cwd)} (${q.why === 'you' ? 'you asked' : `you sent anyway ${QUIET_AFTER} times in a row`}). Stop me again: chompyy nudge strict ${cwd}`);
361
+ }
362
+ lines.push('Did it work? chompyy worked');
363
+ return lines.join('\n');
364
+ }
365
+ // ---------- installing the hook in Claude Code's settings ----------
366
+ export const claudeSettingsPath = () => process.env.CHOMPYY_CLAUDE_SETTINGS || join(homedir(), '.claude', 'settings.json');
367
+ const settingsPath = claudeSettingsPath;
368
+ function readSettings(path) {
369
+ if (!existsSync(path))
370
+ return { settings: {}, raw: null };
371
+ const raw = readFileSync(path, 'utf8');
372
+ try {
373
+ return { settings: JSON.parse(raw), raw };
374
+ }
375
+ catch {
376
+ throw new Error(`${path} isn't valid JSON, so Chompyy left it alone.`);
377
+ }
378
+ }
379
+ const groups = (s) => {
380
+ const hooks = (s.hooks ?? {});
381
+ return Array.isArray(hooks.UserPromptSubmit) ? hooks.UserPromptSubmit : [];
382
+ };
383
+ const ours = (g) => (g.hooks ?? []).some((h) => h.command?.includes(MARK));
384
+ 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. */
386
+ export function nudgeOnSince(events = loadNudges(), path = settingsPath()) {
387
+ const at = Date.parse(loadPrefs().onAt ?? '');
388
+ if (at)
389
+ return at;
390
+ try {
391
+ return statSync(`${path}.chompyy-backup`).mtimeMs;
392
+ }
393
+ catch { }
394
+ return events.length ? Date.parse(events[0].at) : null;
395
+ }
396
+ export function nudgeInstalled(path = settingsPath()) {
397
+ try {
398
+ return groups(readSettings(path).settings).some(ours);
399
+ }
400
+ catch {
401
+ return false;
402
+ }
403
+ }
404
+ /** The command the hook runs: this CLI by absolute path. A copy npx unpacked for one run can vanish, so not that. */
405
+ export function hookCommand(script = process.argv[1] ?? '', node = process.execPath) {
406
+ const real = existsSync(script) ? realpathSync(script) : script;
407
+ if (/[\\/]_npx[\\/]/.test(real))
408
+ throw new Error('This is a one-off npx copy. Install Chompyy first (npm install -g chompyy), then run chompyy nudge on.');
409
+ return `"${node}" "${real}" hook prompt ${MARK}`;
410
+ }
411
+ /** Add (or remove) the hook in ~/.claude/settings.json, keeping every other hook. Backs the file up first. */
412
+ export function setNudge(on, command, path = settingsPath()) {
413
+ const { settings, raw } = readSettings(path);
414
+ const hooks = { ...(settings.hooks ?? {}) };
415
+ const kept = groups(settings).filter((g) => !ours(g));
416
+ const list = on ? [...kept, { hooks: [{ type: 'command', command: command ?? hookCommand(), timeout: 10 }] }] : kept;
417
+ if (list.length)
418
+ hooks.UserPromptSubmit = list;
419
+ else
420
+ delete hooks.UserPromptSubmit;
421
+ if (Object.keys(hooks).length)
422
+ settings.hooks = hooks;
423
+ else
424
+ delete settings.hooks;
425
+ if (raw !== null)
426
+ writeFileSync(`${path}.chompyy-backup`, raw);
427
+ mkdirSync(dirname(path), { recursive: true });
428
+ writeFileSync(path, JSON.stringify(settings, null, 2) + '\n');
429
+ try {
430
+ const p = loadPrefs();
431
+ if (on && !nudgeInstalledBefore(raw))
432
+ savePrefs({ ...p, onAt: new Date().toISOString() });
433
+ }
434
+ catch { }
435
+ return on
436
+ ? `On. Added a UserPromptSubmit hook to ${path.replace(homedir(), '~')} (the old file is saved next to it as .chompyy-backup). Conversations already open may need a restart to pick it up.`
437
+ : `Off. Removed Chompyy's hook from ${path.replace(homedir(), '~')}; your other hooks are untouched.`;
438
+ }
package/dist/pacing.js CHANGED
@@ -9,6 +9,7 @@
9
9
  // The burn rate comes from a small history of quota readings (quota-history.json), saved whenever the snapshot
10
10
  // changes, so no extra calls are made.
11
11
  import { homePath, readJson, writeJson } from './home.js';
12
+ import { archiveWindowEnds } from './premise.js';
12
13
  import { windowView } from './quota.js';
13
14
  export const FIVE_HOURS = 5 * 3600_000;
14
15
  export const WEEK = 7 * 24 * 3600_000;
@@ -34,6 +35,10 @@ export function recordSample(snap, nowMs = Date.parse(snap.capturedAt)) {
34
35
  return false; // out of order
35
36
  samples.push({ at: nowMs, ...(snap.fiveHour ? { five: snap.fiveHour } : {}), ...(snap.sevenDay ? { week: snap.sevenDay } : {}) });
36
37
  writeJson(historyPath(), { samples: samples.filter((s) => s.at > nowMs - KEEP_MS) });
38
+ try {
39
+ archiveWindowEnds(samples, nowMs); // windows that ended, kept beyond the 8 days (premise.ts)
40
+ }
41
+ catch { }
37
42
  return true;
38
43
  }
39
44
  // ---------- pace delta ----------
@@ -0,0 +1,122 @@
1
+ // The premise (FEATURES §10, §11): how often a 5-hour window resets with capacity left while the weekly limit
2
+ // isn't what stops you. Chompyy's pitch rests on that number, so it's measured from your own quota readings, never
3
+ // assumed.
4
+ //
5
+ // quota-history.json keeps only 8 days, so every window that ends is also written to windows.jsonl, which is
6
+ // kept: one line per window, numbers only.
7
+ import { existsSync, readFileSync, appendFileSync } from 'node:fs';
8
+ import { homePath } from './home.js';
9
+ /** Anthropic's reset times wobble by a second or a minute (14:59:59 vs 15:00:00): the same window. */
10
+ const bucket = (resetsAt) => Math.floor((resetsAt + 300) / 600);
11
+ const key = (e) => `${e.kind}:${bucket(e.resetsAt)}`;
12
+ const EXACT_MS = 15 * 60_000;
13
+ /**
14
+ * Windows that have ended, from the readings. A reading after the reset that still shows the old window means no
15
+ * new window has started yet, so its number is the final one. A window is only returned once its number can't
16
+ * change any more: it is exact, or a newer window of the same kind has started.
17
+ */
18
+ export function windowEnds(samples, nowMs) {
19
+ const groups = new Map();
20
+ for (const s of samples) {
21
+ for (const [kind, w] of [['5h', s.five], ['week', s.week]]) {
22
+ if (!w)
23
+ continue;
24
+ const k = key({ kind, resetsAt: w.resetsAt });
25
+ const g = groups.get(k) ?? { kind, resetsAt: w.resetsAt, list: [] };
26
+ g.resetsAt = Math.max(g.resetsAt, w.resetsAt);
27
+ g.list.push({ at: s.at, usedPct: w.usedPct, ...(kind === '5h' && s.week ? { week: s.week } : {}) });
28
+ groups.set(k, g);
29
+ }
30
+ }
31
+ const latest = { '5h': 0, week: 0 };
32
+ for (const g of groups.values())
33
+ latest[g.kind] = Math.max(latest[g.kind], bucket(g.resetsAt));
34
+ const ends = [];
35
+ for (const g of groups.values()) {
36
+ const resetMs = g.resetsAt * 1000;
37
+ if (resetMs > nowMs)
38
+ continue; // still running
39
+ const list = g.list.sort((a, b) => a.at - b.at);
40
+ const before = list.filter((x) => x.at <= resetMs);
41
+ const after = list.filter((x) => x.at > resetMs);
42
+ const last = before.at(-1) ?? after[0];
43
+ const exact = after.length > 0 || resetMs - last.at <= EXACT_MS;
44
+ if (!exact && bucket(g.resetsAt) === latest[g.kind])
45
+ continue; // could still get a closer reading
46
+ const usedPct = Math.max(...(after.length ? [...before, ...after] : before).map((x) => x.usedPct));
47
+ const week = [...before, ...after].reverse().find((x) => x.week)?.week;
48
+ ends.push({ kind: g.kind, resetsAt: g.resetsAt, usedPct, exact, ...(week ? { weekUsedPct: week.usedPct, weekResetsAt: week.resetsAt } : {}) });
49
+ }
50
+ return ends.sort((a, b) => a.resetsAt - b.resetsAt);
51
+ }
52
+ const logPath = () => homePath('windows.jsonl');
53
+ export function loadWindowLog() {
54
+ if (!existsSync(logPath()))
55
+ return [];
56
+ return readFileSync(logPath(), 'utf8').split('\n').filter(Boolean).flatMap((l) => {
57
+ try {
58
+ return [JSON.parse(l)];
59
+ }
60
+ catch {
61
+ return [];
62
+ }
63
+ });
64
+ }
65
+ /** Write the windows that ended and aren't in windows.jsonl yet. Returns how many were added. */
66
+ export function archiveWindowEnds(samples, nowMs) {
67
+ const known = new Set(loadWindowLog().map(key));
68
+ const fresh = windowEnds(samples, nowMs).filter((e) => !known.has(key(e)));
69
+ if (fresh.length)
70
+ appendFileSync(logPath(), fresh.map((e) => JSON.stringify(e)).join('\n') + '\n');
71
+ return fresh.length;
72
+ }
73
+ /** Everything known: the log plus what the current readings add. */
74
+ export function allWindowEnds(samples, nowMs) {
75
+ const byKey = new Map(loadWindowLog().map((e) => [key(e), e]));
76
+ for (const e of windowEnds(samples, nowMs))
77
+ if (!byKey.has(key(e)) || (e.exact && !byKey.get(key(e)).exact))
78
+ byKey.set(key(e), e);
79
+ return [...byKey.values()].sort((a, b) => a.resetsAt - b.resetsAt);
80
+ }
81
+ /** A 5-hour window "had capacity left" at this much or more. */
82
+ export const LEFT_PCT = 20;
83
+ /** A week "wasn't binding" when it reset with at least this much left. */
84
+ export const WEEK_SLACK_PCT = 10;
85
+ export function premise(ends) {
86
+ const five = ends.filter((e) => e.kind === '5h');
87
+ const exact = five.filter((e) => e.exact);
88
+ const left = exact.map((e) => 100 - e.usedPct).sort((a, b) => a - b);
89
+ const median = left.length ? (left.length % 2 ? left[(left.length - 1) / 2] : (left[left.length / 2 - 1] + left[left.length / 2]) / 2) : null;
90
+ const weeks = ends.filter((e) => e.kind === 'week').map((e) => ({ resetsAt: e.resetsAt, leftPct: 100 - e.usedPct, exact: e.exact }));
91
+ const weekOf = new Map(weeks.map((w) => [bucket(w.resetsAt), w]));
92
+ const judged = exact.filter((e) => e.weekResetsAt !== undefined && weekOf.has(bucket(e.weekResetsAt)));
93
+ const hits = judged.filter((e) => 100 - e.usedPct >= LEFT_PCT && weekOf.get(bucket(e.weekResetsAt)).leftPct >= WEEK_SLACK_PCT);
94
+ return {
95
+ fiveHour: { ended: five.length, exact: exact.length, medianLeftPct: median, withLeft: left.filter((l) => l >= LEFT_PCT).length },
96
+ weeks,
97
+ premise: { windows: judged.length, hits: hits.length, sharePct: judged.length ? Math.round((hits.length / judged.length) * 100) : null },
98
+ };
99
+ }
100
+ const day = (sec) => new Date(sec * 1000).toLocaleDateString([], { weekday: 'short', day: 'numeric', month: 'short' });
101
+ export function premiseText(p) {
102
+ const lines = [];
103
+ const f = p.fiveHour;
104
+ if (!f.ended && !p.weeks.length)
105
+ return ['No 5-hour window has ended since Chompyy started reading your quota. Check back after the next reset.'];
106
+ if (!f.ended)
107
+ lines.push('5-hour windows: none ended yet.');
108
+ else
109
+ lines.push(`5-hour windows: ${f.ended} ended, ${f.exact} with a reading close enough to the reset to know the final number.`, f.exact ? ` Left at reset: median ${Math.round(f.medianLeftPct)}%; ${f.withLeft} of ${f.exact} had ${LEFT_PCT}% or more left.` : ' None measured exactly yet.');
110
+ if (p.weeks.length) {
111
+ lines.push('Weeks:');
112
+ for (const w of p.weeks)
113
+ lines.push(` week to ${day(w.resetsAt)}: ${Math.round(w.leftPct)}% of the weekly allowance reset unused${w.exact ? '' : ' (at most: the last reading came before the reset)'}`);
114
+ }
115
+ else
116
+ lines.push('Weeks: none finished yet, so the weekly side is still unknown.');
117
+ const q = p.premise;
118
+ lines.push(q.windows
119
+ ? `The premise: ${q.hits} of ${q.windows} measured windows (${q.sharePct}%) reset with ${LEFT_PCT}%+ left in a week that still had ${WEEK_SLACK_PCT}%+ spare. That is capacity an away run could have used.`
120
+ : 'The premise: not measurable yet (needs a finished week with measured windows in it).');
121
+ return lines;
122
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "chompyy",
3
- "version": "0.4.0",
3
+ "version": "0.4.2",
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",