chompyy 0.3.0 → 0.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -109,16 +109,17 @@ Each card in a git repo runs in its own worktree at `~/.chompyy/worktrees/<id>`
109
109
  | `chompyy statusline` | Status line hook: reads Claude Code's JSON on stdin, saves the snapshot, prints one line |
110
110
  | `chompyy status` | % left in the 5h window, time to reset, weekly used, pace delta, forecast, today's allowance, per-model weekly windows |
111
111
  | `chompyy eat-tokens` | Read-only view of remaining 5h quota and approved/later cards; starts nothing |
112
- | `chompyy later "<idea>"` | New card in *later*, remembering the current directory. Drafts the blueprint in the background when `claude` is available (`--wait` to wait for it, `--no-blueprint` to skip) |
112
+ | `chompyy later "<idea>"` | New card in *later*, remembering the current directory. Drafts the blueprint in the background when `claude` is available (`--wait` to wait for it, `--no-blueprint` to skip). The card starts titled with the idea's first 60 characters; with the blueprint the same model writes a title of 10 words or fewer (one extra short call, no tools). If that call fails, the first title stays |
113
113
  | `chompyy board [--column approved]` | Cards by column: suggested, later, approved, running, review, done |
114
114
  | `chompyy show <id>` | One card with its blueprint, last run and rating |
115
115
  | `chompyy blueprint <id> [--model m]` | Draft (or redraft) the blueprint with a cheap model |
116
116
  | `chompyy picture <id> [--model m]` | Draw (or redraw) the card's picture: a diagram of what it will do, made with the diagram-design skill. Happens on its own after each blueprint while a window is active (`"pictures": false` in config.json turns it off) |
117
+ | `chompyy edit-idea <id>` | Replace a *later* card's idea (and its title) with text from stdin, e.g. `echo "new idea" \| chompyy edit-idea 3`. The blueprint stays; redraft it with `blueprint <id>` |
117
118
  | `chompyy approve <id>` / `drop <id>` | Queue a card for away runs / remove it (kept in `archive.jsonl`) |
118
119
  | `chompyy away <1h\|30m\|1h30m> [--dry-run] [--force]` | Run approved cards until the time is up or the gate closes |
119
120
  | `chompyy report [--all]` | Cards that ran since the last report: one action each, cards needing you first. No paths or raw agent text; ask for those with `show` |
120
121
  | `chompyy diff <id>` | The change the card made on its branch |
121
- | `chompyy keep <id>` | Merge the card's branch into your current branch and remove its worktree. Refuses if your repo has uncommitted changes |
122
+ | `chompyy keep <id>` | Merge the card's branch into your current branch and remove its worktree. Refuses when you have unsaved changes in a file the card also changed, or anything staged; other unsaved work is left alone |
122
123
  | `chompyy undo <id>` | Throw the run away: remove its worktree and branch (or draft folder). Your own branches are never touched |
123
124
  | `chompyy rate <id> <1-5> ["why"]` | Rate a result against its blueprint; moves it to *done* and logs a signal |
124
125
  | `chompyy taste` | Show `taste.md` |
@@ -127,8 +128,10 @@ Each card in a git repo runs in its own worktree at `~/.chompyy/worktrees/<id>`
127
128
  | `chompyy taste retire <id>` | Stop using a preference; it stays in `taste list` with the reason |
128
129
  | `chompyy distill [--force]` | Read new signals and update preferences now (also runs after every away run) |
129
130
  | `chompyy trends` | Last 7 days vs the 7 before: cost per card, keep rate, rating, blueprint edits |
131
+ | `chompyy premise [--json]` | How often a 5-hour window reset with 20%+ left in a week that still had 10%+ spare: the capacity away runs can use. From your quota readings; every ended window is kept in `windows.jsonl` (numbers only), so it grows past the 8 days of `quota-history.json`. `--json` to share it |
132
+ | `chompyy detect [--days 30] [--all] [--json]` | The detective: what wastes tokens in your setup and habits, from your own files. One screen: the findings ranked by tokens and the fix to start with; `--all` adds each finding's count, measured or estimated, what it doesn't prove, and every fix. A mid-session cache rebuild names its cause (e.g. Tool Search loading an MCP server's tools). Works cold with `npx chompyy detect`, nothing else installed. This version checks startup tax (long CLAUDE.md, unused skills and MCP servers, cut-off MEMORY.md) and cache (cold returns, mid-session rebuilds). Reads only; changes nothing |
130
133
  | `chompyy triggers on\|off` | Install or remove the macOS LaunchAgent that runs `chompyy tick` every 5 minutes |
131
- | `chompyy bedtime <23:30\|off>` / `last-hour <on\|off>` | Turn the bedtime and last-hour-before-reset triggers on or off |
134
+ | `chompyy bedtime <23:30\|off>` / `last-hour <on\|off>` / `missed-reset <on\|off>` | Turn the bedtime, last-hour-before-reset and missed-reset (first tick after an unused reset, default off) triggers on or off |
132
135
 
133
136
  ## Taste
134
137
 
@@ -2,7 +2,7 @@
2
2
 
3
3
  ## Third-party code
4
4
 
5
- `cli/src/vendor/codeburn/`: from [codeburn](https://github.com/getagentseal/codeburn) (MIT, Copyright (c) 2026 AgentSeal). See its `UPSTREAM.md` and `LICENSE`.
5
+ `cli/src/vendor/codeburn/`: from [codeburn](https://github.com/getagentseal/codeburn) (MIT, Copyright (c) 2026 AgentSeal). See its `UPSTREAM.md` and `LICENSE`. Its `prices.ts` holds the Claude rows of codeburn's snapshot of [LiteLLM](https://github.com/BerriAI/litellm)'s `model_prices_and_context_window.json` (MIT, Copyright (c) 2023 Berri AI).
6
6
 
7
7
  Its licence, in full (MIT requires it in every copy, including the npm package):
8
8
 
package/dist/appstate.js CHANGED
@@ -2,19 +2,25 @@
2
2
  // The app holds no logic of its own: it shows this JSON and calls chompyy commands.
3
3
  import { execFileSync } from 'node:child_process';
4
4
  import { readFileSync, existsSync } from 'node:fs';
5
+ import { clashOf } from './refresh.js';
5
6
  import { join } from 'node:path';
6
- import { getCard } from './board.js';
7
+ import { getCard, titleFrom } from './board.js';
7
8
  import { budgetGate } from './gate.js';
8
9
  import { appendJsonl, homePath, readJson, writeJson } from './home.js';
9
- import { loadLiveState } from './livequota.js';
10
+ import { keychainAsk, loadLiveState } from './livequota.js';
10
11
  import { windowView } from './quota.js';
11
12
  import { loadSamples, pacing } from './pacing.js';
12
13
  import { changedFiles } from './review.js';
13
14
  import { loadColdStart } from './coldstart.js';
14
15
  import { blueprintHash } from './picture.js';
15
16
  import { costRange, readRuns } from './costs.js';
16
- import { loadStore, nextQuestion, readSignals, receipts } from './taste.js';
17
+ import { cachedWorkspaces, loadDream } from './dream.js';
18
+ import { describeSignal, loadStore, nextQuestion, readSignals, receipts } from './taste.js';
17
19
  import { agentInstalled, loadTriggerState } from './triggers.js';
20
+ import { planFor } from './permissions.js';
21
+ import { loadProfile, preflightHosts } from './preflight.js';
22
+ import { gitRoot } from './workspace.js';
23
+ import { writeBlueprintFile } from './blueprint.js';
18
24
  export function cardView(card, runs = readRuns()) {
19
25
  const qPath = card.run ? join(card.run.workdir, 'QUESTIONS.md') : '';
20
26
  return {
@@ -23,11 +29,24 @@ export function cardView(card, runs = readRuns()) {
23
29
  questionsText: qPath && existsSync(qPath) ? readFileSync(qPath, 'utf8') : null,
24
30
  pictureStale: Boolean(card.picture && card.picture.blueprintHash !== blueprintHash(card.blueprint)),
25
31
  costRange: card.run ? null : costRange(card, runs),
26
- folderBranch: card.column === 'review' && card.run?.branch ? currentBranch(card.cwd) : null,
32
+ folderBranch: card.column === 'review' && card.run?.branch ? (card.run.base?.branch || currentBranch(card.cwd)) : null,
33
+ clashFiles: card.column === 'review' ? clashOf(card)?.files ?? [] : [],
34
+ permissionPlan: ['later', 'suggested', 'approved'].includes(card.column) ? permissionPlanFor(card) : [],
27
35
  };
28
36
  }
37
+ /** The card's permission plan: earlier runs' blocks in its repo, preflight's network needs, the blueprint's Needs. */
38
+ function permissionPlanFor(card) {
39
+ try {
40
+ const root = gitRoot(card.cwd);
41
+ const profile = root ? loadProfile(root) : null;
42
+ return planFor(card.blueprint ?? undefined, profile?.needs ?? [], preflightHosts(profile));
43
+ }
44
+ catch {
45
+ return planFor(card.blueprint ?? undefined, []);
46
+ }
47
+ }
29
48
  /** The branch a folder is on (what Keep merges into), or null. */
30
- function currentBranch(cwd) {
49
+ export function currentBranch(cwd) {
31
50
  try {
32
51
  return execFileSync('git', ['-C', cwd, 'rev-parse', '--abbrev-ref', 'HEAD'], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }).trim() || null;
33
52
  }
@@ -45,6 +64,7 @@ export function appState(board, snap, config, now) {
45
64
  capturedAt: snap?.capturedAt ?? null,
46
65
  plan: live.plan ?? null,
47
66
  note: live.note ?? null,
67
+ askKeychain: keychainAsk(config),
48
68
  fiveHour: windowView(snap?.fiveHour, now),
49
69
  sevenDay: windowView(snap?.sevenDay, now),
50
70
  pacing: pacing(snap, loadSamples(), now, config.bedtime),
@@ -53,9 +73,21 @@ export function appState(board, snap, config, now) {
53
73
  cards: board.cards.map((c) => cardView(c, runs)),
54
74
  coldStart: coldStartState(),
55
75
  tasteQuestion: tasteQuestion(),
76
+ taste: tasteState(),
77
+ dream: dreamState(config, now),
56
78
  triggers: { installed: agentInstalled(), lastHour: config.lastHourTrigger, bedtime: config.bedtime, ...loadTriggerState() },
57
79
  };
58
80
  }
81
+ /** The nightly read for the app: on or off, the workspaces with their ticks, and how last night went. */
82
+ function dreamState(config, now) {
83
+ let workspaces = [];
84
+ try {
85
+ workspaces = cachedWorkspaces(now);
86
+ }
87
+ catch { }
88
+ const s = loadDream();
89
+ return { on: config.dream, model: config.dreamModel, workspaces, last: s.last ?? null };
90
+ }
59
91
  /** The one taste question waiting, with its receipts, for the app to show as a one-tap card. */
60
92
  export function tasteQuestion() {
61
93
  const signals = readSignals();
@@ -65,6 +97,29 @@ export function tasteQuestion() {
65
97
  const byId = new Map(signals.map((s) => [s.id, s]));
66
98
  return { id: p.id, text: p.text, noticed: p.noticed, scope: p.scope, evidence: receipts(p.evidence.map((e) => byId.get(e)).filter(Boolean)) };
67
99
  }
100
+ /**
101
+ * For "What Chompyy heard from you": the rules waiting for your yes (strongest evidence first) and the ones in
102
+ * force. The app shows the waiting count as a badge on the button.
103
+ */
104
+ export function tasteState() {
105
+ const signals = readSignals();
106
+ const byId = new Map(signals.map((s) => [s.id, s]));
107
+ const store = loadStore();
108
+ const item = (p) => {
109
+ const ev = p.evidence.map((e) => byId.get(e)).filter((s) => Boolean(s));
110
+ return {
111
+ id: p.id, text: p.text, noticed: p.noticed, scope: p.scope, evidence: receipts(ev),
112
+ receipts: ev.map((s) => ({ at: s.at, card: s.card ?? null, title: s.title ?? null, said: describeSignal(s, 600) })),
113
+ ...(p.validFrom ? { since: p.validFrom } : {}),
114
+ };
115
+ };
116
+ const waiting = [];
117
+ for (let q = nextQuestion(store, signals), rest = { ...store, prefs: [...store.prefs] }; q; q = nextQuestion(rest, signals)) {
118
+ waiting.push(q);
119
+ rest.prefs = rest.prefs.filter((p) => p.id !== q.id);
120
+ }
121
+ return { waiting: waiting.map(item), learned: store.prefs.filter((p) => p.status === 'active').map(item) };
122
+ }
68
123
  /** Whether the app should offer the cold start: never run, proposals waiting, or done. */
69
124
  export function coldStartState() {
70
125
  const cs = loadColdStart();
@@ -86,10 +141,28 @@ export function editBlueprint(board, id, text, now) {
86
141
  return card;
87
142
  card.blueprint = next;
88
143
  delete card.blueprintError;
144
+ delete card.blueprintWaiting;
145
+ delete card.blueprintWaitUntil;
146
+ writeBlueprintFile(card, next);
89
147
  card.updatedAt = now.toISOString();
90
148
  appendJsonl(homePath('signals.jsonl'), { at: card.updatedAt, card: card.id, title: card.title, kind: 'blueprint-edit', before, after: next });
91
149
  return card;
92
150
  }
151
+ /** Replace a parked card's idea (and the title made from it). Only cards still in `later`: once approved, the blueprint is the contract. */
152
+ export function editIdea(board, id, text, now) {
153
+ const card = getCard(board, id);
154
+ if (card.column !== 'later')
155
+ throw new Error(`Card #${card.id} is in ${card.column}; only cards in later can have their idea edited.`);
156
+ const next = text.trim();
157
+ if (!next)
158
+ throw new Error('The idea is empty.');
159
+ if (card.idea === next)
160
+ return card;
161
+ card.idea = next;
162
+ card.title = titleFrom(next);
163
+ card.updatedAt = now.toISOString();
164
+ return card;
165
+ }
93
166
  /** Answer the run's questions: the card goes back to approved and the next run gets your answers. */
94
167
  export function answerCard(board, id, text, now) {
95
168
  const card = getCard(board, id);
@@ -111,6 +184,9 @@ export function recordCliLocation() {
111
184
  const path = homePath('cli.json');
112
185
  const want = { node: process.execPath, script: process.argv[1] };
113
186
  const have = readJson(path, {});
187
+ // The live copy (live.ts) owns cli.json once set: running a CLI from a work folder must not take the app over.
188
+ if (have.live && have.script && existsSync(have.script))
189
+ return;
114
190
  if (have.node !== want.node || have.script !== want.script)
115
191
  writeJson(path, want);
116
192
  }
package/dist/away.js CHANGED
@@ -1,14 +1,20 @@
1
1
  // Away run (spec §5.2, §5.5, §5.6): approved cards, one at a time, headless, inside the window.
2
2
  import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
3
3
  import { join } from 'node:path';
4
- import { awayQueue, loadBoard, recoverRunning, updateBoard, getCard } from './board.js';
4
+ import { awayQueue, ensureCardDir, loadBoard, recoverRunning, updateBoard, getCard } from './board.js';
5
5
  import { formatDuration } from './duration.js';
6
6
  import { budgetGate } from './gate.js';
7
7
  import { homePath } from './home.js';
8
+ import { windowView } from './quota.js';
8
9
  import { recordRun, usedBetween } from './costs.js';
10
+ import { applyPermissions } from './permissions.js';
9
11
  import { tasteForPrompt } from './taste.js';
12
+ import { boxTempDirs } from './verify.js';
13
+ import { formatTokens } from './tokens.js';
10
14
  /** Don't start a card with less than this much time left in the away run. */
11
15
  export const MIN_CARD_MS = 2 * 60_000;
16
+ /** After a 5-hour reset, wait this much longer before carrying on (the new window needs a moment to show up). */
17
+ export const RESET_WAIT_MARGIN_MS = 2 * 60_000;
12
18
  export function safetyRules(workdir) {
13
19
  return `You are running unattended while the user is away. Nobody can answer questions. Rules:
14
20
  1. Work only inside this directory: ${workdir}. Don't read or change files outside it.
@@ -16,18 +22,19 @@ export function safetyRules(workdir) {
16
22
  no publishing packages, no purchases, no changes to remote services.
17
23
  3. If you need a decision only the user can make, stop and write the question(s) to QUESTIONS.md in this
18
24
  directory, with the options you see and your recommendation. Don't guess on anything irreversible.
19
- 4. Stay inside the blueprint's scope. If this is a git repo, commit your work to the current branch: that is
20
- always allowed, even if the blueprint says otherwise, because the branch is how the user reviews and undoes it.
21
- Don't commit QUESTIONS.md.
25
+ 4. Stay inside the blueprint's scope. Don't commit: leave your changes as files in this directory. Chompyy
26
+ commits them to this folder's branch when you finish (the branch is how the user reviews and undoes it), and
27
+ the repo's .git is read-only to you. git status, git diff and git log work.
22
28
  5. Check your work the way the blueprint says (run the tests if there are any). Shell commands run in a
23
- sandbox, so local commands like tests and scripts are fine.
29
+ sandbox, so local commands like tests and scripts are fine. The sandbox has no network: don't install or
30
+ download anything (no npm install/ci, pip install, brew, curl). Dependencies the repo already has installed
31
+ are in place. If a check can't run without a download, don't retry it: say so in the CHECKS line.
24
32
  6. End with a short summary: what you made, where it is, and how to check it. The very last line must be
25
33
  exactly one of:
26
34
  CHECKS: passed — <what you ran>
27
35
  CHECKS: failed — <what fails, and whether it failed before your change>
28
36
  CHECKS: not run — <why you couldn't check>`;
29
37
  }
30
- /** Claude Code sandbox settings for an away run: writes only in the card's folder (+ its repo's .git), no network. */
31
38
  /**
32
39
  * Build tools keep caches in your home folder (Go in ~/Library/Caches/go-build, npm in ~/.npm), which the
33
40
  * sandbox blocks. Point them at one Chompyy cache folder the sandbox allows, so tests and builds work.
@@ -40,15 +47,21 @@ export function cacheEnv(dir) {
40
47
  npm_config_cache: `${dir}/npm`,
41
48
  PIP_CACHE_DIR: `${dir}/pip`,
42
49
  XDG_CACHE_HOME: dir,
50
+ CLANG_MODULE_CACHE_PATH: `${dir}/clang-module-cache`,
43
51
  };
44
52
  }
45
- export function sandboxSettings(ws, allowedDomains, cacheDir, denyRead = []) {
53
+ /**
54
+ * Claude Code sandbox settings for an away run: writes only in the card's folder, the tool cache and temp folders;
55
+ * no network. Not the repo's .git: from there a hook or a config line (core.fsmonitor, core.hooksPath) would run
56
+ * outside the sandbox the next time git runs in your checkout, keep included (#24). Chompyy commits instead.
57
+ */
58
+ export function sandboxSettings(_ws, allowedDomains, cacheDir, denyRead = []) {
46
59
  return {
47
60
  sandbox: {
48
61
  enabled: true,
49
62
  failIfUnavailable: true, // refuse to run rather than run unprotected
50
63
  allowUnsandboxedCommands: false, // no retrying outside the sandbox
51
- filesystem: { allowWrite: [...(ws.gitDir ? [ws.gitDir] : []), ...(cacheDir ? [cacheDir] : [])], ...(denyRead.length ? { denyRead } : {}) },
64
+ filesystem: { allowWrite: [...(cacheDir ? [cacheDir] : []), ...boxTempDirs()], ...(denyRead.length ? { denyRead } : {}) },
52
65
  network: { allowedDomains },
53
66
  // Commands are confined by the sandbox, so local ones (tests, scripts) run without a prompt.
54
67
  // The deny list still blocks outward commands (push, publish, curl, …).
@@ -56,13 +69,35 @@ export function sandboxSettings(ws, allowedDomains, cacheDir, denyRead = []) {
56
69
  },
57
70
  };
58
71
  }
72
+ /** Web tools: they don't go through the sandbox's network block, so away runs only get them when you turn on awayWeb. */
73
+ const WEB_TOOLS = new Set(['WebSearch', 'WebFetch']);
74
+ /** Read, Glob and Grep with no path open every file on the Mac; without them, the file tools read the card's folder only. */
75
+ const READ_ANYWHERE = new Set(['Read', 'Glob', 'Grep']);
76
+ /**
77
+ * The tools an unattended run may use without asking (#24). A run tricked by text in the repo could otherwise read
78
+ * files outside its folder and send them out in a WebFetch URL. Also applied to an older config.json that still
79
+ * lists them.
80
+ */
81
+ export function awayTools(config, extra = []) {
82
+ const tools = [...config.allowedTools, ...extra].filter((t) => !READ_ANYWHERE.has(t) && !WEB_TOOLS.has(t));
83
+ return config.awayWeb ? [...tools, ...WEB_TOOLS] : tools;
84
+ }
59
85
  /** Read rules for the file tools: the sandbox's denyRead only covers shell commands. */
60
86
  export function denyReadRules(paths) {
61
87
  return paths.flatMap((p) => [`Read(${p})`, `Read(${p}/**)`]);
62
88
  }
63
- export function taskPrompt(card, workdir, taste = '') {
89
+ export function taskPrompt(card, workdir, taste = '', checks = []) {
64
90
  return `${safetyRules(workdir)}
65
- ${taste ? `
91
+ ${checks.length ? `
92
+ # How to check this repo (Chompyy ran these on main in this same sandbox: they pass here)
93
+
94
+ ${checks.map((c) => `- in ${c.dir || 'the top folder'}: \`${c.label}\``).join('\n')}
95
+
96
+ Run these, exactly as written. If one fails after your change, it's your change.
97
+ After you finish, Chompyy runs them again itself and compares the result with main. So CHECKS: failed means
98
+ your change broke something. If a check can't run at all (a permission or sandbox error, a missing download),
99
+ that is not your change: write CHECKS: not run, with the error.
100
+ ` : ''}${taste ? `
66
101
  # How this user likes work done (their taste.md; follow it unless the blueprint says otherwise)
67
102
 
68
103
  ${taste}
@@ -131,7 +166,25 @@ export async function away(durationMs, deps, opts = {}) {
131
166
  // The previous card already read quota when it finished; don't ask twice in a row.
132
167
  if (!opts.dryRun && deps.refreshQuota && deps.now() - lastRefreshMs > 60_000)
133
168
  await deps.refreshQuota();
134
- const gate = budgetGate(deps.snapshot(), config, new Date(deps.now()));
169
+ let gate = budgetGate(deps.snapshot(), config, new Date(deps.now()));
170
+ // The 5-hour window ran low but the run has time left (going to sleep): wait for the reset and carry on,
171
+ // instead of stopping at 23:40 and leaving the night unused. Weekly limits still stop it.
172
+ while (!gate.ok && !opts.force && !opts.dryRun && deps.wait) {
173
+ const five = windowView(deps.snapshot()?.fiveHour, new Date(deps.now()));
174
+ const onlyFiveHour = gate.reasons.every((r) => r.startsWith('5h window'));
175
+ if (!onlyFiveHour || !five.known)
176
+ break;
177
+ const wakeAt = five.resetsAt * 1000 + RESET_WAIT_MARGIN_MS;
178
+ if (wakeAt + MIN_CARD_MS > deadline)
179
+ break;
180
+ out(` ⏸ ${gate.reasons.join('; ')}. Waiting for the 5-hour window to reset at ${new Date(five.resetsAt * 1000).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })}, then carrying on.`);
181
+ await deps.wait(wakeAt - deps.now());
182
+ if (deps.refreshQuota) {
183
+ await deps.refreshQuota().catch(() => { });
184
+ lastRefreshMs = deps.now();
185
+ }
186
+ gate = budgetGate(deps.snapshot(), config, new Date(deps.now()));
187
+ }
135
188
  if (!gate.ok && !opts.force) {
136
189
  summary.stoppedBecause = gate.reasons.join('; ');
137
190
  break;
@@ -198,17 +251,27 @@ export async function runCard(id, timeoutMs, deps, trigger) {
198
251
  return { ...c };
199
252
  });
200
253
  out(`▶ #${card.id} ${card.title} (up to ${formatDuration(timeoutMs)})`);
201
- const logPath = homePath('runs', card.id, `${stamp(startedMs)}.log`);
254
+ // Run output lives in the card's folder, under its workspace: <store>/<workspace>/<id>/.
255
+ const logPath = join(ensureCardDir(card), `${stamp(startedMs)}.log`);
202
256
  let ws = null;
203
257
  let status;
204
258
  let exitCode = null;
205
259
  let summaryText = '';
206
260
  let checks;
207
261
  let verified;
262
+ let tokens;
208
263
  let log = '';
209
264
  try {
210
265
  ws = deps.prepare(card);
211
- const prompt = taskPrompt(card, ws.dir, (deps.taste ?? tasteForPrompt)());
266
+ if (ws.base)
267
+ out(` from ${ws.base.ref} @ ${ws.base.commit.slice(0, 7)}`);
268
+ for (const s of ws.setup ?? [])
269
+ if (s.source !== 'kept')
270
+ out(` deps in ${s.dir}: ${s.source}${s.note ? ` (${s.note})` : ''}`);
271
+ const granted = applyPermissions(card.permissions);
272
+ if (card.permissions?.length)
273
+ out(` allowed for this card: ${card.permissions.join(', ')}`);
274
+ const prompt = taskPrompt(card, ws.dir, (deps.taste ?? tasteForPrompt)(), deps.repoChecks?.(card) ?? []);
212
275
  const cacheDir = homePath('cache', 'tools');
213
276
  mkdirSync(cacheDir, { recursive: true });
214
277
  const questionsPath = join(ws.dir, 'QUESTIONS.md');
@@ -221,22 +284,33 @@ export async function runCard(id, timeoutMs, deps, trigger) {
221
284
  maxTurns: config.maxTurns,
222
285
  permissionMode: config.permissionMode,
223
286
  permissionPrompts: config.permissionPrompts,
224
- allowedTools: config.allowedTools,
287
+ allowedTools: awayTools(config, granted.allowedTools),
225
288
  disallowedTools: [...config.disallowedTools, ...denyReadRules(config.denyReadPaths)],
226
- ...(config.sandbox ? { settings: sandboxSettings(ws, config.sandboxAllowedDomains, cacheDir, config.denyReadPaths) } : {}),
289
+ ...(config.sandbox ? { settings: sandboxSettings(ws, [...config.sandboxAllowedDomains, ...granted.domains], cacheDir, config.denyReadPaths) } : {}),
227
290
  env: cacheEnv(cacheDir),
228
291
  extraArgs: config.extraArgs,
229
292
  ...(config.loopRepeat > 0 ? { loopRepeat: config.loopRepeat } : {}),
230
293
  ...(config.idleTimeoutMin > 0 ? { idleTimeoutMs: config.idleTimeoutMin * 60_000 } : {}),
294
+ ...(config.maxDenied > 0 ? { maxDenied: config.maxDenied } : {}),
231
295
  onSpawn: (pid) => writeFileSync(agentPidPath(card.id), String(pid)),
232
296
  // The whole stream (every tool call and result) goes to disk, never into memory: what to read when a run goes wrong.
233
297
  rawLogPath: logPath.replace(/\.log$/, '.stream.jsonl'),
234
298
  });
235
299
  rmSync(agentPidPath(card.id), { force: true });
236
300
  exitCode = result.exitCode;
301
+ tokens = result.tokens;
302
+ if (tokens)
303
+ out(` used ${formatTokens(tokens)}`);
304
+ if (result.needs) {
305
+ try {
306
+ deps.recordNeeds?.(card, result.needs);
307
+ }
308
+ catch { }
309
+ out(` blocked on: ${[...result.needs.commands, ...result.needs.hosts].join(', ')} (offered on the next blueprint here)`);
310
+ }
237
311
  try {
238
312
  if (deps.commitLeftovers?.(ws, card))
239
- out(' (committed changes the agent left uncommitted)');
313
+ out(" (Chompyy committed the agent's changes)");
240
314
  }
241
315
  catch (err) {
242
316
  out(` couldn't commit leftover changes: ${err instanceof Error ? err.message : err}`);
@@ -292,10 +366,12 @@ export async function runCard(id, timeoutMs, deps, trigger) {
292
366
  exitCode,
293
367
  workdir: ws?.dir ?? '',
294
368
  ...(ws?.branch ? { branch: ws.branch } : {}),
369
+ ...(ws?.base ? { base: ws.base } : {}),
295
370
  summary: summaryText,
296
371
  ...(checks ? { checks } : {}),
297
372
  cost,
298
373
  ...(verified ? { verified } : {}),
374
+ ...(tokens ? { tokens } : {}),
299
375
  ...(trigger ? { trigger } : {}),
300
376
  };
301
377
  });
@@ -308,6 +384,7 @@ export async function runCard(id, timeoutMs, deps, trigger) {
308
384
  status,
309
385
  durationMs: finishedMs - startedMs,
310
386
  ...cost,
387
+ ...(tokens ? { tokens } : {}),
311
388
  });
312
389
  out(` → ${status} · ${formatDuration(finishedMs - startedMs)}${cost.fiveHourPct !== null ? ` · used ${cost.fiveHourPct}% of the 5h window` : ''} · log ${logPath}`);
313
390
  return card.id;
package/dist/blueprint.js CHANGED
@@ -1,4 +1,10 @@
1
+ // Blueprint (spec §5.4): the scope agreed before a card runs, drafted by a cheap model.
2
+ import { writeFileSync } from 'node:fs';
3
+ import { join } from 'node:path';
4
+ import { ensureCardDir } from './board.js';
1
5
  export const BLUEPRINT_SECTIONS = ['Goal', 'Scope', 'Out of scope', 'Shape', "How it's checked"];
6
+ /** Optional: what the run needs beyond the box, for the permission plan. */
7
+ export const OPTIONAL_SECTIONS = ['Needs'];
2
8
  export function blueprintPrompt(card) {
3
9
  return `You write short blueprints for tasks a coding agent will run unattended, with nobody to ask.
4
10
  Turn the idea below into a blueprint. Reply with ONLY this Markdown, no preamble:
@@ -18,15 +24,23 @@ Turn the idea below into a blueprint. Reply with ONLY this Markdown, no preamble
18
24
  ## How it's checked
19
25
  - <how someone can verify the result without the author: tests, files that exist, cited sources>
20
26
 
27
+ ## Needs
28
+ - <ONLY if the run truly can't succeed inside the box; otherwise leave this whole section out>
29
+ - network: <domain>: <why, one line> (the shell needs to reach this domain, e.g. to download a file)
30
+ - command: <program>: <why, one line> (a program the run must use that needs approval)
31
+
21
32
  Look at the working directory first (read-only) so the blueprint fits what is really there: its files,
22
33
  languages, test command and tooling. Don't plan steps for tools the repo doesn't have.
34
+ If the plan depends on facts you're unsure of (an API, a library's usage, a format), you may check them with
35
+ WebSearch or WebFetch first. Keep research short: the blueprint, not the research, is the deliverable.
23
36
 
24
37
  The run can only change files inside the working directory. Its shell has no network, but the agent CAN
25
38
  read public web pages with its web tools (WebFetch, WebSearch), so reading docs or a linked page is fine.
26
- If the idea needs anything outside that (global or user config, other folders or repos, accounts,
27
- installing packages, calling APIs or downloading from the shell),
28
- start Out of scope with "Can't run unattended: <why>" and plan only what can be done inside the directory,
29
- such as a script or written steps the user can run themselves.
39
+ The repo's installed dependencies are already in the run's copy, so don't plan to install them.
40
+ If the idea needs the shell to reach a site or run a program needing approval, list it under Needs: the user
41
+ can allow it when approving. If it needs anything else outside the directory (global or user config, other
42
+ folders or repos, accounts, calling APIs), start Out of scope with "Can't run unattended: <why>" and plan only
43
+ what can be done inside the directory, such as a script or written steps the user can run themselves.
30
44
 
31
45
  Keep it under 200 words. Pick the smallest useful version of the idea.
32
46
  Never write "no commits" or "leave files untracked": the run always commits to the card's own branch (Chompyy
@@ -37,6 +51,12 @@ can make, say so in Out of scope and plan to write that question to QUESTIONS.md
37
51
  Working directory: ${card.cwd}
38
52
  Idea: ${card.idea}`;
39
53
  }
54
+ /** Keep a copy of the card's blueprint in its folder (`<store>/<workspace>/<id>/blueprint.md`). Returns the path. */
55
+ export function writeBlueprintFile(card, text) {
56
+ const path = join(ensureCardDir(card), 'blueprint.md');
57
+ writeFileSync(path, text.trim() + '\n');
58
+ return path;
59
+ }
40
60
  /** Strip chatter before the first heading; insist on the Goal heading. */
41
61
  export function cleanBlueprint(output) {
42
62
  const text = output.trim();
@@ -50,15 +70,90 @@ export async function draftBlueprint(card, runner, opts) {
50
70
  prompt: blueprintPrompt(card),
51
71
  cwd: opts.cwd,
52
72
  model: opts.model,
53
- tools: 'Read,Glob,Grep',
54
- timeoutMs: opts.timeoutMs ?? 120_000,
73
+ // Research while drafting: the plan you approve should already be checked against the docs.
74
+ tools: 'Read,Glob,Grep,WebSearch,WebFetch',
75
+ // Headless runs refuse anything not allowed up front (nobody to approve), so allow the research tools.
76
+ allowedTools: ['Read', 'Glob', 'Grep', 'WebSearch', 'WebFetch'],
77
+ timeoutMs: opts.timeoutMs ?? 240_000,
55
78
  });
56
79
  if (result.timedOut)
57
80
  throw new Error('Blueprint model timed out.');
81
+ // In -p mode Claude Code prints some failures (like the usage limit) on stdout, so fall back to it.
58
82
  if (result.exitCode !== 0)
59
- throw new Error(`claude exited with ${result.exitCode}: ${result.stderr.trim().slice(0, 300)}`);
83
+ throw new Error(`claude exited with ${result.exitCode}: ${(result.stderr.trim() || result.output.trim()).slice(0, 300)}`);
60
84
  return cleanBlueprint(result.output);
61
85
  }
86
+ /** Most words and characters a card title may have. */
87
+ export const TITLE_MAX_WORDS = 10;
88
+ export const TITLE_MAX_CHARS = 60;
89
+ export function titlePrompt(idea) {
90
+ return `Write a short title for this task card on a kanban board. Reply with ONLY the title: at most ${TITLE_MAX_WORDS} words,
91
+ no quotes, no ending period, no preamble. Say what the task is about, e.g. "Retitle parked cards with a model summary".
92
+
93
+ Task: ${idea}`;
94
+ }
95
+ /**
96
+ * The model's reply as a card title: first non-empty line, without quotes, bullets, a "Title:" label or an
97
+ * ending period, cut to 10 words and 60 characters. Empty when nothing usable is left.
98
+ */
99
+ export function cleanTitle(output) {
100
+ const line = output.split('\n').map((l) => l.trim()).find((l) => l.length > 0) ?? '';
101
+ let t = line
102
+ .replace(/^([-*•#]+|\d+[.)])\s*/, '')
103
+ .replace(/^title\s*:\s*/i, '')
104
+ .replace(/^["'`*_]+|["'`*_]+$/g, '')
105
+ .replace(/[.。]+$/, '')
106
+ .replace(/\s+/g, ' ')
107
+ .trim();
108
+ t = t.split(' ').slice(0, TITLE_MAX_WORDS).join(' ');
109
+ if (t.length > TITLE_MAX_CHARS)
110
+ t = t.slice(0, TITLE_MAX_CHARS - 1).trimEnd() + '…';
111
+ return t;
112
+ }
113
+ /**
114
+ * A short title for the card, written by the same cheap model as the blueprint (no tools, one short call).
115
+ * Never throws: if the call fails or the reply is unusable, the card keeps its current title.
116
+ */
117
+ export async function draftTitle(card, runner, opts) {
118
+ try {
119
+ const result = await runner.run({ prompt: titlePrompt(card.idea), cwd: opts.cwd, model: opts.model, tools: '', timeoutMs: opts.timeoutMs ?? 60_000 });
120
+ if (result.exitCode !== 0 || result.timedOut)
121
+ return card.title;
122
+ return cleanTitle(result.output) || card.title;
123
+ }
124
+ catch {
125
+ return card.title;
126
+ }
127
+ }
128
+ /** A draft that started this long ago and never finished (its process died) counts as not drafting. */
129
+ const DRAFT_STALE_MS = 3 * 60_000;
130
+ /**
131
+ * Later cards "Draft all" should draft: no blueprint yet and not being drafted right now.
132
+ * Cards with a blueprint (edited ones too) are left alone; a card whose last draft failed is retried.
133
+ */
134
+ export function laterToDraft(board, now = new Date()) {
135
+ return board.cards.filter((c) => c.column === 'later' &&
136
+ !c.blueprint?.trim() &&
137
+ (!c.draftingAt || Date.parse(c.draftingAt) < now.getTime() - DRAFT_STALE_MS));
138
+ }
139
+ /**
140
+ * The plan for `chompyy blueprint --all-later`: which cards to draft, or why it drafts nothing.
141
+ * Same gate as background drafting: with no active 5-hour window a model call would start a new one.
142
+ */
143
+ export function draftAllPlan(board, windowActive, now = new Date()) {
144
+ if (!windowActive)
145
+ return { ids: [], message: 'No active 5-hour window: drafting now would start one. Nothing drafted; try again while you are using Claude Code.' };
146
+ const ids = laterToDraft(board, now).map((c) => c.id);
147
+ return ids.length ? { ids } : { ids, message: 'Every later card already has a blueprint (or is being drafted).' };
148
+ }
149
+ /**
150
+ * True when a failed model call ran into the plan's usage limit (out of quota), e.g. Claude Code's
151
+ * "Claude AI usage limit reached|1763470800", "5-hour limit reached ∙ resets 3pm" or "You've hit your limit".
152
+ * Such a failure isn't the card's fault: it should wait for the reset, not be marked failed.
153
+ */
154
+ export function isUsageLimit(message) {
155
+ return /usage limit reached|(5-hour|weekly|session|opus) limit reached|hit your (usage )?limit|limit reached\s*[∙·|]\s*resets/i.test(message);
156
+ }
62
157
  /** Generic options when a card-specific list can't be made (e.g. no active window). */
63
158
  export const GENERIC_FIVE_STAR = ['Closer to what I asked for', 'Shorter and simpler', 'More thorough', 'A different format'];
64
159
  export function fiveStarPrompt(card) {