chompyy 0.4.5 → 0.4.7

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/send.js ADDED
@@ -0,0 +1,294 @@
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 gives every kept card
3
+ // GitHub's main doesn't have its own pull request, from Chompyy's branch chompyy/card-<id> holding the card's own
4
+ // commits, so you merge, skip or revert each card alone on GitHub. (It was one PR for all of them until the user
5
+ // asked for one per card, 2026-11-30.) It never pushes main itself. Once every kept card is on GitHub's main, Send
6
+ // moves your main to match it, so the two don't drift apart.
7
+ import { execFileSync } from 'node:child_process';
8
+ import { realpathSync } from 'node:fs';
9
+ import { resolve } from 'node:path';
10
+ import { homePath, readJson, writeJson } from './home.js';
11
+ import { gitRoot } from './workspace.js';
12
+ import { exe } from './exe.js';
13
+ const git = (dir, args) => execFileSync(exe('git'), ['-C', dir, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim();
14
+ const tryGit = (dir, args) => {
15
+ try {
16
+ return git(dir, args);
17
+ }
18
+ catch {
19
+ return null;
20
+ }
21
+ };
22
+ /** The merge commit Keep makes (review.ts keepCard). */
23
+ const KEEP = /^Keep Chompyy card #(\S+): (.*)$/;
24
+ const sentPath = () => homePath('sent.json');
25
+ /** The repo's one .git folder, as a real path: every folder of the repo (and /var vs /private/var) agrees on it. */
26
+ const commonDir = (repo) => realpathSync(resolve(repo, git(repo, ['rev-parse', '--git-common-dir'])));
27
+ const sentKey = (repo, branch) => `${commonDir(repo)}\n${branch}`;
28
+ /** The PRs Send opened for this branch, by card id (a record from before per-card PRs has none). */
29
+ const sentCards = (repo, branch) => (readJson(sentPath(), {})[sentKey(repo, branch)]?.cards ?? {});
30
+ export const cardBranch = (id) => `chompyy/card-${id}`;
31
+ /** The branches kept cards landed on: one per repo and branch, however many folders the repo has. */
32
+ export function landings(cards) {
33
+ const roots = new Map();
34
+ const dirs = new Map();
35
+ const out = new Map();
36
+ for (const c of cards) {
37
+ const branch = c.run?.base?.branch;
38
+ if (c.outcome !== 'kept' || !c.run?.branch || !branch)
39
+ continue;
40
+ if (!roots.has(c.cwd))
41
+ roots.set(c.cwd, gitRoot(c.cwd));
42
+ const repo = roots.get(c.cwd);
43
+ if (!repo)
44
+ continue;
45
+ if (!dirs.has(repo))
46
+ dirs.set(repo, tryGit(repo, ['rev-parse', '--git-common-dir']) === null ? '' : commonDir(repo));
47
+ const key = `${dirs.get(repo)}\n${branch}`;
48
+ if (dirs.get(repo) && !out.has(key))
49
+ out.set(key, { repo, branch });
50
+ }
51
+ return [...out.values()];
52
+ }
53
+ /** Where `branch` goes on GitHub: its upstream's remote and branch, or null when it has none. */
54
+ function upstreamOf(repo, branch) {
55
+ const remote = tryGit(repo, ['config', `branch.${branch}.remote`]);
56
+ const merge = tryGit(repo, ['config', `branch.${branch}.merge`]);
57
+ if (!remote || remote === '.' || !merge?.startsWith('refs/heads/'))
58
+ return null;
59
+ return { remote, base: merge.slice('refs/heads/'.length) };
60
+ }
61
+ /** What Send would send from `branch`, from what this Mac last fetched (no network). Null: nothing to compare with. */
62
+ export function outbox(repo, branch) {
63
+ const up = upstreamOf(repo, branch);
64
+ const tip = tryGit(repo, ['rev-parse', '--verify', '-q', `refs/heads/${branch}`]);
65
+ if (!up || !tip || !tryGit(repo, ['rev-parse', '--verify', '-q', `refs/remotes/${up.remote}/${up.base}`]))
66
+ return null;
67
+ return outboxAt(repo, branch, up.remote, up.base, tip);
68
+ }
69
+ /**
70
+ * Keep's merges on the branch's own line (first parent) whose card isn't on GitHub's base yet. A card counts as
71
+ * there once its own commits are, however they got there: its PR, or an older Send that carried all of main.
72
+ */
73
+ function unsentKeeps(repo, tip, upstream) {
74
+ const keeps = git(repo, ['log', '--first-parent', '--merges', '--reverse', '--format=%P%x09%s', tip, `^${upstream}`])
75
+ .split('\n')
76
+ .flatMap((line) => {
77
+ const tab = line.indexOf('\t');
78
+ const parents = line.slice(0, tab).split(' ');
79
+ const m = KEEP.exec(line.slice(tab + 1));
80
+ return m && parents[1] ? [{ id: m[1], title: m[2], tip: parents[1] }] : [];
81
+ });
82
+ if (!keeps.length)
83
+ return [];
84
+ const missing = new Set(git(repo, ['rev-list', ...keeps.map((k) => k.tip), `^${upstream}`]).split('\n'));
85
+ return keeps.filter((k) => missing.has(k.tip));
86
+ }
87
+ function outboxAt(repo, branch, remote, base, tip) {
88
+ const upstream = `refs/remotes/${remote}/${base}`;
89
+ const sent = sentCards(repo, branch);
90
+ const cards = unsentKeeps(repo, tip, upstream).map((k) => {
91
+ const rec = sent[k.id];
92
+ return { ...k, pr: rec && rec.tip === k.tip ? { number: rec.number, url: rec.url } : null };
93
+ });
94
+ const own = Number(git(repo, ['rev-list', '--count', '--first-parent', '--no-merges', tip, `^${upstream}`]));
95
+ return { repo, branch, remote, base, cards, fresh: cards.filter((c) => !c.pr), own };
96
+ }
97
+ /** Every landing branch with kept cards GitHub doesn't have, for the app (`chompyy state`). */
98
+ export function outboxes(cards) {
99
+ const out = [];
100
+ for (const l of landings(cards)) {
101
+ try {
102
+ const o = outbox(l.repo, l.branch);
103
+ if (o?.cards.length)
104
+ out.push(o);
105
+ }
106
+ catch { }
107
+ }
108
+ return out;
109
+ }
110
+ /** Files where `tip` and GitHub's base change the same lines, or [] (git before 2.38 can't tell: then []). */
111
+ export function clashFiles(repo, upstream, tip) {
112
+ try {
113
+ execFileSync(exe('git'), ['-C', repo, 'merge-tree', '--write-tree', '--name-only', upstream, tip], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] });
114
+ return [];
115
+ }
116
+ catch (e) {
117
+ const err = e;
118
+ if (err.status !== 1 || !err.stdout)
119
+ return [];
120
+ const files = [];
121
+ for (const line of err.stdout.split('\n').slice(1)) {
122
+ if (!line.trim())
123
+ break; // the conflicted files end at the first blank line; messages follow
124
+ files.push(line.trim());
125
+ }
126
+ return [...new Set(files)];
127
+ }
128
+ }
129
+ /** "owner/repo" from a GitHub remote URL (https or ssh), else null. */
130
+ export function githubRepo(url) {
131
+ return /github\.com[:/]+([^/\s]+\/[^/\s]+?)(?:\.git)?\/?$/.exec(url.trim())?.[1] ?? null;
132
+ }
133
+ const plural = (n, one, many = `${one}s`) => `${n} ${n === 1 ? one : many}`;
134
+ const fileList = (files) => files.slice(0, 3).join(', ') + (files.length > 3 ? ` and ${files.length - 3} more` : '');
135
+ /** No "#31" in GitHub text: GitHub would link card 31 to its own PR or issue #31. */
136
+ export function prTitle(card) {
137
+ return `Kept card ${card.id}: ${card.title}`;
138
+ }
139
+ export function prBody(card, o) {
140
+ const lines = [
141
+ `Merge this to land card ${card.id} on ${o.base}: ${card.title}${o.checks ? ` (${o.checks})` : ''}. It is already on ${o.branch} on the Mac that sent it, kept with Chompyy.`,
142
+ ];
143
+ if (o.after)
144
+ lines.push('', `It was built on card ${o.after.id}: merge PR #${o.after.pr} first. Until then this PR shows that card's changes too.`);
145
+ if (o.clash.length)
146
+ lines.push('', `It clashes with ${o.base} in ${fileList(o.clash)}: resolve that here before merging.`);
147
+ lines.push('', 'Each kept card gets its own PR, so you can merge or revert it alone (`chompyy send`).');
148
+ return lines.join('\n');
149
+ }
150
+ /** 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. */
151
+ export function checksOf(card) {
152
+ const result = card?.run?.verified?.result ?? card?.run?.checks?.result;
153
+ return result === 'passed' ? 'checks passed' : result === 'failed' ? 'checks failed' : null;
154
+ }
155
+ const realGh = (repo, args, input) => execFileSync(exe('gh'), args, { cwd: repo, encoding: 'utf8', input, stdio: [input === undefined ? 'ignore' : 'pipe', 'pipe', 'pipe'] }).trim();
156
+ /** The folder that has `branch` checked out, if any. */
157
+ function folderWith(repo, branch) {
158
+ for (const b of git(repo, ['worktree', 'list', '--porcelain']).split('\n\n')) {
159
+ const dir = b.match(/^worktree (.+)$/m)?.[1];
160
+ if (dir && b.includes(`\nbranch refs/heads/${branch}`))
161
+ return dir;
162
+ }
163
+ return null;
164
+ }
165
+ /**
166
+ * Every kept card is on GitHub's base: move your branch there when that loses nothing, so the two don't drift apart.
167
+ * With per-card PRs GitHub merges each card's own commits, and Keep's merges stay on your branch only.
168
+ */
169
+ function catchUp(repo, branch, upstream, base, tip) {
170
+ const done = `Nothing to send: GitHub's ${base} has every kept card already`;
171
+ const there = git(repo, ['rev-parse', upstream]);
172
+ if (tip === there)
173
+ return { message: `${done}.`, url: null };
174
+ const own = Number(git(repo, ['rev-list', '--count', '--first-parent', '--no-merges', tip, `^${upstream}`]));
175
+ if (own)
176
+ return { message: `${done}. Push your own ${plural(own, 'commit')} on ${branch} yourself: Send only carries kept cards.`, url: null };
177
+ // Your branch may only add Keep's merges: merged into GitHub's base, it would change nothing.
178
+ const merged = tryGit(repo, ['merge-tree', '--write-tree', upstream, tip])?.split('\n')[0];
179
+ if (merged !== git(repo, ['rev-parse', `${upstream}^{tree}`]))
180
+ return { message: `${done}. Your ${branch} differs from GitHub's: run git pull there.`, url: null };
181
+ const folder = folderWith(repo, branch);
182
+ try {
183
+ if (folder)
184
+ git(folder, ['reset', '-q', '--keep', there]); // keeps your unsaved changes; refuses if they'd clash
185
+ else
186
+ git(repo, ['update-ref', `refs/heads/${branch}`, there, tip]);
187
+ }
188
+ catch (e) {
189
+ return { message: `${done}. Your ${branch} couldn't move to GitHub's: ${e.message.split('\n')[0]}`, url: null };
190
+ }
191
+ return { message: `${done}: your ${branch} now matches GitHub's.`, url: null };
192
+ }
193
+ /** Send one landing branch: fetch GitHub's base, then push each kept card's branch and open or update its PR. */
194
+ export function sendOne(repo, branch, cards, deps) {
195
+ const up = upstreamOf(repo, branch);
196
+ if (!up)
197
+ throw new Error(`Link ${branch} to GitHub first (git branch -u origin/${branch}): it has no branch there to merge into. Nothing was sent.`);
198
+ const { remote, base } = up;
199
+ const slug = githubRepo(tryGit(repo, ['config', `remote.${remote}.url`]) ?? '');
200
+ if (!slug)
201
+ throw new Error(`Send works with GitHub only, and ${remote} isn't on GitHub. Nothing was sent.`);
202
+ const upstream = `refs/remotes/${remote}/${base}`;
203
+ // GitHub's latest first, so what's sent is about what is there now. Card branches merged and deleted drop out.
204
+ git(repo, ['fetch', '-q', remote, `+refs/heads/${base}:${upstream}`]);
205
+ tryGit(repo, ['fetch', '-q', '--prune', remote, `+refs/heads/chompyy/card-*:refs/remotes/${remote}/chompyy/card-*`]);
206
+ const tip = git(repo, ['rev-parse', `refs/heads/${branch}`]);
207
+ const o = outboxAt(repo, branch, remote, base, tip);
208
+ if (!o.cards.length)
209
+ return catchUp(repo, branch, upstream, base, tip);
210
+ try {
211
+ deps.gh(repo, ['auth', 'status']);
212
+ }
213
+ catch {
214
+ throw new Error("Install GitHub's gh and sign in first: brew install gh, then gh auth login.\nNothing was sent.");
215
+ }
216
+ const open = new Map(JSON.parse(deps.gh(repo, ['pr', 'list', '--repo', slug, '--state', 'open', '--json', 'number,url,headRefName', '--limit', '200']) || '[]').map((p) => [p.headRefName, { number: p.number, url: p.url }]));
217
+ const byId = new Map(cards.map((c) => [c.id, c]));
218
+ const sent = [];
219
+ const errors = [];
220
+ const all = readJson(sentPath(), {});
221
+ const rec = (all[sentKey(repo, branch)] = { cards: { ...(all[sentKey(repo, branch)]?.cards ?? {}) } });
222
+ for (const [i, card] of o.cards.entries()) {
223
+ const head = cardBranch(card.id);
224
+ const remoteRef = `refs/remotes/${remote}/${head}`;
225
+ try {
226
+ // Built on an earlier kept card that isn't on GitHub yet (it started from your main): its PR carries that
227
+ // card's commits too until that one merges. Based on main still, so merging it can never land elsewhere.
228
+ const reach = new Set(git(repo, ['rev-list', card.tip, `^${upstream}`]).split('\n'));
229
+ const before = o.cards.slice(0, i).filter((e) => reach.has(e.tip)).at(-1);
230
+ const beforePr = before && (sent.find((s) => s.card.id === before.id)?.pr ?? open.get(cardBranch(before.id)));
231
+ const clash = clashFiles(repo, upstream, card.tip);
232
+ const there = tryGit(repo, ['rev-parse', '--verify', '-q', remoteRef]);
233
+ if (there !== card.tip) {
234
+ git(repo, ['push', '-q', `--force-with-lease=refs/heads/${head}:${there ?? ''}`, remote, `${card.tip}:refs/heads/${head}`]);
235
+ tryGit(repo, ['update-ref', remoteRef, card.tip]);
236
+ }
237
+ const body = prBody(card, { base, branch, checks: checksOf(byId.get(card.id)), after: before && beforePr ? { id: before.id, pr: beforePr.number } : null, clash });
238
+ let pr = open.get(head);
239
+ const isNew = !pr;
240
+ if (pr) {
241
+ if (there !== card.tip)
242
+ deps.gh(repo, ['pr', 'edit', String(pr.number), '--repo', slug, '--body-file', '-'], body);
243
+ }
244
+ else {
245
+ const url = deps.gh(repo, ['pr', 'create', '--repo', slug, '--base', base, '--head', head, '--title', prTitle(card), '--body-file', '-'], body).split('\n').pop().trim();
246
+ pr = { number: Number(/\/pull\/(\d+)/.exec(url)?.[1] ?? 0), url };
247
+ }
248
+ rec.cards[card.id] = { number: pr.number, url: pr.url, tip: card.tip, at: deps.now().toISOString() };
249
+ sent.push({ card, pr, isNew, clash });
250
+ }
251
+ catch (e) {
252
+ errors.push(`card ${card.id}: ${e.message.split('\n')[0]}`);
253
+ }
254
+ }
255
+ writeJson(sentPath(), all);
256
+ if (!sent.length)
257
+ throw new Error(`Nothing was sent: ${errors[0]}`);
258
+ const clashing = sent.filter((s) => s.clash.length).length;
259
+ const fresh = sent.filter((s) => s.isNew).length;
260
+ const url = sent.length === 1 ? sent[0].pr.url : `https://github.com/${slug}/pulls?q=${encodeURIComponent('is:pr is:open "Kept card" in:title')}`;
261
+ const what = sent.length === 1 ? `PR #${sent[0].pr.number}` : `${sent.length} PRs`;
262
+ const how = sent.length === 1 ? ` to land kept card ${sent[0].card.id} on ${base}` : `, one per kept card, to land them on ${base}`;
263
+ const news = fresh === sent.length ? '' : fresh ? ` (${fresh} new)` : sent.length === 1 ? ' (sent before)' : ' (all sent before)';
264
+ const notes = [clashing ? `${plural(clashing, 'clashes', 'clash')} with ${base}: resolve on GitHub` : '', errors.length ? `${plural(errors.length, 'card')} not sent: ${errors[0]}` : '']
265
+ .filter(Boolean)
266
+ .join('; ');
267
+ return { message: `Merge ${what} on GitHub${how}${news}${notes ? `. ${notes}` : ''}.\n${url}`, url };
268
+ }
269
+ /** `chompyy send`: every landing branch with kept cards GitHub doesn't have. */
270
+ export function sendKept(cards, deps = {}) {
271
+ const d = { gh: deps.gh ?? realGh, now: deps.now ?? (() => new Date()) };
272
+ const ls = landings(cards);
273
+ if (!ls.length)
274
+ return { message: 'Nothing to send: keep a card first.', url: null };
275
+ const linked = ls.filter((l) => upstreamOf(l.repo, l.branch));
276
+ if (!linked.length)
277
+ 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.`);
278
+ const results = [];
279
+ const errors = [];
280
+ for (const l of linked) {
281
+ try {
282
+ results.push(sendOne(l.repo, l.branch, cards, d));
283
+ }
284
+ catch (e) {
285
+ errors.push(e.message);
286
+ }
287
+ }
288
+ const sent = results.filter((r) => r.url);
289
+ if (errors.length && !results.length)
290
+ throw new Error(errors[0]);
291
+ if (!sent.length)
292
+ return results[0] ?? { message: 'Nothing to send: GitHub has every kept card already.', url: null };
293
+ return { message: [...sent.map((r) => r.message), ...errors].join('\n'), url: sent[0].url };
294
+ }
@@ -0,0 +1,110 @@
1
+ // The cache timer in Claude Code's status line (2026-11-30). Claude Code 2.1.251+ hands the status line
2
+ // `prompt_cache`: when the main conversation's cache goes cold and what the next message rewrites then. It re-runs
3
+ // the status line the moment the cache expires, so a clock time ("warm till 14:32") stays true without a refresh
4
+ // timer. The nudge stops the first message after the cache expired; this shows it before you type.
5
+ //
6
+ // `chompyy statusline on` keeps the status line you had: Chompyy runs it on the same input and prints its line
7
+ // above Chompyy's (Orca's, for one, prints nothing and only reports to Orca).
8
+ import { spawnSync } from 'node:child_process';
9
+ import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
10
+ import { homedir } from 'node:os';
11
+ import { dirname } from 'node:path';
12
+ import { homePath } from './home.js';
13
+ import { claudeSettingsPath, MIN_CONTEXT, readSettings, selfCommand } from './nudge.js';
14
+ const MARK = '# chompyy statusline';
15
+ const k = (n) => (n >= 1e6 ? `${(n / 1e6).toFixed(1)}M` : `${Math.round(n / 1000)}k`);
16
+ const hhmm = (ms) => new Date(ms).toLocaleTimeString('en-GB', { hour: '2-digit', minute: '2-digit' });
17
+ /**
18
+ * The cache part of the line, or null when there's nothing worth saying: a conversation too small for a cold cache
19
+ * to matter (the nudge's 40k), one just compacted, caching off, or a Claude Code too old to report it.
20
+ */
21
+ export function cacheText(stdin, now) {
22
+ let pc;
23
+ try {
24
+ pc = JSON.parse(stdin).prompt_cache;
25
+ }
26
+ catch {
27
+ return null;
28
+ }
29
+ const tokens = pc?.recache_tokens_if_cold;
30
+ if (!pc?.caching_observed || typeof tokens !== 'number' || tokens < MIN_CONTEXT)
31
+ return null;
32
+ const expires = typeof pc.expires_at === 'number' ? pc.expires_at * 1000 : 0;
33
+ if (pc.warm && expires > now.getTime())
34
+ return { cold: false, text: `cache warm till ${hhmm(expires)}` };
35
+ return { cold: true, text: `/compact first: cache cold, next message rewrites ${k(tokens)}` };
36
+ }
37
+ /** Cold goes first, where a long line can't cut it off; warm goes last, dim. */
38
+ export function composeLine(quota, cache, color = false) {
39
+ if (!cache)
40
+ return quota;
41
+ const paint = (code, s) => (color ? `\u001b[${code}m${s}\u001b[0m` : s);
42
+ return cache.cold ? `🍪 ${paint(33, cache.text)} | ${quota.replace(/^🍪 /, '')}` : `${quota} | ${paint(2, cache.text)}`;
43
+ }
44
+ /** Run the status line you had on the same input. One that fails or takes over `timeoutMs` prints nothing. */
45
+ export function runWrapped(command, stdin, timeoutMs = 3_000) {
46
+ try {
47
+ const r = spawnSync('/bin/sh', ['-c', command], { input: stdin, encoding: 'utf8', timeout: timeoutMs, env: process.env });
48
+ return r.status === 0 && typeof r.stdout === 'string' ? r.stdout.replace(/\s+$/, '') : '';
49
+ }
50
+ catch {
51
+ return '';
52
+ }
53
+ }
54
+ /** Your status line's output above Chompyy's line. */
55
+ export function statusLineOutput(ours, wrapped, stdin) {
56
+ const theirs = wrapped ? runWrapped(wrapped, stdin) : '';
57
+ return theirs ? `${theirs}\n${ours}` : ours;
58
+ }
59
+ const savedPath = () => homePath('statusline.json');
60
+ const isOurs = (s) => Boolean(s?.command?.includes(MARK));
61
+ /** The status line Chompyy wraps, saved when it was turned on. */
62
+ function saved() {
63
+ try {
64
+ return JSON.parse(readFileSync(savedPath(), 'utf8'));
65
+ }
66
+ catch {
67
+ return null;
68
+ }
69
+ }
70
+ export function wrappedCommand() {
71
+ return saved()?.wrapped?.command ?? null;
72
+ }
73
+ export function statuslineInstalled(path = claudeSettingsPath()) {
74
+ try {
75
+ return isOurs(readSettings(path).settings.statusLine);
76
+ }
77
+ catch {
78
+ return false;
79
+ }
80
+ }
81
+ export const statuslineCommand = (script, node) => `${selfCommand(script, node)} statusline ${MARK}`;
82
+ /** Point Claude Code's status line at Chompyy, keeping the one you had inside it; off gives yours back. Backs the file up first. */
83
+ export function setStatusline(on, command, path = claudeSettingsPath()) {
84
+ const { settings, raw } = readSettings(path);
85
+ const current = settings.statusLine;
86
+ const where = path.replace(homedir(), '~');
87
+ if (on) {
88
+ const wrapped = isOurs(current) ? (saved()?.wrapped ?? null) : (current ?? null);
89
+ mkdirSync(dirname(savedPath()), { recursive: true });
90
+ writeFileSync(savedPath(), JSON.stringify({ wrapped }, null, 2) + '\n');
91
+ settings.statusLine = { ...(wrapped ?? {}), type: 'command', command: command ?? statuslineCommand() };
92
+ }
93
+ else {
94
+ if (current && !isOurs(current))
95
+ return `Nothing to turn off: the status line in ${where} isn't Chompyy's.`;
96
+ const wrapped = saved()?.wrapped ?? null;
97
+ if (wrapped)
98
+ settings.statusLine = wrapped;
99
+ else
100
+ delete settings.statusLine;
101
+ rmSync(savedPath(), { force: true });
102
+ }
103
+ if (raw !== null)
104
+ writeFileSync(`${path}.chompyy-backup`, raw);
105
+ mkdirSync(dirname(path), { recursive: true });
106
+ writeFileSync(path, JSON.stringify(settings, null, 2) + '\n');
107
+ return on
108
+ ? `Restart open conversations to see the cache timer. (Status line set in ${where}${current && !isOurs(current) ? '; yours still runs above it' : ''}; old file saved as .chompyy-backup.)`
109
+ : `Cache timer off. (${existsSync(path) && settings.statusLine ? 'Your status line is back' : 'Status line removed'} in ${where}.)`;
110
+ }
package/dist/suggest.js CHANGED
@@ -9,6 +9,7 @@ import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs';
9
9
  import { basename, join } from 'node:path';
10
10
  import { addCard } from './board.js';
11
11
  import { readTaste } from './taste.js';
12
+ import { exe } from './exe.js';
12
13
  /** Vision and convention docs, in order of how much they say about where the repo is going. */
13
14
  const DOCS = ['README.md', 'VISION.md', 'ROADMAP.md', 'FEATURES.md', 'PLAN.md', 'TODO.md', 'CONTRIBUTING.md', 'CLAUDE.md', 'AGENTS.md'];
14
15
  const PER_DOC = 6000;
@@ -19,12 +20,12 @@ const MAX_DIGEST = 40_000;
19
20
  */
20
21
  function safeGit(repo, args) {
21
22
  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
+ const r = spawnSync(exe('git'), ['-c', 'core.fsmonitor=false', '-c', 'core.hooksPath=/dev/null', '-C', repo, ...args], { encoding: 'utf8', env, timeout: 15_000, maxBuffer: 4 << 20 });
23
24
  return r.status === 0 ? r.stdout : '';
24
25
  }
25
26
  /** Open issues through your own `gh`, when the repo is on GitHub and gh is logged in. Optional: [] otherwise. */
26
27
  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
+ const r = spawnSync(exe('gh'), ['issue', 'list', '--state', 'open', '--limit', '30', '--json', 'number,title'], { cwd: repo, encoding: 'utf8', timeout: 20_000 });
28
29
  if (r.status !== 0)
29
30
  return [];
30
31
  try {
@@ -0,0 +1,79 @@
1
+ // Near-duplicate taste.md lines: find them and propose one merged line. Deterministic, no model calls,
2
+ // and nothing is written: callers decide what to do with a proposal.
3
+ //
4
+ // Similarity is a token-set score (Jaccard: shared words / all distinct words) over the instruction text,
5
+ // lowercased, with the learned suffix "(learned … · from cards #3 · p12)", the pN id and filler words removed.
6
+ /** Pairs scoring at or above this are flagged. Measured on the test fixtures: true duplicates score 0.42–0.44, the must-not-merge pair 0.125. */
7
+ export const MERGE_THRESHOLD = 0.4;
8
+ const SUFFIX = /\s+\((?:learned|from your history|merged)[^)]*\)\s*$/;
9
+ const STOP = new Set('a an the and or for with to in on of at by as is are be it its this that then too my their your our me i so'.split(' '));
10
+ /** Parse one taste.md bullet. Null for headings, comments, blanks and anything not a "- " bullet. */
11
+ export function parseTasteLine(raw) {
12
+ const m = raw.match(/^\s*[-*]\s+(.+)$/);
13
+ const body = m?.[1];
14
+ if (!body)
15
+ return null;
16
+ const suffix = body.match(SUFFIX)?.[0] ?? '';
17
+ const text = body.slice(0, body.length - suffix.length).trim();
18
+ if (!text)
19
+ return null;
20
+ return {
21
+ text,
22
+ ids: [...new Set(suffix.match(/\bp\d+\b/g) ?? [])],
23
+ cards: [...new Set(suffix.match(/#\d+/g) ?? [])],
24
+ };
25
+ }
26
+ function tokens(text) {
27
+ return new Set(text
28
+ .toLowerCase()
29
+ .replace(/\bp\d+\b/g, ' ')
30
+ .split(/[^a-z0-9]+/)
31
+ .filter((t) => t && !STOP.has(t)));
32
+ }
33
+ /** Token-set (Jaccard) similarity of two instruction texts, 0..1. */
34
+ export function similarity(a, b) {
35
+ const ta = tokens(a);
36
+ const tb = tokens(b);
37
+ if (!ta.size || !tb.size)
38
+ return 0;
39
+ let shared = 0;
40
+ for (const t of ta)
41
+ if (tb.has(t))
42
+ shared++;
43
+ return shared / (ta.size + tb.size - shared);
44
+ }
45
+ /** Every pair of bullet lines scoring at or above the threshold, highest score first. */
46
+ export function findNearDuplicates(lines, threshold = MERGE_THRESHOLD) {
47
+ const parsed = lines.map(parseTasteLine);
48
+ const out = [];
49
+ for (let i = 0; i < parsed.length; i++) {
50
+ const pi = parsed[i];
51
+ if (!pi)
52
+ continue;
53
+ for (let j = i + 1; j < parsed.length; j++) {
54
+ const pj = parsed[j];
55
+ if (!pj)
56
+ continue;
57
+ const score = similarity(pi.text, pj.text);
58
+ if (score >= threshold)
59
+ out.push({ a: i, b: j, score });
60
+ }
61
+ }
62
+ return out.sort((x, y) => y.score - x.score || x.a - y.a || x.b - y.b);
63
+ }
64
+ const byNumber = (x, y) => Number(x.replace(/\D/g, '')) - Number(y.replace(/\D/g, ''));
65
+ /**
66
+ * One merged line for two near-duplicates. Keeps the longer instruction (it usually carries more of the
67
+ * rule) and the union of both lines' pN ids and card refs, so no evidence is lost.
68
+ */
69
+ export function proposeMerge(a, b) {
70
+ const pa = parseTasteLine(a);
71
+ const pb = parseTasteLine(b);
72
+ if (!pa || !pb)
73
+ throw new Error('proposeMerge needs two taste.md bullet lines');
74
+ const text = pb.text.length > pa.text.length ? pb.text : pa.text;
75
+ const ids = [...new Set([...pa.ids, ...pb.ids])].sort(byNumber);
76
+ const cards = [...new Set([...pa.cards, ...pb.cards])].sort(byNumber);
77
+ const parts = ['merged', ...(cards.length ? [`from cards ${cards.join(', ')}`] : []), ...(ids.length ? [ids.join(' + ')] : [])];
78
+ return { text, ids, cards, line: `- ${text} (${parts.join(' · ')})` };
79
+ }
package/dist/taste.js CHANGED
@@ -43,13 +43,21 @@ export function insertUnderHeading(text, scope, line) {
43
43
  rows.splice(end, 0, line);
44
44
  return rows.join('\n');
45
45
  }
46
- /** taste.md for agents: drop the header comment so prompts carry only the preferences. Empty when nothing learned. */
46
+ /**
47
+ * taste.md for agents: drop the header comment so prompts carry only the preferences. Empty when nothing learned.
48
+ * A line whose id is retired in preferences.json never reaches a run, even if it was pasted back by hand.
49
+ */
47
50
  export function tasteForPrompt() {
48
51
  const path = tastePath();
49
52
  if (!existsSync(path))
50
53
  return '';
54
+ const retired = new Set(loadStore().prefs.filter((p) => p.status === 'retired').map((p) => p.id));
51
55
  const lines = readFileSync(path, 'utf8')
52
56
  .split('\n')
57
+ .filter((l) => {
58
+ const id = l.match(MARK)?.[1];
59
+ return !id || !retired.has(id);
60
+ })
53
61
  .map((l) => l.replace(/\s+\((learned|from your history)[^)]*\)\s*$/, ''));
54
62
  const kept = lines.filter((l) => /^\s*[-*]\s+\S/.test(l) || l.startsWith('## '));
55
63
  // Only headings, no preferences: nothing to say.
@@ -57,6 +65,29 @@ export function tasteForPrompt() {
57
65
  return '';
58
66
  return kept.join('\n').replace(/(## [^\n]+\n)(?=## |$)/g, '').trim();
59
67
  }
68
+ const DAY_MS = 86_400_000;
69
+ /**
70
+ * Learned lines in taste.md: every "(learned …)" line counts toward the total; those dated within 7 days of
71
+ * `now` also count as new. An undated or badly dated line counts toward the total only.
72
+ */
73
+ export function learnedCount(text, now) {
74
+ let total = 0;
75
+ let newWithin7Days = 0;
76
+ for (const line of text.split('\n')) {
77
+ const m = line.match(/\(learned\b([^)]*)\)\s*$/);
78
+ if (!m)
79
+ continue;
80
+ total++;
81
+ const date = m[1].match(/\b(\d{4}-\d{2}-\d{2})\b/)?.[1];
82
+ const at = date ? Date.parse(`${date}T00:00:00Z`) : NaN;
83
+ if (Number.isNaN(at))
84
+ continue;
85
+ const days = Math.floor((now.getTime() - at) / DAY_MS);
86
+ if (days >= 0 && days < 7)
87
+ newWithin7Days++;
88
+ }
89
+ return { total, newWithin7Days };
90
+ }
60
91
  export function signalsPath() {
61
92
  return homePath('signals.jsonl');
62
93
  }
@@ -117,6 +148,8 @@ export function signalWeight(s) {
117
148
  return 1;
118
149
  if (s.kind === 'chat')
119
150
  return 2;
151
+ if (s.kind === 'advice-declined')
152
+ return 2;
120
153
  return 0;
121
154
  }
122
155
  /** One line per signal, for the distiller prompt and for "why do you think that?". */
@@ -137,6 +170,8 @@ export function describeSignal(s, max = 400) {
137
170
  return `${s.raw.outcome === 'undone' ? 'undid' : 'kept'} the result of ${card}`;
138
171
  case 'answer':
139
172
  return `answered the questions of ${card}: "${cut(s.raw.text)}"`;
173
+ case 'advice-declined':
174
+ return `declined the advice ${card} (${s.raw.key}): never suggest it again`;
140
175
  case 'chat': {
141
176
  const where = String(s.raw.workspace ?? '').split('/').pop() || 'a session';
142
177
  return `said in a session in ${where} on ${s.at.slice(0, 10)}: "${cut(s.raw.quote)}"${s.raw.why ? ` (${cut(s.raw.why, 200)})` : ''}`;
@@ -327,10 +362,10 @@ export function retire(p, because, now, against = []) {
327
362
  p.against = [...(p.against ?? []), ...against];
328
363
  p.updatedAt = p.retiredAt;
329
364
  }
330
- /** Signals the distiller should read: governed, about cards, not yet seen. */
365
+ /** Signals the distiller should read: not yet seen, and from a governed card, a session (chat) or advice you declined. */
331
366
  export function newSignals(store, signals, governed) {
332
367
  const seen = store.seenThrough ?? 0;
333
- return signals.filter((s) => Number(s.id.slice(1)) > seen && signalWeight(s) > 0 && (s.kind === 'chat' || (s.card && governed.has(s.card))));
368
+ return signals.filter((s) => Number(s.id.slice(1)) > seen && signalWeight(s) > 0 && (s.kind === 'chat' || s.kind === 'advice-declined' || (s.card && governed.has(s.card))));
334
369
  }
335
370
  /** Read new signals with the model and update preferences.json. Runs at most once per call; nothing to read = no model call. */
336
371
  export async function distill(board, runner, opts) {
@@ -411,7 +446,8 @@ export function retirePreference(id, now) {
411
446
  return p;
412
447
  }
413
448
  // ---------- taste.md stays in step ----------
414
- const MARK = /\s+·\s+(p\d+)\)\s*$/;
449
+ /** The "· pN)" id at the end of a learned line. Tolerates hand-edit spacing like "· p3 )". */
450
+ const MARK = /\s*·\s*(p\d+)\s*\)\s*$/;
415
451
  export function learnedLine(p, signals) {
416
452
  const byId = new Map(signals.map((s) => [s.id, s]));
417
453
  const cards = [...new Set(p.evidence.map((e) => byId.get(e)?.card).filter(Boolean))].map((c) => `#${c}`);
package/dist/triggers.js CHANGED
@@ -9,6 +9,7 @@ import { dirname, join } from 'node:path';
9
9
  import { budgetGate } from './gate.js';
10
10
  import { homePath, readJson, writeJson } from './home.js';
11
11
  import { windowView } from './quota.js';
12
+ import { exe } from './exe.js';
12
13
  const statePath = () => homePath('triggers.json');
13
14
  export const loadTriggerState = () => readJson(statePath(), { fired: [] });
14
15
  export function markFired(key, now, why) {
@@ -155,7 +156,7 @@ ${env}
155
156
  `;
156
157
  }
157
158
  function launchctl(args) {
158
- execFileSync('launchctl', args, { stdio: 'ignore' });
159
+ execFileSync(exe('launchctl'), args, { stdio: 'ignore' });
159
160
  }
160
161
  /** Install (or reinstall) the LaunchAgent that runs `chompyy tick` every 5 minutes. */
161
162
  export function installAgent() {
package/dist/verify.js CHANGED
@@ -117,13 +117,16 @@ export async function verifyRun(opts) {
117
117
  rmSync(linked);
118
118
  }
119
119
  }
120
+ // Enough for a whole test run: the names of failing tests are read from it, and a 20k tail cut off the first
121
+ // failures of a run with a dozen (each prints its stack), so they looked new on the card (2026-11-30).
122
+ const MAX_OUTPUT = 2_000_000;
120
123
  export function run(argv, cwd, env, timeoutMs) {
121
124
  return new Promise((resolve, reject) => {
122
125
  const child = spawn(argv[0], argv.slice(1), { cwd, env, stdio: ['ignore', 'pipe', 'pipe'], detached: true });
123
126
  let output = '';
124
127
  let timedOut = false;
125
128
  const add = (d) => {
126
- output = (output + d.toString()).slice(-20_000);
129
+ output = (output + d.toString()).slice(-MAX_OUTPUT);
127
130
  };
128
131
  child.stdout.on('data', add);
129
132
  child.stderr.on('data', add);