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,146 @@
1
+ // Verify, main vs card (research/away-readiness.md, step 4): after a card runs, Chompyy runs the repo's checks
2
+ // itself on the card's copy AND on the main it started from, both in the sandbox, and reports only what the card
3
+ // made worse. The agent's own "CHECKS:" line becomes a claim; this is the measurement.
4
+ // passes on the card → ok
5
+ // fails on the card, passes on main → the card broke it (with the failing tests when readable)
6
+ // fails on both, same failing tests → not the card: main fails the same way
7
+ // fails on both, new failing tests on the card → the card broke those tests
8
+ // Main's results are cached per commit, so cards that started from the same main share one run.
9
+ import { execFileSync } from 'node:child_process';
10
+ import { createHash } from 'node:crypto';
11
+ import { existsSync, rmSync } from 'node:fs';
12
+ import { basename, join } from 'node:path';
13
+ import { cacheEnv } from './away.js';
14
+ import { setupDependencies } from './deps.js';
15
+ import { homePath, readJson, writeJson } from './home.js';
16
+ import { detectChecks } from './preflight.js';
17
+ import { run as runCmd, sandboxProfile } from './verify.js';
18
+ /** Names of failing tests in common test runners' output (vitest/jest, go test, pytest, XCTest, cargo). */
19
+ export function failingTests(output) {
20
+ const clean = output.replace(/\u001b\[[0-9;]*[A-Za-z]/g, '');
21
+ const names = new Set();
22
+ for (const m of clean.matchAll(/^\s*(?:FAIL|×|✗)\s+(\S+\.(?:test|spec)\.[jt]sx?\s*>.+?)\s*(?:\d+ms)?$/gm))
23
+ names.add(m[1].trim());
24
+ for (const m of clean.matchAll(/^\s*×\s+(.+?)\s+\d+ms\s*$/gm))
25
+ names.add(m[1].trim());
26
+ for (const m of clean.matchAll(/^--- FAIL: (\S+)/gm))
27
+ names.add(m[1]);
28
+ for (const m of clean.matchAll(/^FAILED (\S+::\S+)/gm))
29
+ names.add(m[1]);
30
+ for (const m of clean.matchAll(/Test Case '-\[(\S+ \S+)\]' failed/g))
31
+ names.add(m[1]);
32
+ for (const m of clean.matchAll(/^test (\S+) \.\.\. FAILED/gm))
33
+ names.add(m[1]);
34
+ // vitest prints a failure twice ("× name" and "FAIL file > name"): keep the fuller one.
35
+ const all = [...names];
36
+ return all.filter((n) => !all.some((m) => m !== n && m.endsWith(` > ${n}`))).sort();
37
+ }
38
+ const tail = (t) => t.replace(/\u001b\[[0-9;]*[A-Za-z]/g, '').trimEnd().split('\n').slice(-12).join('\n').slice(-1500);
39
+ const key = (c) => `${c.dir}::${c.label}`;
40
+ function baselinePath(root, commit) {
41
+ const repo = `${basename(root)}-${createHash('sha256').update(root).digest('hex').slice(0, 8)}`;
42
+ return homePath('baselines', repo, `${commit}.json`);
43
+ }
44
+ async function runChecks(checks, dir, opts, exec) {
45
+ const env = { ...process.env, ...cacheEnv(opts.cacheDir), CI: '1', NO_COLOR: '1', FORCE_COLOR: '0' };
46
+ const out = {};
47
+ const once = (c) => exec(c.argv, join(dir, c.dir), env, opts.timeoutMs, [dir, opts.cacheDir]).catch((err) => ({ code: null, output: String(err), timedOut: false }));
48
+ for (const c of checks) {
49
+ let r = await once(c);
50
+ let flaky = false;
51
+ // A failure gets one retry: passing the second time means flaky (slow tests on a busy Mac), not broken.
52
+ if (r.code !== 0 || r.timedOut) {
53
+ const again = await once(c);
54
+ if (again.code === 0 && !again.timedOut)
55
+ flaky = true;
56
+ r = again.code === 0 && !again.timedOut ? again : r;
57
+ }
58
+ const passed = r.code === 0 && !r.timedOut;
59
+ out[key(c)] = { result: passed ? 'passed' : 'failed', failures: passed ? [] : failingTests(r.output), output: r.timedOut ? `${r.output}\n(timed out)` : r.output, ...(flaky ? { flaky } : {}) };
60
+ }
61
+ return out;
62
+ }
63
+ /** Main's results for these checks at `commit`: from the cache, else run once on a clean copy and cached. */
64
+ async function baseline(checks, opts, exec) {
65
+ const path = baselinePath(opts.root, opts.baseCommit);
66
+ const cached = readJson(path, null);
67
+ const missing = checks.filter((c) => !cached?.results[key(c)]);
68
+ if (cached && !missing.length)
69
+ return cached;
70
+ const dir = homePath('baseline-copy', basename(path, '.json'));
71
+ const git = (args) => execFileSync('git', ['-C', opts.root, ...args], { stdio: 'ignore' });
72
+ try {
73
+ git(['worktree', 'remove', '--force', dir]);
74
+ }
75
+ catch { }
76
+ rmSync(dir, { recursive: true, force: true });
77
+ git(['worktree', 'add', '--detach', '--quiet', dir, opts.baseCommit]);
78
+ try {
79
+ setupDependencies(opts.root, dir, basename(path, '.json'), { env: cacheEnv(opts.cacheDir) });
80
+ const ran = await runChecks(missing, dir, opts, exec);
81
+ const results = { ...(cached?.results ?? {}) };
82
+ for (const [k, v] of Object.entries(ran))
83
+ results[k] = { result: v.result, failures: v.failures };
84
+ const b = { commit: opts.baseCommit, at: (opts.now ?? (() => new Date()))().toISOString(), results };
85
+ writeJson(path, b);
86
+ return b;
87
+ }
88
+ finally {
89
+ try {
90
+ git(['worktree', 'remove', '--force', dir]);
91
+ }
92
+ catch { }
93
+ rmSync(dir, { recursive: true, force: true });
94
+ }
95
+ }
96
+ /** Whether the check's output named its failing tests (so the comparison was test by test). */
97
+ function failingTestsKnown(o) {
98
+ return Boolean(o.tail && failingTests(o.tail).length);
99
+ }
100
+ /** Run the repo's checks on the card and on its main; report only what the card made worse. Never throws. */
101
+ export async function verifyCard(opts) {
102
+ const at = (opts.now ?? (() => new Date()))().toISOString();
103
+ const exec = opts.exec ?? ((argv, cwd, env, t, writable) => runCmd(['/usr/bin/sandbox-exec', '-p', sandboxProfile({ writable, denyRead: opts.denyRead }), ...argv], cwd, env, t));
104
+ if (!opts.exec && (process.platform !== 'darwin' || !existsSync('/usr/bin/sandbox-exec'))) {
105
+ return { result: 'not run', why: 'needs the macOS sandbox (sandbox-exec) to run checks safely', at };
106
+ }
107
+ const checks = detectChecks(opts.dir, opts.cacheDir);
108
+ if (!checks.length)
109
+ return { result: 'not run', why: 'no checks found in the repo (tests, typecheck or build)', at };
110
+ try {
111
+ const onCard = await runChecks(checks, opts.dir, opts, exec);
112
+ const failedOnCard = checks.filter((c) => onCard[key(c)].result === 'failed');
113
+ // Only run main when something failed on the card: a clean card needs no comparison.
114
+ const main = failedOnCard.length ? await baseline(failedOnCard, opts, exec) : null;
115
+ const outcomes = checks.map((c) => {
116
+ const mine = onCard[key(c)];
117
+ const theirs = main?.results[key(c)];
118
+ if (mine.result === 'passed')
119
+ return { label: c.label, dir: c.dir, card: 'passed', main: theirs?.result ?? 'unknown', newFailures: [], verdict: 'ok', ...(mine.flaky ? { flaky: true } : {}) };
120
+ if (!theirs || theirs.result === 'passed') {
121
+ return { label: c.label, dir: c.dir, card: 'failed', main: theirs?.result ?? 'unknown', newFailures: mine.failures, verdict: 'broke', tail: tail(mine.output) };
122
+ }
123
+ const known = new Set(theirs.failures);
124
+ const fresh = mine.failures.filter((f) => !known.has(f));
125
+ // Both fail. New failing tests on the card → the card broke them; otherwise main fails the same way.
126
+ const broke = fresh.length > 0;
127
+ return { label: c.label, dir: c.dir, card: 'failed', main: 'failed', newFailures: fresh, verdict: broke ? 'broke' : 'same-as-main', tail: tail(mine.output) };
128
+ });
129
+ const broke = outcomes.filter((o) => o.verdict === 'broke');
130
+ const same = outcomes.filter((o) => o.verdict === 'same-as-main');
131
+ const names = (o) => `${o.dir ? `${o.dir}: ` : ''}${o.label.split(' --')[0]}`;
132
+ if (broke.length) {
133
+ const detail = broke.map((o) => `${names(o)}${o.newFailures.length ? ` (${o.newFailures.slice(0, 3).join('; ')}${o.newFailures.length > 3 ? ` and ${o.newFailures.length - 3} more` : ''})` : ''}`).join(', ');
134
+ return { result: 'failed', command: broke.map(names).join(', '), why: `this change broke ${detail}; it passes on main`, at, tail: broke[0].tail, outcomes };
135
+ }
136
+ const okList = outcomes.filter((o) => o.verdict === 'ok').map((o) => `${names(o)}${o.flaky ? ' (flaky: failed once, passed on retry)' : ''}`);
137
+ const unnamed = same.some((o) => !o.newFailures.length && !failingTestsKnown(o));
138
+ const why = same.length
139
+ ? `${okList.length ? `${okList.join(', ')} pass` : 'nothing new fails'}; ${same.map(names).join(', ')} fail${same.length === 1 ? 's' : ''} the same way on main, so not because of this change${unnamed ? " (its output doesn't name tests, so this compares pass/fail only)" : ''}`
140
+ : `${okList.join(', ')} pass`;
141
+ return { result: 'passed', command: outcomes.map(names).join(', '), why, at, outcomes };
142
+ }
143
+ catch (err) {
144
+ return { result: 'not run', why: `couldn't run the checks: ${err instanceof Error ? err.message : err}`, at };
145
+ }
146
+ }
package/dist/workspace.js CHANGED
@@ -1,10 +1,55 @@
1
1
  // Where a card runs (spec §5.5): its own git worktree on chompyy/<id>, or a draft folder.
2
2
  import { execFileSync } from 'node:child_process';
3
- import { existsSync, mkdirSync } from 'node:fs';
3
+ import { createHash } from 'node:crypto';
4
+ import { existsSync, lstatSync, mkdirSync, readdirSync, readFileSync, realpathSync, rmSync, writeFileSync } from 'node:fs';
5
+ import { basename, dirname, join, resolve } from 'node:path';
6
+ import { setupDependencies } from './deps.js';
4
7
  import { homePath } from './home.js';
5
8
  function git(cwd, args) {
6
9
  return execFileSync('git', ['-C', cwd, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim();
7
10
  }
11
+ const tryGit = (cwd, args) => {
12
+ try {
13
+ return git(cwd, args);
14
+ }
15
+ catch {
16
+ return null;
17
+ }
18
+ };
19
+ /**
20
+ * The latest main, as interactive Claude would see it: fetch the remote (Chompyy, outside the box, may use the
21
+ * network) and use its default branch; with no remote, the local main/master; failing that, HEAD.
22
+ */
23
+ export function latestMain(root, fetch = true) {
24
+ let note;
25
+ const hasOrigin = (tryGit(root, ['remote']) ?? '').split('\n').includes('origin');
26
+ if (hasOrigin && fetch && tryGit(root, ['fetch', '--quiet', 'origin']) === null)
27
+ note = "couldn't fetch origin; used what's already here";
28
+ const candidates = hasOrigin
29
+ ? [tryGit(root, ['symbolic-ref', '--quiet', '--short', 'refs/remotes/origin/HEAD']), 'origin/main', 'origin/master', 'main', 'master']
30
+ : ['main', 'master'];
31
+ for (const ref of candidates) {
32
+ if (!ref)
33
+ continue;
34
+ const commit = tryGit(root, ['rev-parse', '--verify', '--quiet', `${ref}^{commit}`]);
35
+ if (!commit)
36
+ continue;
37
+ // Kept cards land on your local branch and may not be pushed yet: when it is ahead of the remote's, start
38
+ // from it, or the next card starts without them and clashes with them (found by the lab night, 2026-11-20).
39
+ const local = ref.startsWith('origin/') ? ref.slice('origin/'.length) : null;
40
+ const localCommit = local ? tryGit(root, ['rev-parse', '--verify', '--quiet', `refs/heads/${local}^{commit}`]) : null;
41
+ if (local && localCommit && localCommit !== commit) {
42
+ const isAncestor = (a, b) => tryGit(root, ['merge-base', '--is-ancestor', a, b]) !== null;
43
+ if (isAncestor(commit, localCommit))
44
+ return { ref: local, commit: localCommit, ...(note ? { note } : {}) };
45
+ if (!isAncestor(localCommit, commit)) {
46
+ return { ref: local, commit: localCommit, note: `your ${local} and ${ref} have each moved on; used your ${local} (it has your kept cards)${note ? `; ${note}` : ''}` };
47
+ }
48
+ }
49
+ return { ref, commit, ...(note ? { note } : {}) };
50
+ }
51
+ return { ref: 'HEAD', commit: git(root, ['rev-parse', 'HEAD']), note: note ?? 'no main branch found; used HEAD' };
52
+ }
8
53
  export function gitRoot(cwd) {
9
54
  if (!existsSync(cwd))
10
55
  return null;
@@ -15,6 +60,13 @@ export function gitRoot(cwd) {
15
60
  return null;
16
61
  }
17
62
  }
63
+ /** The git branch a folder is on, for a new card's workspace; null outside git or on a detached HEAD. */
64
+ export function branchOf(cwd) {
65
+ if (!existsSync(cwd))
66
+ return null;
67
+ const branch = tryGit(cwd, ['symbolic-ref', '--quiet', '--short', 'HEAD']);
68
+ return branch || null;
69
+ }
18
70
  function branchExists(root, branch) {
19
71
  try {
20
72
  git(root, ['rev-parse', '--verify', '--quiet', `refs/heads/${branch}`]);
@@ -31,7 +83,7 @@ export function planWorkspace(card) {
31
83
  return { kind: 'worktree', dir: homePath('worktrees', card.id), branch: `chompyy/${card.id}` };
32
84
  return { kind: 'draft', dir: homePath('runs', card.id, 'work') };
33
85
  }
34
- export function prepareWorkspace(card) {
86
+ export function prepareWorkspace(card, opts = {}) {
35
87
  const plan = planWorkspace(card);
36
88
  if (plan.kind === 'draft') {
37
89
  mkdirSync(plan.dir, { recursive: true });
@@ -40,41 +92,103 @@ export function prepareWorkspace(card) {
40
92
  const root = gitRoot(card.cwd);
41
93
  const branch = plan.branch;
42
94
  const gitDir = git(root, ['rev-parse', '--path-format=absolute', '--git-common-dir']);
95
+ // A rerun keeps working in the same worktree, from the same base as before.
43
96
  if (existsSync(plan.dir))
44
- return { ...plan, gitDir }; // a rerun keeps working in the same worktree
45
- // New branch from the repo's current HEAD; on a rerun after the folder was removed, reuse the branch.
46
- const args = branchExists(root, branch) ? ['worktree', 'add', plan.dir, branch] : ['worktree', 'add', '-b', branch, plan.dir, 'HEAD'];
97
+ return { ...plan, gitDir, ...(card.run?.base ? { base: card.run.base } : {}) };
98
+ // Same code as prompting Claude directly: a new card starts from the latest main (fetched), not from whatever
99
+ // this folder has checked out. On a rerun after the folder was removed, it reuses its branch.
100
+ const base = latestMain(root, opts.fetch ?? true);
101
+ const local = base.ref.replace(/^origin\//, '');
102
+ const args = branchExists(root, branch) ? ['worktree', 'add', plan.dir, branch] : ['worktree', 'add', '-b', branch, plan.dir, base.commit];
47
103
  git(root, args);
48
- return { ...plan, gitDir };
104
+ const repoKey = `${basename(root)}-${createHash('sha256').update(root).digest('hex').slice(0, 8)}`;
105
+ const setup = setupDependencies(root, plan.dir, repoKey, { env: { npm_config_cache: homePath('cache', 'tools', 'npm') } });
106
+ return { ...plan, gitDir, base: { ref: base.ref, commit: base.commit, branch: local === 'HEAD' ? '' : local }, setup };
49
107
  }
50
108
  /** Files a run may leave that never belong in the user's repo. */
51
109
  export const NEVER_COMMIT = ['QUESTIONS.md', '.claude'];
52
110
  /** OS clutter that appears when you open the card's copy in Finder or Explorer; never committed. */
53
111
  export const JUNK_FILES = ['.DS_Store', 'Thumbs.db', 'desktop.ini'];
54
112
  /**
55
- * Safety net after a run: commit anything the agent left uncommitted in its worktree, so keep merges the
56
- * whole result and undo removes it. Without this, keep would merge nothing and then delete the folder.
57
- * Returns true when it made a commit.
113
+ * The agent can edit any file in its folder, the `.git` link file included. Pointed at a folder it made, git would
114
+ * read that folder's config (hooks, core.fsmonitor, filters) and run it, outside the sandbox, the next time Chompyy
115
+ * runs git there (#24). So after a run, before any git command in the folder, the link goes back to the repo's own
116
+ * record of this worktree (in .git, which the agent can't write). Returns true when it had to repair it.
117
+ */
118
+ export function restoreGitLink(dir, gitDir) {
119
+ const want = realpathSync(dir);
120
+ const records = join(gitDir, 'worktrees');
121
+ const name = existsSync(records)
122
+ ? readdirSync(records).find((n) => {
123
+ try {
124
+ const linked = resolve(gitDir, readFileSync(join(records, n, 'gitdir'), 'utf8').trim());
125
+ return existsSync(dirname(linked)) && realpathSync(dirname(linked)) === want;
126
+ }
127
+ catch {
128
+ return false;
129
+ }
130
+ })
131
+ : undefined;
132
+ if (!name)
133
+ throw new Error(`${gitDir} has no record of the worktree ${dir}`);
134
+ const link = `gitdir: ${join(records, name)}\n`;
135
+ const path = join(dir, '.git');
136
+ const stat = existsSync(path) || isLink(path) ? lstatSync(path) : null;
137
+ if (stat?.isFile() && readFileSync(path, 'utf8') === link)
138
+ return false;
139
+ rmSync(path, { recursive: true, force: true });
140
+ writeFileSync(path, link);
141
+ return true;
142
+ }
143
+ const isLink = (p) => {
144
+ try {
145
+ return lstatSync(p).isSymbolicLink();
146
+ }
147
+ catch {
148
+ return false;
149
+ }
150
+ };
151
+ /**
152
+ * After a run: commit the agent's changes in its worktree (the agent can't write .git, so it never commits
153
+ * itself), so keep merges the whole result and undo removes it. Puts the worktree's .git link back first when
154
+ * the workspace knows its repo. Returns true when it made a commit.
58
155
  */
59
156
  export function commitLeftovers(ws, card) {
60
157
  if (ws.kind !== 'worktree' || !existsSync(ws.dir))
61
158
  return false;
62
- const excludes = [...NEVER_COMMIT.map((p) => `:(exclude)${p}`), ...JUNK_FILES.map((f) => `:(exclude,glob)**/${f}`)];
63
- git(ws.dir, ['add', '-A', '--', '.', ...excludes]);
159
+ if (ws.gitDir)
160
+ restoreGitLink(ws.dir, ws.gitDir);
161
+ // Add exactly the changed files we want, by name. Naming excluded paths instead (":(exclude).claude") makes git
162
+ // fail outright when the repo also gitignores them (Keep broke this way on 2026-11-18).
163
+ const files = changedPaths(ws.dir).filter((f) => !neverCommit(f));
164
+ for (let i = 0; i < files.length; i += 200)
165
+ git(ws.dir, ['add', '-A', '--', ...files.slice(i, i + 200)]);
64
166
  const staged = git(ws.dir, ['diff', '--cached', '--name-only']);
65
167
  if (!staged)
66
168
  return false;
67
- git(ws.dir, ['-c', 'user.name=Chompyy', '-c', 'user.email=chompyy@localhost', 'commit', '--no-verify', '-m', `Chompyy card #${card.id}: ${card.title}\n\nCommitted by Chompyy: the agent left these changes uncommitted.`]);
169
+ git(ws.dir, ['-c', 'user.name=Chompyy', '-c', 'user.email=chompyy@localhost', 'commit', '--no-verify', '-m', `Chompyy card #${card.id}: ${card.title}\n\nMade by an away run; committed by Chompyy.`]);
68
170
  return true;
69
171
  }
172
+ /** Files that never belong in your repo: QUESTIONS.md, .claude/, and OS clutter. */
173
+ function neverCommit(f) {
174
+ return NEVER_COMMIT.some((n) => f === n || f.startsWith(`${n}/`)) || JUNK_FILES.some((j) => f === j || f.endsWith(`/${j}`));
175
+ }
176
+ /** Every changed or new (not ignored) file in a folder, exact paths (NUL-separated, so spaces and quotes are safe). */
177
+ function changedPaths(dir) {
178
+ const out = execFileSync('git', ['-C', dir, 'status', '--porcelain', '-z', '--untracked-files=all'], { encoding: 'utf8' });
179
+ const parts = out.split('\0').filter(Boolean);
180
+ const paths = [];
181
+ for (let i = 0; i < parts.length; i++) {
182
+ const entry = parts[i];
183
+ paths.push(entry.slice(3));
184
+ if (/^[RC]/.test(entry))
185
+ paths.push(parts[++i]); // a rename lists the old path next
186
+ }
187
+ return paths;
188
+ }
70
189
  /** Uncommitted changes in a worktree that keep would lose (ignores QUESTIONS.md and .claude). */
71
190
  export function uncommittedWork(dir) {
72
191
  if (!existsSync(dir))
73
192
  return [];
74
- return git(dir, ['status', '--porcelain'])
75
- .split('\n')
76
- .filter(Boolean)
77
- .map((l) => l.replace(/^\s*\S{1,2}\s+/, '')) // the helper trims, so the first line may lose its leading space
78
- .filter((f) => !NEVER_COMMIT.some((n) => f === n || f.startsWith(`${n}/`)))
79
- .filter((f) => !JUNK_FILES.some((j) => f === j || f.endsWith(`/${j}`)));
193
+ return [...new Set(changedPaths(dir))].filter((f) => !neverCommit(f));
80
194
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "chompyy",
3
- "version": "0.3.0",
3
+ "version": "0.4.1",
4
4
  "description": "Use Claude Code 5-hour window capacity that would reset unused: park ideas, blueprint them, run approved cards while you're away.",
5
5
  "keywords": [
6
6
  "claude-code",
@@ -40,7 +40,8 @@
40
40
  "typecheck": "tsc -p tsconfig.json --noEmit",
41
41
  "prepare": "npm run build",
42
42
  "prepack": "npm run build && cp ../LICENSE ../THIRD_PARTY_NOTICES.md .",
43
- "postpack": "rm -f LICENSE THIRD_PARTY_NOTICES.md"
43
+ "postpack": "rm -f LICENSE THIRD_PARTY_NOTICES.md",
44
+ "lab": "npm run build && vitest run -c vitest.lab.config.ts"
44
45
  },
45
46
  "devDependencies": {
46
47
  "@types/node": "^20.19.43",