chompyy 0.4.1 → 0.4.3
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 +5 -0
- package/dist/advice.js +383 -0
- package/dist/away.js +4 -1
- package/dist/blueprint.js +45 -0
- package/dist/board.js +61 -2
- package/dist/cli.js +129 -4
- package/dist/detect.js +102 -45
- package/dist/didwork.js +454 -0
- package/dist/nudge.js +438 -0
- package/package.json +1 -1
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/package.json
CHANGED