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.
@@ -0,0 +1,290 @@
1
+ // Refresh (2026-11-19): Chompyy keeps cards in review up to date with main by itself. Cards from one night start
2
+ // from the same main; keeping one can make the next clash with it (#20 and #21 after #12, #19, #22 were kept).
3
+ // You shouldn't have to pick an order or merge by hand. After each Keep, every card in review that now clashes
4
+ // is brought onto the new main: git merges it when it can, and when it can't, a short agent session in the
5
+ // card's own sandbox fits both changes together. Then Chompyy's own check runs again against the new main.
6
+ // Pressing Keep on a clashing card does the same and keeps it once the check passes.
7
+ import { execFileSync } from 'node:child_process';
8
+ import { closeSync, existsSync, openSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
9
+ import { join, resolve } from 'node:path';
10
+ import { awayTools, cacheEnv, denyReadRules, safetyRules, sandboxSettings } from './away.js';
11
+ import { getCard, loadBoard, updateBoard } from './board.js';
12
+ import { homePath } from './home.js';
13
+ import { windowView } from './quota.js';
14
+ import { commitLeftovers, gitRoot, restoreGitLink } from './workspace.js';
15
+ const git = (cwd, args) => execFileSync('git', ['-C', cwd, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim();
16
+ const ok = (cwd, args) => {
17
+ try {
18
+ git(cwd, args);
19
+ return true;
20
+ }
21
+ catch {
22
+ return false;
23
+ }
24
+ };
25
+ /** The branch Keep would land the card on. */
26
+ export function landingBranch(card) {
27
+ if (card.run?.base?.branch)
28
+ return card.run.base.branch;
29
+ try {
30
+ return git(card.cwd, ['rev-parse', '--abbrev-ref', 'HEAD']) || null;
31
+ }
32
+ catch {
33
+ return null;
34
+ }
35
+ }
36
+ /**
37
+ * Would Keep clash? For a card in review: the landing branch's commit, and the files git can't merge by itself.
38
+ * Null when it merges cleanly (or isn't a branch card in review). Uses `git merge-tree`, which touches no folder.
39
+ */
40
+ export function clashOf(card) {
41
+ const run = card.run;
42
+ if (card.column !== 'review' || !run?.branch)
43
+ return null;
44
+ const repo = gitRoot(card.cwd);
45
+ const branch = landingBranch(card);
46
+ if (!repo || !branch)
47
+ return null;
48
+ try {
49
+ const onto = git(repo, ['rev-parse', branch]);
50
+ if (ok(repo, ['merge-base', '--is-ancestor', onto, run.branch]))
51
+ return null; // already has it
52
+ try {
53
+ git(repo, ['merge-tree', '--write-tree', '--name-only', onto, run.branch]);
54
+ return null; // merges cleanly
55
+ }
56
+ catch (err) {
57
+ const e = err;
58
+ if (e.status !== 1)
59
+ return null; // not a conflict (an old git, a missing branch): leave it to Keep
60
+ const files = String(e.stdout ?? '').split('\n\n')[0].split('\n').slice(1).filter(Boolean);
61
+ return { onto, branch, files: [...new Set(files)] };
62
+ }
63
+ }
64
+ catch {
65
+ return null;
66
+ }
67
+ }
68
+ /** Why a refresh must wait, or null. Like drafting: it finishes work you already chose, so only a used-up window stops it. */
69
+ export function refreshGate(snap, now) {
70
+ const five = windowView(snap?.fiveHour, now);
71
+ const week = windowView(snap?.sevenDay, now);
72
+ if (five.known && five.usedPct >= 100)
73
+ return 'the 5-hour window is used up; it updates after the reset';
74
+ if (week.known && week.usedPct >= 100)
75
+ return 'the weekly limit is used up; it updates after the reset';
76
+ return null;
77
+ }
78
+ export function refreshPrompt(card, workdir, branch, files, checks) {
79
+ return `${safetyRules(workdir)}
80
+
81
+ # Bring card #${card.id} up to date with ${branch}
82
+
83
+ This folder is card #${card.id} ("${card.title}"), waiting for review. Meanwhile other work was kept on ${branch}, and
84
+ the two now clash. Chompyy has already started \`git merge ${branch}\` here; these files have conflicts:
85
+
86
+ ${files.map((f) => `- ${f}`).join('\n')}
87
+
88
+ Resolve every conflict so that BOTH changes work: this card's change (what it was for: ${card.idea}) and what is
89
+ already on ${branch}. Usually that means keeping both sides and fitting them together: both imports, both fields,
90
+ both functions, both tests. Don't drop either side's feature, don't change anything else, and don't restart or
91
+ abort the merge. Leave the resolved files as they are: don't \`git add\` or commit (.git is read-only to you).
92
+ Chompyy checks them and finishes the merge.
93
+ ${checks.length ? `
94
+ After the merge, check it (these pass on ${branch}):
95
+ ${checks.map((c) => `- in ${c.dir || 'the top folder'}: \`${c.label}\``).join('\n')}
96
+ ` : ''}`;
97
+ }
98
+ function setRefresh(id, refresh, extra = () => { }) {
99
+ updateBoard((b) => {
100
+ const c = getCard(b, id);
101
+ c.refresh = refresh;
102
+ extra(c);
103
+ c.updatedAt = refresh.at;
104
+ });
105
+ }
106
+ /** Markers git leaves in a conflicted file. */
107
+ const MARKERS = /^(<{7}|>{7})( |$)/m;
108
+ /** Bring one card in review onto its landing branch. Returns what happened (also saved on the card). */
109
+ export async function refreshCard(id, deps) {
110
+ const card = getCard(loadBoard(), id);
111
+ const at = () => deps.now().toISOString();
112
+ const keepIfAsked = (verified) => {
113
+ if (!card.keepWhenRefreshed || !deps.keep)
114
+ return;
115
+ if (verified && verified.result !== 'passed')
116
+ return deps.out(` not keeping #${id} by itself: ${verified.why}`);
117
+ deps.keep(id);
118
+ };
119
+ const clash = clashOf(card);
120
+ if (!clash) {
121
+ const done = { state: 'done', why: 'already merges cleanly with main', at: at() };
122
+ if (card.refresh || card.keepWhenRefreshed)
123
+ setRefresh(id, done);
124
+ keepIfAsked(undefined);
125
+ return done;
126
+ }
127
+ const short = clash.onto.slice(0, 7);
128
+ const waiting = refreshGate(deps.snapshot(), deps.now());
129
+ if (waiting) {
130
+ const r = { state: 'waiting', onto: clash.onto, files: clash.files, why: waiting, at: at() };
131
+ setRefresh(id, r);
132
+ deps.out(` #${id} clashes with ${clash.branch} but waits: ${waiting}`);
133
+ return r;
134
+ }
135
+ const run = card.run;
136
+ const dir = run.workdir;
137
+ const fail = (why) => {
138
+ const r = { state: 'failed', onto: clash.onto, files: clash.files, why, at: at() };
139
+ setRefresh(id, r, (c) => delete c.keepWhenRefreshed);
140
+ deps.out(` ✗ #${id}: ${why}`);
141
+ return r;
142
+ };
143
+ if (!existsSync(join(dir, '.git')))
144
+ return fail(`its folder ${dir} is gone; run it again on top of the latest with \`chompyy redo ${id}\``);
145
+ setRefresh(id, { state: 'running', onto: clash.onto, files: clash.files, why: `bringing it onto ${clash.branch} @ ${short}`, at: at() });
146
+ deps.out(`▶ refreshing #${id} onto ${clash.branch} @ ${short} (clashes in ${clash.files.join(', ')})`);
147
+ commitLeftovers({ kind: 'worktree', dir }, card);
148
+ const before = git(dir, ['rev-parse', 'HEAD']);
149
+ let agentGitDir;
150
+ const undo = () => {
151
+ if (agentGitDir)
152
+ restoreGitLink(dir, agentGitDir); // the agent may have repointed it; never run git through its link
153
+ if (ok(dir, ['rev-parse', '-q', '--verify', 'MERGE_HEAD']))
154
+ ok(dir, ['merge', '--abort']);
155
+ ok(dir, ['reset', '-q', '--hard', before]);
156
+ };
157
+ let by = 'git';
158
+ let tokens;
159
+ const ident = ['-c', 'user.name=Chompyy', '-c', 'user.email=chompyy@localhost'];
160
+ if (!ok(dir, [...ident, 'merge', '--no-edit', '-m', `Bring Chompyy card #${id} up to date with ${clash.branch}`, clash.onto])) {
161
+ by = 'agent';
162
+ const config = deps.config;
163
+ const gitDir = resolve(dir, git(dir, ['rev-parse', '--git-common-dir']));
164
+ const ws = { kind: 'worktree', dir, branch: run.branch, gitDir };
165
+ agentGitDir = gitDir;
166
+ const cacheDir = homePath('cache', 'tools');
167
+ try {
168
+ const result = await deps.runner.run({
169
+ prompt: refreshPrompt(card, dir, clash.branch, clash.files, deps.repoChecks?.(card) ?? []),
170
+ cwd: dir,
171
+ timeoutMs: deps.timeoutMs ?? 15 * 60_000,
172
+ model: config.runModel,
173
+ maxTurns: config.maxTurns,
174
+ permissionMode: config.permissionMode,
175
+ permissionPrompts: config.permissionPrompts,
176
+ allowedTools: awayTools(config),
177
+ disallowedTools: [...config.disallowedTools, ...denyReadRules(config.denyReadPaths)],
178
+ ...(config.sandbox ? { settings: sandboxSettings(ws, config.sandboxAllowedDomains, cacheDir, config.denyReadPaths) } : {}),
179
+ env: cacheEnv(cacheDir),
180
+ extraArgs: config.extraArgs,
181
+ ...(config.idleTimeoutMin > 0 ? { idleTimeoutMs: config.idleTimeoutMin * 60_000 } : {}),
182
+ rawLogPath: homePath('runs', id, `refresh-${at().replace(/[:.]/g, '-')}.stream.jsonl`),
183
+ });
184
+ tokens = result.tokens;
185
+ if (result.timedOut || result.stuck || result.stalled) {
186
+ undo();
187
+ return fail(`the agent couldn't finish fitting the changes together (${result.timedOut ? 'ran out of time' : result.stuck ?? result.stalled}); nothing was changed`);
188
+ }
189
+ }
190
+ catch (err) {
191
+ undo();
192
+ return fail(`the agent didn't run (${err instanceof Error ? err.message : err}); nothing was changed`);
193
+ }
194
+ // The agent can't write .git, so Chompyy finishes the merge: only once no conflict markers are left.
195
+ restoreGitLink(dir, gitDir);
196
+ const resolved = clash.files.every((f) => !existsSync(join(dir, f)) || !MARKERS.test(readFileSync(join(dir, f), 'utf8')));
197
+ if (resolved && ok(dir, ['rev-parse', '-q', '--verify', 'MERGE_HEAD'])) {
198
+ ok(dir, ['add', '-A', '--', ...clash.files]);
199
+ ok(dir, ['add', '-u']);
200
+ ok(dir, [...ident, 'commit', '--no-verify', '--no-edit']);
201
+ }
202
+ // Chompyy checks the merge itself, never on the agent's word.
203
+ const stillMerging = ok(dir, ['rev-parse', '-q', '--verify', 'MERGE_HEAD']);
204
+ const leftMarkers = clash.files.filter((f) => existsSync(join(dir, f)) && MARKERS.test(readFileSync(join(dir, f), 'utf8')));
205
+ const hasMain = ok(dir, ['merge-base', '--is-ancestor', clash.onto, 'HEAD']);
206
+ if (stillMerging || leftMarkers.length || !hasMain) {
207
+ undo();
208
+ return fail(leftMarkers.length
209
+ ? `conflict markers were left in ${leftMarkers.join(', ')}; nothing was changed`
210
+ : stillMerging
211
+ ? "the merge wasn't finished; nothing was changed"
212
+ : `the result doesn't contain ${clash.branch}; nothing was changed`);
213
+ }
214
+ }
215
+ const base = { ref: run.base?.ref ?? clash.branch, branch: clash.branch, commit: clash.onto };
216
+ let verified;
217
+ if (deps.verify) {
218
+ deps.out(' checking it against the new main (running the repo\'s tests, sandboxed)…');
219
+ verified = await deps.verify({ kind: 'worktree', dir, branch: run.branch, base }, card).catch(() => undefined);
220
+ if (verified)
221
+ deps.out(` ${verified.result === 'passed' ? '✓' : verified.result === 'failed' ? '✗' : '·'} ${verified.why}`);
222
+ }
223
+ const done = {
224
+ state: 'done',
225
+ onto: clash.onto,
226
+ files: clash.files,
227
+ by,
228
+ ...(tokens ? { tokens } : {}),
229
+ why: by === 'agent' ? `brought onto ${clash.branch} @ ${short}; an agent fitted both changes together in ${clash.files.join(', ')}` : `brought onto ${clash.branch} @ ${short}`,
230
+ at: at(),
231
+ };
232
+ setRefresh(id, done, (c) => {
233
+ c.run = { ...c.run, base, ...(verified ? { verified } : {}) };
234
+ });
235
+ deps.out(` → #${id} is up to date with ${clash.branch}`);
236
+ keepIfAsked(verified);
237
+ return done;
238
+ }
239
+ /** Every card in review that clashes with its main, one at a time. */
240
+ export async function refreshClashing(deps) {
241
+ const out = [];
242
+ for (const c of loadBoard().cards) {
243
+ if (c.column !== 'review' || !c.run?.branch)
244
+ continue;
245
+ if (!clashOf(c) && !c.keepWhenRefreshed && c.refresh?.state !== 'waiting')
246
+ continue;
247
+ out.push(await refreshCard(c.id, deps));
248
+ }
249
+ return out;
250
+ }
251
+ /**
252
+ * One refresh at a time (two Keeps in a row ask twice). A second ask leaves a note and the running one goes
253
+ * round again, so every card ends up on the newest main. Returns false when another refresh took the ask.
254
+ */
255
+ export async function withRefreshLock(fn) {
256
+ const lock = homePath('refresh.lock');
257
+ const again = homePath('refresh.again');
258
+ let fd;
259
+ try {
260
+ fd = openSync(lock, 'wx');
261
+ }
262
+ catch {
263
+ const pid = Number(readFileSync(lock, 'utf8')) || 0;
264
+ let alive = false;
265
+ try {
266
+ if (pid)
267
+ process.kill(pid, 0);
268
+ alive = pid > 0;
269
+ }
270
+ catch { }
271
+ if (alive) {
272
+ writeFileSync(again, '');
273
+ return false;
274
+ }
275
+ rmSync(lock, { force: true });
276
+ fd = openSync(lock, 'wx');
277
+ }
278
+ try {
279
+ writeFileSync(fd, String(process.pid));
280
+ do {
281
+ rmSync(again, { force: true });
282
+ await fn();
283
+ } while (existsSync(again));
284
+ return true;
285
+ }
286
+ finally {
287
+ closeSync(fd);
288
+ rmSync(lock, { force: true });
289
+ }
290
+ }
package/dist/report.js CHANGED
@@ -1,5 +1,6 @@
1
1
  // "While you were away" report and rating (spec §5.7).
2
2
  import { getCard } from './board.js';
3
+ import { formatTokens } from './tokens.js';
3
4
  import { formatDuration } from './duration.js';
4
5
  import { wrap } from './review.js';
5
6
  import { appendJsonl, homePath, readJson, writeJson } from './home.js';
@@ -97,6 +98,8 @@ export function formatReport(cards, since, facts, extras = {}) {
97
98
  wrap(q, 70).forEach((part, i) => out.push(` ${i === 0 ? '·' : ' '} ${part}`));
98
99
  if (!decided)
99
100
  out.push(` changed: ${filesLine(files)} · took ${formatDuration(c.run.durationMs)}`);
101
+ if (!decided && c.run.tokens)
102
+ out.push(` used: ${formatTokens(c.run.tokens)}`);
100
103
  out.push('');
101
104
  }
102
105
  const top = sorted[0];
package/dist/review.js CHANGED
@@ -3,7 +3,16 @@
3
3
  import { execFileSync } from 'node:child_process';
4
4
  import { existsSync, readFileSync, readdirSync, rmSync } from 'node:fs';
5
5
  import { join } from 'node:path';
6
+ import { homePath } from './home.js';
6
7
  import { commitLeftovers, gitRoot, uncommittedWork } from './workspace.js';
8
+ /**
9
+ * What a card's changes are measured from: the commit it started from (the latest main at the time), so the
10
+ * list shows only the card's own work. Measuring from your folder's HEAD showed 56 files for a 6-file card when
11
+ * the folder sat on an older commit (2026-11-18). Older cards without a base fall back to HEAD.
12
+ */
13
+ function since(run) {
14
+ return run.base?.commit ?? 'HEAD';
15
+ }
7
16
  function git(cwd, args) {
8
17
  return execFileSync('git', ['-C', cwd, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim();
9
18
  }
@@ -59,7 +68,7 @@ export function changedFiles(card) {
59
68
  const root = gitRoot(card.cwd);
60
69
  if (!root)
61
70
  return [];
62
- return git(root, ['diff', '--name-only', `HEAD...${run.branch}`]).split('\n').filter(Boolean);
71
+ return git(root, ['diff', '--name-only', `${since(run)}...${run.branch}`]).split('\n').filter(Boolean);
63
72
  }
64
73
  return readdirSync(run.workdir, { recursive: true, withFileTypes: true })
65
74
  .filter((d) => d.isFile())
@@ -105,41 +114,84 @@ export function diffCard(card) {
105
114
  const root = gitRoot(card.cwd);
106
115
  if (!root)
107
116
  throw new Error(`${card.cwd} is no longer a git repo.`);
108
- return git(root, ['diff', '--stat', '--patch', `HEAD...${run.branch}`]) || 'No changes on the branch.';
117
+ return git(root, ['diff', '--stat', '--patch', `${since(run)}...${run.branch}`]) || 'No changes on the branch.';
109
118
  }
110
119
  function removeWorktree(root, card) {
111
120
  const run = ran(card);
112
121
  if (existsSync(run.workdir))
113
122
  git(root, ['worktree', 'remove', '--force', run.workdir]);
114
123
  }
115
- /** Merge the card's branch into the repo's current branch, then tidy up the worktree. */
124
+ /**
125
+ * Where Keep lands a card that started from the latest main: the folder that has that branch open (merged there,
126
+ * with your unsaved work protected as before), else a temporary copy of the branch, so your folders aren't touched.
127
+ */
128
+ export function landingFor(root, branch, id) {
129
+ const blocks = git(root, ['worktree', 'list', '--porcelain']).split('\n\n');
130
+ for (const b of blocks) {
131
+ const dir = b.match(/^worktree (.+)$/m)?.[1];
132
+ if (dir && b.includes(`\nbranch refs/heads/${branch}`) && existsSync(dir))
133
+ return { dir, temporary: false };
134
+ }
135
+ const has = (ref) => {
136
+ try {
137
+ git(root, ['rev-parse', '--verify', '--quiet', ref]);
138
+ return true;
139
+ }
140
+ catch {
141
+ return false;
142
+ }
143
+ };
144
+ if (!has(`refs/heads/${branch}`)) {
145
+ if (!has(`refs/remotes/origin/${branch}`))
146
+ throw new Error(`There's no ${branch} branch in ${root} to keep this card on.`);
147
+ git(root, ['branch', branch, `origin/${branch}`]);
148
+ }
149
+ const dir = homePath('landing', id);
150
+ rmSync(dir, { recursive: true, force: true });
151
+ git(root, ['worktree', 'add', '--quiet', dir, branch]);
152
+ return { dir, temporary: true };
153
+ }
154
+ /** Merge the card's branch into the branch it started from (or, for older cards, the repo's current branch), then tidy up. */
116
155
  export function keepCard(card) {
117
156
  const run = ran(card);
118
157
  if (!run.branch)
119
158
  return `Card #${card.id} ran in a draft folder; copy what you want from ${run.workdir}`;
120
- const root = gitRoot(card.cwd);
121
- if (!root)
159
+ const repo = gitRoot(card.cwd);
160
+ if (!repo)
122
161
  throw new Error(`${card.cwd} is no longer a git repo.`);
162
+ const landing = run.base?.branch ? landingFor(repo, run.base.branch, card.id) : { dir: repo, temporary: false };
163
+ const root = landing.dir;
164
+ const dropLanding = () => {
165
+ if (landing.temporary) {
166
+ try {
167
+ git(repo, ['worktree', 'remove', '--force', landing.dir]);
168
+ }
169
+ catch { }
170
+ }
171
+ };
123
172
  // Your own unsaved work only blocks Keep when it touches the same files as the card (git's own rule),
124
173
  // or when something is staged (git won't put unrelated staged changes into a merge commit).
125
174
  const into = git(root, ['rev-parse', '--abbrev-ref', 'HEAD']);
126
175
  const yours = [...new Set(git(root, ['status', '--porcelain', '--untracked-files=all']).split('\n').filter(Boolean)
127
176
  .map((l) => l.trim().replace(/^\S+\s+/, '').replace(/^.* -> /, '')))];
128
177
  if (yours.length) {
129
- const theirs = new Set(git(root, ['diff', '--name-only', `HEAD...${run.branch}`]).split('\n').filter(Boolean));
178
+ const theirs = new Set(git(root, ['diff', '--name-only', `${since(run)}...${run.branch}`]).split('\n').filter(Boolean));
130
179
  const clash = yours.filter((f) => theirs.has(f));
131
180
  const staged = git(root, ['diff', '--cached', '--name-only']).split('\n').filter(Boolean);
132
181
  const list = (fs) => fs.slice(0, 3).join(', ') + (fs.length > 3 ? ` and ${fs.length - 3} more` : '');
133
182
  if (clash.length) {
183
+ dropLanding();
134
184
  throw new Error(`Can't keep #${card.id} yet: it changes ${list(clash)}, and you have unsaved changes in ${clash.length === 1 ? 'that file' : 'those files'} in ${root} (branch ${into}). Commit or set them aside first, or press Undo to drop the card's work.`);
135
185
  }
136
186
  if (staged.length) {
187
+ dropLanding();
137
188
  throw new Error(`Can't keep #${card.id} yet: ${root} has staged changes (${list(staged)}) that a merge would mix in. Commit or unstage them first, or press Undo to drop the card's work.`);
138
189
  }
139
190
  }
140
191
  commitLeftovers({ kind: 'worktree', dir: run.workdir }, card); // older runs may have left work uncommitted
141
192
  const loose = uncommittedWork(run.workdir);
142
193
  if (loose.length) {
194
+ dropLanding();
143
195
  throw new Error(`The card's folder has uncommitted work that keep would lose: ${loose.slice(0, 5).join(', ')}. Commit it in ${run.workdir} first.`);
144
196
  }
145
197
  try {
@@ -150,12 +202,17 @@ export function keepCard(card) {
150
202
  git(root, ['merge', '--abort']);
151
203
  }
152
204
  catch { }
205
+ dropLanding();
153
206
  throw new Error(`${run.branch} conflicts with ${into}: another card or your own work changed the same lines. Nothing was changed. Run it again on top of the latest with \`chompyy redo ${card.id}\` (or merge by hand: git -C ${root} merge ${run.branch}).`);
154
207
  }
155
- removeWorktree(root, card);
156
- git(root, ['branch', '-d', run.branch]);
208
+ dropLanding();
209
+ removeWorktree(repo, card);
210
+ git(repo, ['branch', '-D', run.branch]); // merged just now (into the landing branch, which may not be this folder's)
157
211
  const note = yours.length ? ` Your ${yours.length} unsaved change${yours.length === 1 ? ' was' : 's were'} left as they were.` : '';
158
- return `Kept #${card.id}: merged ${run.branch} into ${into}.${note} Undo it with \`git -C ${root} reset --hard HEAD~1\`.`;
212
+ if (landing.temporary) {
213
+ return `Kept #${card.id}: merged ${run.branch} into ${into} (none of your folders has ${into} open, so they weren't touched).${note} Undo it with \`git -C ${repo} branch -f ${into} ${into}~1\`.`;
214
+ }
215
+ return `Kept #${card.id}: merged ${run.branch} into ${into}${root !== repo ? ` in ${root}` : ''}.${note} Undo it with \`git -C ${root} reset --hard HEAD~1\`.`;
159
216
  }
160
217
  /** Throw the run away: remove the worktree and branch (or the draft folder). */
161
218
  export function undoCard(card) {
package/dist/runner.js CHANGED
@@ -1,7 +1,9 @@
1
1
  // The one seam: something that runs a prompt headless. ClaudeRunner wraps `claude -p`;
2
2
  // tests pass a fake.
3
3
  import { spawn, spawnSync } from 'node:child_process';
4
+ import { TokenTally } from './tokens.js';
4
5
  import { closeSync, openSync, writeSync } from 'node:fs';
6
+ import { commandPattern, hostsInErrors } from './permissions.js';
5
7
  /** The raw output written to disk, cut off after `max` bytes (with a note saying so). */
6
8
  export class RawLog {
7
9
  max;
@@ -38,10 +40,16 @@ export class RawLog {
38
40
  this.fd = null;
39
41
  }
40
42
  }
43
+ // Chompyy's runs never pick up other tools' hooks or MCP servers: a SessionStart hook would add its rules to
44
+ // every call, and a blocking Stop hook can force an extra turn whose reply replaces ours (headroom hit this;
45
+ // research/detective/RULEBOOK.md rule T3). Your login, settings, permissions and CLAUDE.md still load.
46
+ // (--bare would skip hooks too, but it also skips the subscription login.)
47
+ export const ISOLATION_ARGS = ['--strict-mcp-config'];
48
+ export const ISOLATION_SETTINGS = { disableAllHooks: true };
41
49
  export function claudeArgs(req) {
42
- const args = req.loopRepeat
43
- ? ['-p', '--output-format', 'stream-json', '--verbose', '--no-session-persistence']
44
- : ['-p', '--output-format', 'text', '--no-session-persistence'];
50
+ const args = req.loopRepeat || req.stream
51
+ ? ['-p', '--output-format', 'stream-json', '--verbose', '--no-session-persistence', ...ISOLATION_ARGS]
52
+ : ['-p', '--output-format', 'text', '--no-session-persistence', ...ISOLATION_ARGS];
45
53
  if (req.model)
46
54
  args.push('--model', req.model);
47
55
  if (req.maxTurns)
@@ -56,8 +64,7 @@ export function claudeArgs(req) {
56
64
  args.push('--allowedTools', ...req.allowedTools);
57
65
  if (req.disallowedTools?.length)
58
66
  args.push('--disallowedTools', ...req.disallowedTools);
59
- if (req.settings)
60
- args.push('--settings', JSON.stringify(req.settings));
67
+ args.push('--settings', JSON.stringify({ ...req.settings, ...ISOLATION_SETTINGS }));
61
68
  if (req.extraArgs?.length)
62
69
  args.push(...req.extraArgs);
63
70
  return args;
@@ -277,8 +284,15 @@ export class ClaudeRunner {
277
284
  let timedOut = false;
278
285
  let stuck;
279
286
  const final = new FinalText();
287
+ let denied = 0;
288
+ const deniedTools = new Map();
289
+ // What it was blocked on: blocked Bash calls link back to their command by id; hosts come from error text.
290
+ const bashCommands = new Map();
291
+ const neededCommands = new Set();
292
+ const neededHosts = new Set();
280
293
  const raw = new RawLog(req.rawLogPath, req.rawLogMaxBytes);
281
- const watch = req.loopRepeat ? new LoopWatch(req.loopRepeat) : null;
294
+ const tally = new TokenTally();
295
+ const watch = req.loopRepeat ? new LoopWatch(req.loopRepeat) : req.stream ? new LoopWatch(Number.POSITIVE_INFINITY) : null;
282
296
  const lines = new LineReader((line) => {
283
297
  if (!line.trim())
284
298
  return;
@@ -290,6 +304,37 @@ export class ClaudeRunner {
290
304
  return;
291
305
  }
292
306
  final.feed(event);
307
+ tally.feed(event);
308
+ const ev = event;
309
+ if (Array.isArray(ev.message?.content)) {
310
+ for (const b of ev.message.content) {
311
+ if (b?.type === 'tool_use' && b.name === 'Bash' && b.id && typeof b.input?.command === 'string')
312
+ bashCommands.set(b.id, b.input.command);
313
+ if (b?.type === 'tool_result') {
314
+ const text = typeof b.content === 'string' ? b.content : JSON.stringify(b.content ?? '');
315
+ for (const h of hostsInErrors(text.slice(0, 20_000)))
316
+ neededHosts.add(h);
317
+ }
318
+ }
319
+ }
320
+ if (ev.type === 'system' && ev.subtype === 'permission_denied') {
321
+ if (ev.tool_name === 'Bash' && ev.tool_use_id) {
322
+ const pattern = commandPattern(bashCommands.get(ev.tool_use_id) ?? '');
323
+ if (pattern)
324
+ neededCommands.add(pattern);
325
+ }
326
+ // A blocked action isn't progress. Thousands of them (npm retrying with no network) mean it's stuck.
327
+ denied++;
328
+ deniedTools.set(ev.tool_name ?? '?', (deniedTools.get(ev.tool_name ?? '?') ?? 0) + 1);
329
+ if (req.maxDenied && denied >= req.maxDenied && !stuck) {
330
+ const top = [...deniedTools.entries()].sort((a, b) => b[1] - a[1])[0]?.[0] ?? '?';
331
+ stuck = `the sandbox blocked it ${denied} times (mostly ${top === 'SandboxNetworkAccess' ? 'network access: away runs are offline' : top})`;
332
+ killAll('SIGTERM');
333
+ setTimeout(() => killAll('SIGKILL'), 5000).unref();
334
+ }
335
+ return;
336
+ }
337
+ poke();
293
338
  const why = stuck ? null : watch.feed(event);
294
339
  if (why) {
295
340
  stuck = why;
@@ -314,7 +359,8 @@ export class ClaudeRunner {
314
359
  };
315
360
  poke();
316
361
  child.stdout.on('data', (d) => {
317
- poke();
362
+ if (!watch)
363
+ poke(); // with stream-json, a line counts as progress only if it isn't a blocked action
318
364
  raw.write(d);
319
365
  if (watch)
320
366
  lines.push(d);
@@ -339,7 +385,9 @@ export class ClaudeRunner {
339
385
  if (watch)
340
386
  lines.end();
341
387
  const output = watch ? final.text() : text.toString();
342
- resolve({ exitCode, output, stderr: stderr.toString(), timedOut, durationMs: Date.now() - started, ...(stuck ? { stuck } : {}), ...(stalled ? { stalled } : {}) });
388
+ resolve({ exitCode, output, stderr: stderr.toString(), timedOut, durationMs: Date.now() - started, ...(stuck ? { stuck } : {}), ...(stalled ? { stalled } : {}),
389
+ ...(tally.total() ? { tokens: tally.total() } : {}),
390
+ ...(neededCommands.size || neededHosts.size ? { needs: { commands: [...neededCommands], hosts: [...neededHosts] } } : {}) });
343
391
  };
344
392
  child.on('error', (err) => {
345
393
  stderr.push(String(err));