chompyy 0.0.0-stage → 0.1.0

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 BranchWork-HQ
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,180 @@
1
- # Temporary Holding Version
1
+ # chompyy (CLI)
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Uses the capacity in Claude Code's 5-hour window that would otherwise reset unused. You park ideas as cards, each card gets a short **blueprint** (the scope agreed before it runs), approved cards run headless while you're away, and a report shows what ran so you can rate it.
4
+
5
+ This is the MVP from [the spec](../research/spec-token-utilization.md) §10, CLI only. Node 20+, no runtime dependencies.
6
+
7
+ ## Install
8
+
9
+ ```bash
10
+ npm install -g chompyy
11
+ chompyy help
12
+ chompyy app # macOS: install the menu bar app too
13
+ ```
14
+
15
+ From source:
16
+
17
+ ```bash
18
+ cd cli
19
+ npm install # also builds dist/
20
+ npm link # puts `chompyy` on your PATH
21
+ chompyy help
22
+ ```
23
+
24
+ Without linking: `npx chompyy help` from inside `cli/`, or `node cli/dist/cli.js help`.
25
+
26
+ You also need [Claude Code](https://code.claude.com) (`claude` on your PATH) for blueprints and away runs, on a Pro, Max or Ultra plan for the quota numbers.
27
+
28
+ ## Quota
29
+
30
+ By default Chompyy reads live quota with Claude Code's saved login (macOS Keychain or `~/.claude/.credentials.json`), from the same usage endpoint Claude Code's `/usage` shows. It sends no message, so it never starts a window, and it checks at most every 5 minutes. Nothing to set up. To use only the status line instead, set `"quotaSource": "statusline"` in `~/.chompyy/config.json`.
31
+
32
+ ## Set up the quota snapshot (fallback)
33
+
34
+ Chompyy can also read quota from Claude Code's status line, never by sending a message (if no window is active, the first message would start a new 5-hour window). Add this to `~/.claude/settings.json`:
35
+
36
+ ```json
37
+ {
38
+ "statusLine": {
39
+ "type": "command",
40
+ "command": "chompyy statusline"
41
+ }
42
+ }
43
+ ```
44
+
45
+ Each status line refresh writes `~/.chompyy/quota.json` and shows one line:
46
+
47
+ ```
48
+ 🍪 5h 62% left · 1h40m · ~37%/h | 7d 41% used
49
+ ```
50
+
51
+ That reads: 62% of the 5h window left, it resets in 1h40m, so about 37% per hour is available until then; 41% of the weekly limit is used. `rate_limits` only appears after the first reply of a session; until then the last snapshot is kept. Once the window's `resets_at` has passed, the snapshot is stale and Chompyy treats the window as unknown.
52
+
53
+ If you already have a status line command, keep it and call Chompyy from a small wrapper: save stdin to a variable, pipe it to `chompyy statusline`, and print both.
54
+
55
+ ## Two-minute walkthrough
56
+
57
+ ```bash
58
+ cd ~/code/my-repo
59
+ chompyy later "Add a --json flag to the export script, with a test"
60
+ # 📥 #1 parked in later · drafting the blueprint in the background
61
+
62
+ chompyy show 1 # read the blueprint (Goal / Scope / Out of scope / Shape / How it's checked)
63
+ chompyy blueprint 1 # not happy? draft it again (or --model sonnet)
64
+ chompyy approve 1 # later → approved; needs a blueprint
65
+ chompyy status # 5h left, reset time, pace, weekly used
66
+ chompyy eat-tokens # read-only view of the leftover window and cards to consider
67
+ chompyy away 1h --dry-run # the plan: which cards, where they'd run, whether the gate is open
68
+ chompyy away 1h # go get lunch; cards run one at a time, then move to review
69
+ chompyy report # what ran, and the one thing to do about each (cards that need you first)
70
+ chompyy diff 1 # see the change; then keep it, or throw it away
71
+ chompyy keep 1 # merge its branch into your current branch (or: chompyy undo 1)
72
+ chompyy rate 1 4 "right scope, test was thin"
73
+ chompyy board # everything, by column
74
+ ```
75
+
76
+ Each card in a git repo runs in its own worktree at `~/.chompyy/worktrees/<id>` on a new branch `chompyy/<id>`; review it with `git log chompyy/1` or `git diff HEAD...chompyy/1` in your repo, and merge it yourself if you like it. Cards outside git run in `~/.chompyy/runs/<id>/work/`.
77
+
78
+ `away` runs in the foreground and needs the terminal to stay open; for a long run use `nohup chompyy away 1h > ~/.chompyy/away.log 2>&1 &`, or tmux. Claude Code may warn that a sign-in expires; for unattended jobs it suggests `claude setup-token`.
79
+
80
+ ## Commands
81
+
82
+ | Command | What it does |
83
+ |---|---|
84
+ | `chompyy statusline` | Status line hook: reads Claude Code's JSON on stdin, saves the snapshot, prints one line |
85
+ | `chompyy status` | % left in the 5h window, time to reset, per-hour pace, weekly used, stale or not |
86
+ | `chompyy eat-tokens` | Read-only view of remaining 5h quota and approved/later cards; starts nothing |
87
+ | `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) |
88
+ | `chompyy board [--column approved]` | Cards by column: suggested, later, approved, running, review, done |
89
+ | `chompyy show <id>` | One card with its blueprint, last run and rating |
90
+ | `chompyy blueprint <id> [--model m]` | Draft (or redraft) the blueprint with a cheap model |
91
+ | `chompyy approve <id>` / `drop <id>` | Queue a card for away runs / remove it (kept in `archive.jsonl`) |
92
+ | `chompyy away <1h\|30m\|1h30m> [--dry-run] [--force]` | Run approved cards until the time is up or the gate closes |
93
+ | `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` |
94
+ | `chompyy diff <id>` | The change the card made on its branch |
95
+ | `chompyy keep <id>` | Merge the card's branch into your current branch and remove its worktree. Refuses if your repo has uncommitted changes |
96
+ | `chompyy undo <id>` | Throw the run away: remove its worktree and branch (or draft folder). Your own branches are never touched |
97
+ | `chompyy rate <id> <1-5> ["why"]` | Rate a result against its blueprint; moves it to *done* and logs a signal |
98
+ | `chompyy taste` | Show `taste.md` (a stub for now; nothing is distilled yet) |
99
+
100
+ ## The budget gate
101
+
102
+ Before each card, `away` checks the snapshot and stops when:
103
+
104
+ - the 5h window has less than `min5hLeftPct` left (default 10%),
105
+ - weekly usage is ahead of an even pace through the week (e.g. 2.5 days into the week, more than ~36% used): it spends only what you haven't used so far and never borrows from the days ahead (`weeklyPace`),
106
+ - weekly usage is over `100 − weeklyReservePct` (hard stop, default above 90%, whatever the pace),
107
+ - the 5h window is unknown: no snapshot, or its `resets_at` has passed. Running then would start a *new* window instead of using leftover capacity. Open Claude Code once to refresh it, or pass `--force`.
108
+
109
+ An unknown weekly window doesn't close the gate (some plans don't report it); `away` says it wasn't checked. The snapshot doesn't move during an away run (no interactive session updates it), so in practice the gate stops the run when the window resets.
110
+
111
+ ## Config
112
+
113
+ `~/.chompyy/config.json`; any key you leave out keeps its default.
114
+
115
+ | Key | Default | Meaning |
116
+ |---|---|---|
117
+ | `claudeBin` | `"claude"` | The Claude Code binary |
118
+ | `blueprintModel` | `"haiku"` | Model that drafts blueprints (`claude -p --model haiku --tools ""`) |
119
+ | `runModel` | `null` | Model for away runs; `null` uses Claude Code's default |
120
+ | `cardTimeoutMin` | `30` | Wall-clock cap per card, in minutes; also capped by the time left in the away run |
121
+ | `maxTurns` | `50` | Passed as `--max-turns`. `claude --help` (2.1.322) doesn't list it, but `claude -p` accepts it; set `null` if your version rejects it |
122
+ | `min5hLeftPct` | `10` | Minimum % left in the 5h window to start a card |
123
+ | `weeklyPace` | `true` | Only run while weekly usage is behind an even pace through the week |
124
+ | `weeklyReservePct` | `10` | Hard stop: never run above `100 − this` % weekly used |
125
+ | `permissionMode` | `"acceptEdits"` | `--permission-mode` for away runs: file edits allowed, other tools only if allowed below |
126
+ | `permissionPrompts` | `"none"` | `--permission-prompts`: anything that would ask for permission is denied, so a run never hangs waiting. Set `null` on Claude Code versions without this flag |
127
+ | `allowedTools` | read/search tools, `git status/diff/log/add/commit`, `npm test`, `npm run`, `npx vitest`, `pytest` | `--allowedTools` |
128
+ | `disallowedTools` | `git push/merge/rebase/reset/checkout/switch/worktree`, `gh`, `npm publish`, `curl`, `rm -rf` | `--disallowedTools` |
129
+ | `sandbox` | `true` | Run away cards in Claude Code's OS sandbox (macOS, Linux, WSL2) |
130
+ | `sandboxAllowedDomains` | `[]` | Domains sandboxed commands may reach, e.g. `["registry.npmjs.org"]` |
131
+ | `extraArgs` | `[]` | Appended to every away-run `claude -p` call, e.g. `["--max-budget-usd", "2"]` for API-key users |
132
+
133
+ Set `CHOMPYY_HOME` to keep state somewhere other than `~/.chompyy` (the tests do this).
134
+
135
+ ## Safety rules
136
+
137
+ A card runs unattended only inside a box (spec §5.5):
138
+
139
+ - **Its own place**: a fresh git worktree on `chompyy/<id>`, or a draft folder under `~/.chompyy/runs/<id>/`. Your checkout is never touched; nothing is merged.
140
+ - **Rules in the prompt**, before the blueprint: work only inside this directory; no git push, merge, rebase or PR; no sending, posting, publishing or purchases; if a decision is needed, stop and write `QUESTIONS.md` (the report flags those cards as ❓).
141
+ - **Enforced by the OS** (default, `sandbox: true`): cards run in Claude Code's sandbox. Shell commands can write only inside the card's folder (plus its repo's `.git`, so commits work) and have **no network** unless you list domains in `sandboxAllowedDomains`. So a `git push` fails even if a test script tries it. If the sandbox can't start, the card refuses to run rather than run unprotected. Checked on macOS with a real headless run: network and outside writes were blocked, the commit worked. File reads are not restricted.
142
+ - **Rules in the tools**: `acceptEdits` plus an allow list, a deny list for push/merge/`gh`/publish, and `--permission-prompts none` so anything outside the lists is refused instead of waiting for you.
143
+ - **Caps**: a wall-clock timeout per card, a turn cap, the away duration, and the budget gate above.
144
+ - **Blueprint first**: a card can't be approved without one.
145
+
146
+ These lower the risk; they don't make it zero. Read the result (and its branch) before you merge anything.
147
+
148
+ ## Agent shortcuts (Claude Code skills)
149
+
150
+ `skills/` holds `/later`, `/eat-tokens`, `/away` and `/taste`. Each one shells out to `chompyy`. Install them for all your projects by linking them into your personal skills folder:
151
+
152
+ ```bash
153
+ mkdir -p ~/.claude/skills
154
+ for s in later eat-tokens away taste; do ln -s "$PWD/skills/$s" ~/.claude/skills/$s; done # run from cli/
155
+ ```
156
+
157
+ Or copy them into a project's `.claude/skills/` to scope them to that repo.
158
+
159
+ ## Files
160
+
161
+ Everything is plain JSON or Markdown in `~/.chompyy/`:
162
+
163
+ | File | What |
164
+ |---|---|
165
+ | `quota.json` | Last quota snapshot |
166
+ | `board.json` | Cards, with blueprints, run info and ratings |
167
+ | `runs/<id>/<time>.log` | Prompt, output and errors of each run |
168
+ | `worktrees/<id>/` | Git worktrees of cards that ran in a repo |
169
+ | `signals.jsonl` | One line per rating: card, rating, reason, blueprint (input for the future taste distiller) |
170
+ | `taste.md` | What's been learned; edit freely |
171
+ | `archive.jsonl` | Dropped cards |
172
+ | `state.json` | When the last report was shown |
173
+ | `config.json` | Your settings |
174
+
175
+ ## Develop
176
+
177
+ ```bash
178
+ npm test # vitest
179
+ npm run build # tsc → dist/
180
+ ```
@@ -0,0 +1,31 @@
1
+ # Third-party notices
2
+
3
+ ## Third-party code
4
+
5
+ `cli/src/vendor/codeburn/`: from [codeburn](https://github.com/getagentseal/codeburn) (MIT, Copyright (c) 2026 AgentSeal). See its `UPSTREAM.md` and `LICENSE`.
6
+
7
+ Its licence, in full (MIT requires it in every copy, including the npm package):
8
+
9
+ ```
10
+ MIT License
11
+
12
+ Copyright (c) 2026 AgentSeal
13
+
14
+ Permission is hereby granted, free of charge, to any person obtaining a copy
15
+ of this software and associated documentation files (the "Software"), to deal
16
+ in the Software without restriction, including without limitation the rights
17
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
18
+ copies of the Software, and to permit persons to whom the Software is
19
+ furnished to do so, subject to the following conditions:
20
+
21
+ The above copyright notice and this permission notice shall be included in all
22
+ copies or substantial portions of the Software.
23
+
24
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
25
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
26
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
27
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
28
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
29
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
30
+ SOFTWARE.
31
+ ```
@@ -0,0 +1,75 @@
1
+ // What the Mac app reads (`chompyy state --json`) and the card actions it needs beyond the CLI's.
2
+ // The app holds no logic of its own: it shows this JSON and calls chompyy commands.
3
+ import { readFileSync, existsSync } from 'node:fs';
4
+ import { join } from 'node:path';
5
+ import { getCard } from './board.js';
6
+ import { budgetGate } from './gate.js';
7
+ import { appendJsonl, homePath, readJson, writeJson } from './home.js';
8
+ import { loadLiveState } from './livequota.js';
9
+ import { windowView } from './quota.js';
10
+ import { changedFiles } from './review.js';
11
+ export function cardView(card) {
12
+ const qPath = card.run ? join(card.run.workdir, 'QUESTIONS.md') : '';
13
+ return {
14
+ ...card,
15
+ files: card.run ? changedFiles(card) : [],
16
+ questionsText: qPath && existsSync(qPath) ? readFileSync(qPath, 'utf8') : null,
17
+ };
18
+ }
19
+ export function appState(board, snap, config, now) {
20
+ const live = loadLiveState();
21
+ return {
22
+ generatedAt: now.toISOString(),
23
+ quota: {
24
+ source: snap?.source ?? 'statusline',
25
+ capturedAt: snap?.capturedAt ?? null,
26
+ plan: live.plan ?? null,
27
+ note: live.note ?? null,
28
+ fiveHour: windowView(snap?.fiveHour, now),
29
+ sevenDay: windowView(snap?.sevenDay, now),
30
+ },
31
+ gate: budgetGate(snap, config, now),
32
+ cards: board.cards.map(cardView),
33
+ };
34
+ }
35
+ /** Replace a card's blueprint with your edit. Edits are the strongest taste signal, so the change is logged. */
36
+ export function editBlueprint(board, id, text, now) {
37
+ const card = getCard(board, id);
38
+ if (card.column === 'running')
39
+ throw new Error(`Card #${card.id} is running; edit it after the run.`);
40
+ const next = text.trim();
41
+ if (!next)
42
+ throw new Error('The blueprint is empty.');
43
+ const before = card.blueprint;
44
+ if (before?.trim() === next)
45
+ return card;
46
+ card.blueprint = next;
47
+ delete card.blueprintError;
48
+ card.updatedAt = now.toISOString();
49
+ appendJsonl(homePath('signals.jsonl'), { at: card.updatedAt, card: card.id, title: card.title, kind: 'blueprint-edit', before, after: next });
50
+ return card;
51
+ }
52
+ /** Answer the run's questions: the card goes back to approved and the next run gets your answers. */
53
+ export function answerCard(board, id, text, now) {
54
+ const card = getCard(board, id);
55
+ if (card.column !== 'review')
56
+ throw new Error(`Card #${card.id} is in ${card.column}; only cards waiting for review can be answered.`);
57
+ const answer = text.trim();
58
+ if (!answer)
59
+ throw new Error('The answer is empty.');
60
+ const at = now.toISOString();
61
+ card.answers = [...(card.answers ?? []), { at, text: answer }];
62
+ card.column = 'approved';
63
+ card.approvedAt = at;
64
+ card.updatedAt = at;
65
+ appendJsonl(homePath('signals.jsonl'), { at, card: card.id, title: card.title, kind: 'answer', text: answer });
66
+ return card;
67
+ }
68
+ /** Remember how to start this CLI, so the Mac app can run it without your shell's PATH (nvm etc.). */
69
+ export function recordCliLocation() {
70
+ const path = homePath('cli.json');
71
+ const want = { node: process.execPath, script: process.argv[1] };
72
+ const have = readJson(path, {});
73
+ if (have.node !== want.node || have.script !== want.script)
74
+ writeJson(path, want);
75
+ }
package/dist/away.js ADDED
@@ -0,0 +1,225 @@
1
+ // Away run (spec §5.2, §5.5, §5.6): approved cards, one at a time, headless, inside the window.
2
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
3
+ import { join } from 'node:path';
4
+ import { awayQueue, loadBoard, recoverRunning, updateBoard, getCard } from './board.js';
5
+ import { formatDuration } from './duration.js';
6
+ import { budgetGate } from './gate.js';
7
+ import { homePath } from './home.js';
8
+ /** Don't start a card with less than this much time left in the away run. */
9
+ export const MIN_CARD_MS = 2 * 60_000;
10
+ export function safetyRules(workdir) {
11
+ return `You are running unattended while the user is away. Nobody can answer questions. Rules:
12
+ 1. Work only inside this directory: ${workdir}. Don't read or change files outside it.
13
+ 2. Nothing outward: no git push, merge, rebase or pull request; no sending email or messages, no posting,
14
+ no publishing packages, no purchases, no changes to remote services.
15
+ 3. If you need a decision only the user can make, stop and write the question(s) to QUESTIONS.md in this
16
+ directory, with the options you see and your recommendation. Don't guess on anything irreversible.
17
+ 4. Stay inside the blueprint's scope. If this is a git repo, commit your work to the current branch: that is
18
+ always allowed, even if the blueprint says otherwise, because the branch is how the user reviews and undoes it.
19
+ Don't commit QUESTIONS.md.
20
+ 5. Check your work the way the blueprint says (run the tests if there are any). Shell commands run in a
21
+ sandbox, so local commands like tests and scripts are fine.
22
+ 6. End with a short summary: what you made, where it is, and how to check it. The very last line must be
23
+ exactly one of:
24
+ CHECKS: passed — <what you ran>
25
+ CHECKS: failed — <what fails, and whether it failed before your change>
26
+ CHECKS: not run — <why you couldn't check>`;
27
+ }
28
+ /** Claude Code sandbox settings for an away run: writes only in the card's folder (+ its repo's .git), no network. */
29
+ /**
30
+ * Build tools keep caches in your home folder (Go in ~/Library/Caches/go-build, npm in ~/.npm), which the
31
+ * sandbox blocks. Point them at one Chompyy cache folder the sandbox allows, so tests and builds work.
32
+ */
33
+ export function cacheEnv(dir) {
34
+ return {
35
+ GOCACHE: `${dir}/go-build`,
36
+ GOMODCACHE: `${dir}/go-mod`,
37
+ GOFLAGS: '-modcacherw',
38
+ npm_config_cache: `${dir}/npm`,
39
+ PIP_CACHE_DIR: `${dir}/pip`,
40
+ XDG_CACHE_HOME: dir,
41
+ };
42
+ }
43
+ export function sandboxSettings(ws, allowedDomains, cacheDir) {
44
+ return {
45
+ sandbox: {
46
+ enabled: true,
47
+ failIfUnavailable: true, // refuse to run rather than run unprotected
48
+ allowUnsandboxedCommands: false, // no retrying outside the sandbox
49
+ filesystem: { allowWrite: [...(ws.gitDir ? [ws.gitDir] : []), ...(cacheDir ? [cacheDir] : [])] },
50
+ network: { allowedDomains },
51
+ // Commands are confined by the sandbox, so local ones (tests, scripts) run without a prompt.
52
+ // The deny list still blocks outward commands (push, publish, curl, …).
53
+ autoAllowBashIfSandboxed: true,
54
+ },
55
+ };
56
+ }
57
+ export function taskPrompt(card, workdir) {
58
+ return `${safetyRules(workdir)}
59
+
60
+ # Task #${card.id}: ${card.title}
61
+
62
+ Original idea: ${card.idea}
63
+
64
+ # Blueprint (agreed scope)
65
+
66
+ ${card.blueprint ?? ''}
67
+ ${card.answers?.length ? `
68
+ # Your earlier questions have been answered
69
+
70
+ The previous run left QUESTIONS.md. The user's answers:
71
+
72
+ ${card.answers.map((a) => a.text).join('\n\n')}
73
+
74
+ Continue from the work already in this folder. Delete QUESTIONS.md once it's resolved.
75
+ ` : ''}`;
76
+ }
77
+ /** The agent's own verdict on its checks: the last "CHECKS: passed|failed|not run — why" line. */
78
+ export function parseChecks(output) {
79
+ const matches = [...output.matchAll(/^\s*\**CHECKS:\**\s*(passed|failed|not run)\s*[—–:-]*\s*(.*)$/gim)];
80
+ const last = matches.at(-1);
81
+ if (!last)
82
+ return undefined;
83
+ return { result: last[1].toLowerCase(), why: last[2].trim() };
84
+ }
85
+ function firstLines(text, n = 5) {
86
+ return text
87
+ .split('\n')
88
+ .map((l) => l.trimEnd())
89
+ .filter((l) => l.trim() !== '')
90
+ .slice(0, n)
91
+ .join('\n');
92
+ }
93
+ function stamp(ms) {
94
+ return new Date(ms).toISOString().replace(/[:.]/g, '-');
95
+ }
96
+ export async function away(durationMs, deps, opts = {}) {
97
+ const { config, out } = deps;
98
+ const start = deps.now();
99
+ const deadline = start + durationMs;
100
+ if (!opts.dryRun) {
101
+ const recovered = updateBoard((b) => recoverRunning(b, new Date(deps.now())));
102
+ if (recovered.length)
103
+ out(`Put back in approved after an interrupted run: ${recovered.map((id) => `#${id}`).join(', ')}`);
104
+ }
105
+ const queue = awayQueue(loadBoard());
106
+ const summary = { ran: [], skipped: [], stoppedBecause: null };
107
+ if (queue.length === 0) {
108
+ out('No approved cards. Approve one with `chompyy approve <id>`.');
109
+ return summary;
110
+ }
111
+ out(`${opts.dryRun ? 'Plan' : 'Away'} for ${formatDuration(durationMs)}: ${queue.length} approved card(s), one at a time, ${config.cardTimeoutMin}m max each.`);
112
+ for (const queued of queue) {
113
+ const remaining = deadline - deps.now();
114
+ if (!opts.dryRun && remaining < MIN_CARD_MS) {
115
+ summary.stoppedBecause = 'time is up';
116
+ break;
117
+ }
118
+ if (!opts.dryRun && deps.refreshQuota)
119
+ await deps.refreshQuota();
120
+ const gate = budgetGate(deps.snapshot(), config, new Date(deps.now()));
121
+ if (!gate.ok && !opts.force) {
122
+ summary.stoppedBecause = gate.reasons.join('; ');
123
+ break;
124
+ }
125
+ if (opts.dryRun) {
126
+ const ws = deps.plan(queued);
127
+ out(` would run #${queued.id} ${queued.title}`);
128
+ out(` in ${ws.kind === 'worktree' ? `worktree ${ws.dir} (branch ${ws.branch})` : `draft folder ${ws.dir}`}`);
129
+ summary.ran.push(queued.id);
130
+ continue;
131
+ }
132
+ summary.ran.push(await runCard(queued.id, Math.min(config.cardTimeoutMin * 60_000, remaining), deps));
133
+ }
134
+ const notRun = queue.map((c) => c.id).filter((id) => !summary.ran.includes(id));
135
+ summary.skipped = notRun;
136
+ if (summary.stoppedBecause)
137
+ out(`${opts.dryRun ? 'Would stop' : 'Stopped'}: ${summary.stoppedBecause}.`);
138
+ if (notRun.length)
139
+ out(`Left in approved: ${notRun.map((id) => `#${id}`).join(', ')}`);
140
+ if (opts.dryRun)
141
+ out('Dry run: nothing was started.');
142
+ else
143
+ out(`Done. ${summary.ran.length} card(s) in review. See \`chompyy report\`.`);
144
+ return summary;
145
+ }
146
+ async function runCard(id, timeoutMs, deps) {
147
+ const { config, out } = deps;
148
+ const startedMs = deps.now();
149
+ const card = updateBoard((b) => {
150
+ const c = getCard(b, id);
151
+ c.column = 'running';
152
+ c.updatedAt = new Date(startedMs).toISOString();
153
+ return { ...c };
154
+ });
155
+ out(`▶ #${card.id} ${card.title} (up to ${formatDuration(timeoutMs)})`);
156
+ const logPath = homePath('runs', card.id, `${stamp(startedMs)}.log`);
157
+ let ws = null;
158
+ let status;
159
+ let exitCode = null;
160
+ let summaryText = '';
161
+ let checks;
162
+ let log = '';
163
+ try {
164
+ ws = deps.prepare(card);
165
+ const prompt = taskPrompt(card, ws.dir);
166
+ const cacheDir = homePath('cache', 'tools');
167
+ mkdirSync(cacheDir, { recursive: true });
168
+ const questionsPath = join(ws.dir, 'QUESTIONS.md');
169
+ const questionsBefore = existsSync(questionsPath) ? readFileSync(questionsPath, 'utf8') : null;
170
+ const result = await deps.runner.run({
171
+ prompt,
172
+ cwd: ws.dir,
173
+ timeoutMs,
174
+ model: config.runModel,
175
+ maxTurns: config.maxTurns,
176
+ permissionMode: config.permissionMode,
177
+ permissionPrompts: config.permissionPrompts,
178
+ allowedTools: config.allowedTools,
179
+ disallowedTools: config.disallowedTools,
180
+ ...(config.sandbox ? { settings: sandboxSettings(ws, config.sandboxAllowedDomains, cacheDir) } : {}),
181
+ env: cacheEnv(cacheDir),
182
+ extraArgs: config.extraArgs,
183
+ });
184
+ exitCode = result.exitCode;
185
+ try {
186
+ if (deps.commitLeftovers?.(ws, card))
187
+ out(' (committed changes the agent left uncommitted)');
188
+ }
189
+ catch (err) {
190
+ out(` couldn't commit leftover changes: ${err instanceof Error ? err.message : err}`);
191
+ }
192
+ const hasQuestions = existsSync(questionsPath) && readFileSync(questionsPath, 'utf8') !== questionsBefore;
193
+ status = result.timedOut ? 'timeout' : result.exitCode !== 0 ? 'failed' : hasQuestions ? 'questions' : 'ok';
194
+ checks = parseChecks(result.output);
195
+ summaryText = firstLines(result.output.replace(/^\s*CHECKS:.*$/gim, '')) || firstLines(result.stderr);
196
+ log = `# prompt\n\n${prompt}\n\n# output\n\n${result.output}\n\n# stderr\n\n${result.stderr}\n`;
197
+ }
198
+ catch (err) {
199
+ status = 'error';
200
+ summaryText = String(err instanceof Error ? err.message : err);
201
+ log = `# error\n\n${summaryText}\n`;
202
+ }
203
+ const finishedMs = deps.now();
204
+ const header = `card #${card.id} · ${status} · exit ${exitCode} · ${formatDuration(finishedMs - startedMs)}\nworkdir: ${ws?.dir ?? '-'}${ws?.branch ? `\nbranch: ${ws.branch}` : ''}\n\n`;
205
+ writeFileSync(logPath, header + log);
206
+ updateBoard((b) => {
207
+ const c = getCard(b, id);
208
+ c.column = 'review';
209
+ c.updatedAt = new Date(finishedMs).toISOString();
210
+ c.logPath = logPath;
211
+ c.run = {
212
+ status,
213
+ startedAt: new Date(startedMs).toISOString(),
214
+ finishedAt: new Date(finishedMs).toISOString(),
215
+ durationMs: finishedMs - startedMs,
216
+ exitCode,
217
+ workdir: ws?.dir ?? '',
218
+ ...(ws?.branch ? { branch: ws.branch } : {}),
219
+ summary: summaryText,
220
+ ...(checks ? { checks } : {}),
221
+ };
222
+ });
223
+ out(` → ${status} · ${formatDuration(finishedMs - startedMs)} · log ${logPath}`);
224
+ return card.id;
225
+ }
@@ -0,0 +1,91 @@
1
+ export const BLUEPRINT_SECTIONS = ['Goal', 'Scope', 'Out of scope', 'Shape', "How it's checked"];
2
+ export function blueprintPrompt(card) {
3
+ return `You write short blueprints for tasks a coding agent will run unattended, with nobody to ask.
4
+ Turn the idea below into a blueprint. Reply with ONLY this Markdown, no preamble:
5
+
6
+ ## Goal
7
+ <one line: what exists when this is done>
8
+
9
+ ## Scope
10
+ - <3 to 5 bullets of what the result will contain>
11
+
12
+ ## Out of scope
13
+ - <1 to 3 bullets of what will NOT be done, especially anything outward: no push, merge, PR, sending or posting. Committing is fine: the run commits to the card's own branch, which Chompyy creates; don't name a branch>
14
+
15
+ ## Shape
16
+ <a short outline of the artifact: files, sections or steps>
17
+
18
+ ## How it's checked
19
+ - <how someone can verify the result without the author: tests, files that exist, cited sources>
20
+
21
+ Look at the working directory first (read-only) so the blueprint fits what is really there: its files,
22
+ languages, test command and tooling. Don't plan steps for tools the repo doesn't have.
23
+
24
+ The run can only change files inside the working directory. Its shell has no network, but the agent CAN
25
+ 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.
30
+
31
+ Keep it under 200 words. Pick the smallest useful version of the idea.
32
+ Never write "no commits" or "leave files untracked": the run always commits to the card's own branch (Chompyy
33
+ creates and names it, so don't name one), and that branch is how the user reviews, keeps or undoes the work.
34
+ Don't plan a QUESTIONS.md by default. Only if the idea truly can't be done without a decision only the user
35
+ can make, say so in Out of scope and plan to write that question to QUESTIONS.md.
36
+
37
+ Working directory: ${card.cwd}
38
+ Idea: ${card.idea}`;
39
+ }
40
+ /** Strip chatter before the first heading; insist on the Goal heading. */
41
+ export function cleanBlueprint(output) {
42
+ const text = output.trim();
43
+ const start = text.indexOf('## Goal');
44
+ if (start === -1)
45
+ throw new Error('The model reply has no "## Goal" section.');
46
+ return text.slice(start).trim();
47
+ }
48
+ export async function draftBlueprint(card, runner, opts) {
49
+ const result = await runner.run({
50
+ prompt: blueprintPrompt(card),
51
+ cwd: opts.cwd,
52
+ model: opts.model,
53
+ tools: 'Read,Glob,Grep',
54
+ timeoutMs: opts.timeoutMs ?? 120_000,
55
+ });
56
+ if (result.timedOut)
57
+ throw new Error('Blueprint model timed out.');
58
+ if (result.exitCode !== 0)
59
+ throw new Error(`claude exited with ${result.exitCode}: ${result.stderr.trim().slice(0, 300)}`);
60
+ return cleanBlueprint(result.output);
61
+ }
62
+ /** Generic options when a card-specific list can't be made (e.g. no active window). */
63
+ export const GENERIC_FIVE_STAR = ['Closer to what I asked for', 'Shorter and simpler', 'More thorough', 'A different format'];
64
+ export function fiveStarPrompt(card) {
65
+ return `A coding agent finished a task and the user rated it below 5 stars. Suggest what would most likely
66
+ have made it a 5 for this user. Reply with ONLY 4 lines, one option per line, no numbering, no bullets.
67
+ Each option: a concrete, specific change to the result, at most 9 words, written as the user would say it
68
+ (e.g. "Put the answers in a separate file"). Make them different from each other.
69
+
70
+ Task: ${card.idea}
71
+
72
+ Blueprint:
73
+ ${card.blueprint ?? '(none)'}
74
+
75
+ What the agent said it did:
76
+ ${card.summary ?? '(nothing)'}
77
+
78
+ Files changed: ${(card.files ?? []).join(', ') || '(unknown)'}`;
79
+ }
80
+ export async function draftFiveStarOptions(card, runner, opts) {
81
+ const result = await runner.run({ prompt: fiveStarPrompt(card), cwd: opts.cwd, model: opts.model, tools: '', timeoutMs: 60_000 });
82
+ if (result.exitCode !== 0 || result.timedOut)
83
+ throw new Error('could not draft options');
84
+ const lines = result.output
85
+ .split('\n')
86
+ .map((l) => l.replace(/^\s*([-*•]|\d+[.)])\s*/, '').replace(/^"|"$/g, '').trim())
87
+ .filter((l) => l.length > 2 && l.length < 90);
88
+ if (lines.length < 2)
89
+ throw new Error('could not draft options');
90
+ return lines.slice(0, 4);
91
+ }