chompyy 0.4.4 → 0.4.5

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/cli.js CHANGED
@@ -41,6 +41,7 @@ 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';
45
46
  import { formatLive, keepAffectsLive, liveOff, liveSet, liveUpdateLocked, loadLive, startLiveUpdate } from './live.js';
46
47
  import { agentInstalled, awayRunning, bedtimeKey, decideTrigger, installAgent, loadTriggerState, markFired, noteTick, parseClock, takeAwayLock, uninstallAgent } from './triggers.js';
@@ -57,6 +58,8 @@ Quota
57
58
  chompyy advise apply apply approved settings advice now, if no session has been active for 10 minutes
58
59
  chompyy worked [--json] did it work? measure each approved advice card against the check on its card
59
60
  chompyy worked --share the same as a summary to paste (no project, skill or file names)
61
+ chompyy suggest [repo] [--force] a few tasks for a repo from its docs, issues and TODOs, as suggested cards
62
+ (one model call; waits for an active 5-hour window unless --force)
60
63
  chompyy nudge on|off live suggestions while you work: stops the first message to a big conversation
61
64
  whose cache expired, with the price and the cheaper ways (Claude Code hook)
62
65
  chompyy nudge strict|quiet|learn [dir] in this project: always stop me, only a heads-up, or learn (default:
@@ -1177,6 +1180,23 @@ async function main(argv) {
1177
1180
  return console.log(nudgeProofText(proof).join('\n'));
1178
1181
  return console.log([workedText(cards), ...(proof ? ['', ...nudgeProofText(proof)] : [])].join('\n'));
1179
1182
  }
1183
+ case 'suggest': {
1184
+ // A few tasks for a repo, from what it wants to become and what its code shows: suggested cards to approve.
1185
+ const repo = gitRoot(resolve(args[0] ?? process.cwd()));
1186
+ if (!repo)
1187
+ throw new Error(`${args[0] ?? 'This folder'} isn't in a git repo. chompyy suggest <repo folder>`);
1188
+ const config = loadConfig();
1189
+ if (!claudeAvailable(config.claudeBin))
1190
+ throw new Error('Suggesting tasks needs the claude command (Claude Code in Terminal). See TRY.md.');
1191
+ if (!values.force && !windowActive(now))
1192
+ throw new Error('No active 5-hour window: suggesting now would start one. Try again while you use Claude Code, or add --force.');
1193
+ const existing = loadBoard().cards.map((c) => c.title);
1194
+ const { tasks, dropped } = await suggestTasks(repo, new ClaudeRunner(config.claudeBin), { model: config.suggestModel, cwd: chompyyHome(), existing });
1195
+ const cards = updateBoard((b) => addSuggested(b, repo, tasks, now));
1196
+ if (values.json)
1197
+ return json({ repo, added: cards.map((c) => ({ id: c.id, title: c.title, why: c.why })), dropped });
1198
+ return console.log(suggestText(repo, cards, dropped));
1199
+ }
1180
1200
  case 'hook': {
1181
1201
  // Claude Code's UserPromptSubmit hook. Must never fail loudly or stop a prompt by accident.
1182
1202
  if (args[0] !== 'prompt')
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/pacing.js CHANGED
@@ -123,6 +123,63 @@ 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 spareWindows = windowPct ? unusedPct / windowPct : null;
165
+ const maxReachablePct = windowPct ? Math.min(100, v.usedPct + (v.msLeft / FIVE_HOURS) * windowPct) : null;
166
+ const resets = v.resetsAt * 1000;
167
+ const head = `Week ${Math.round(v.usedPct)}% used.`;
168
+ let line;
169
+ let runsOutAt;
170
+ if (projected >= 100 && rate > 0) {
171
+ runsOutAt = now.getTime() + (100 - v.usedPct) / rate;
172
+ line = `${head} At your pace it runs out ~${dayClock(runsOutAt)}, before the reset ${dayClock(resets)}.`;
173
+ }
174
+ else {
175
+ const spare = spareWindows !== null && spareWindows >= 1 ? `: about ${Math.floor(spareWindows)} full 5-hour window${Math.floor(spareWindows) === 1 ? '' : 's'}` : '';
176
+ line = `${head} At your pace ~${Math.round(unusedPct)}% resets unused on ${dayClock(resets)}${spare}.`;
177
+ if (maxReachablePct !== null && maxReachablePct < 99)
178
+ line += ` Even running every window flat out, you'd reach ~${Math.round(maxReachablePct)}%.`;
179
+ }
180
+ const short = line.slice(head.length + 1);
181
+ return { usedPct: v.usedPct, resetsAt: v.resetsAt, unusedPct, ...(runsOutAt ? { runsOutAt } : {}), windowPct, spareWindows, maxReachablePct, line, short };
182
+ }
126
183
  // ---------- rolling daily allowance ----------
127
184
  /** The day you're in: from your last bedtime (or midnight) to the next. */
128
185
  export function dayBounds(now, bedtime) {
@@ -188,6 +245,7 @@ export function pacing(snap, samples, now, bedtime) {
188
245
  fiveHourDelta: paceDelta(snap?.fiveHour, FIVE_HOURS, now),
189
246
  weekDelta: paceDelta(snap?.sevenDay, WEEK, now),
190
247
  fiveHourForecast: forecastWindow(snap?.fiveHour, FIVE_HOURS, samples, (s) => s.five, now),
248
+ week: weekForecast(snap, samples, now),
191
249
  today: dailyAllowance(snap?.sevenDay, samples, now, bedtime),
192
250
  models,
193
251
  };
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' : ''}`);
@@ -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.5",
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",