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.
@@ -0,0 +1,260 @@
1
+ import { execFile } from 'node:child_process';
2
+ import { chmodSync, closeSync, constants, fstatSync, fsyncSync, lstatSync, mkdirSync, openSync, readFileSync, renameSync, unlinkSync, writeFileSync, } from 'node:fs';
3
+ import { chmod, lstat, mkdir, open, rename, unlink } from 'node:fs/promises';
4
+ import path from 'node:path';
5
+ import { promisify } from 'node:util';
6
+ const NOFOLLOW = constants.O_NOFOLLOW ?? 0;
7
+ const execFileAsync = promisify(execFile);
8
+ // The macOS keychain prompt (first read of an item `security` is not yet trusted
9
+ // for) blocks until the user answers. Give them time to click Allow before we
10
+ // give up — the old 10s kill fired while the dialog was still open and got
11
+ // misread as "disconnected".
12
+ const KEYCHAIN_TIMEOUT_MS = 90_000;
13
+ // `security -w` hex-encodes password data it can't hand back as a clean C-string
14
+ // (Claude Code line-wraps its JSON blob, which triggers this). Real credential
15
+ // JSON always contains non-hex characters like '{' and '"', so an all-hex,
16
+ // even-length payload is unambiguously a hex dump we must decode.
17
+ function decodeKeychainValue(raw) {
18
+ const trimmed = raw.trim();
19
+ if (trimmed.length >= 2 && trimmed.length % 2 === 0 && /^[0-9a-fA-F]+$/.test(trimmed)) {
20
+ return Buffer.from(trimmed, 'hex').toString('utf8');
21
+ }
22
+ return raw;
23
+ }
24
+ // exit 44 / "could not be found" is a genuine miss. A Deny (exit 128, "User
25
+ // canceled") and our own timer firing while the dialog waited are the user's
26
+ // answer to a prompt. Anything else (interaction not allowed, I/O, a kill or
27
+ // crash we did not cause) means access wasn't granted, but showed no prompt,
28
+ // so the next candidate is tried.
29
+ function classifyKeychainError(error, timedOut) {
30
+ if (timedOut)
31
+ return 'unanswered';
32
+ const err = error;
33
+ const code = typeof err.code === 'number' || typeof err.code === 'string' ? Number(err.code) : undefined;
34
+ const text = `${err.stderr ?? ''} ${err.message ?? ''}`.toLowerCase();
35
+ if (code === 44 || text.includes('could not be found') || text.includes('specified item could not be found')) {
36
+ return 'notFound';
37
+ }
38
+ if (code === 128 || text.includes('user canceled'))
39
+ return 'denied';
40
+ return 'other';
41
+ }
42
+ // Items (service plus account) the user refused since the last user-initiated
43
+ // refresh, which clears them: one prompt per item per action, never persisted.
44
+ const refusedThisRun = new Map();
45
+ export function forgetKeychainRefusals() {
46
+ refusedThisRun.clear();
47
+ }
48
+ /**
49
+ * Reads a generic-password keychain item via the Apple-signed `/usr/bin/security`
50
+ * (which the item's `apple-tool:` partition trusts, avoiding the partition-list
51
+ * prompt on already-consented items). Tries each account candidate in order
52
+ * (`null` = service-only) and stops at a Deny or an unanswered prompt: a later
53
+ * candidate can match the same item, and asking again is a second prompt the
54
+ * user already answered. A refused item is skipped (with the service-only
55
+ * lookup) until {@link forgetKeychainRefusals}. Never returns or logs the
56
+ * secret to any caller but the direct one.
57
+ */
58
+ export async function readKeychainPassword(service, accounts = [null], exec = execFileAsync) {
59
+ if (process.platform !== 'darwin')
60
+ return { status: 'notFound' };
61
+ let denied = false;
62
+ let refusal;
63
+ for (const account of accounts) {
64
+ const item = JSON.stringify([service, account]);
65
+ const remembered = refusedThisRun.get(item);
66
+ if (remembered) {
67
+ refusal = remembered;
68
+ continue;
69
+ }
70
+ const args = ['find-generic-password', '-s', service, ...(account ? ['-a', account] : []), '-w'];
71
+ const controller = new AbortController();
72
+ let timedOut = false;
73
+ const timer = setTimeout(() => { timedOut = true; controller.abort(); }, KEYCHAIN_TIMEOUT_MS);
74
+ try {
75
+ const { stdout } = await exec('/usr/bin/security', args, { signal: controller.signal, maxBuffer: 64 * 1024 });
76
+ if (stdout && stdout.trim())
77
+ return { status: 'found', value: decodeKeychainValue(stdout) };
78
+ }
79
+ catch (error) {
80
+ const kind = classifyKeychainError(error, timedOut);
81
+ if (kind === 'denied' || kind === 'unanswered') {
82
+ refusedThisRun.set(item, kind);
83
+ // A later service-only lookup can match the refused item and ask again.
84
+ refusedThisRun.set(JSON.stringify([service, null]), kind);
85
+ return { status: 'accessDenied', reason: kind };
86
+ }
87
+ if (kind === 'other')
88
+ denied = true;
89
+ }
90
+ finally {
91
+ clearTimeout(timer);
92
+ }
93
+ }
94
+ if (refusal)
95
+ return { status: 'accessDenied', reason: refusal };
96
+ return denied ? { status: 'accessDenied' } : { status: 'notFound' };
97
+ }
98
+ export function sanitizeError(error) {
99
+ const raw = error instanceof Error ? error.message : String(error);
100
+ return raw
101
+ .replace(/\0/g, '')
102
+ .replace(/Bearer\s+[^\s,;"']+/gi, '[REDACTED]')
103
+ .replace(/sk-ant-[A-Za-z0-9_-]+/gi, '[REDACTED]')
104
+ .replace(/sk-[A-Za-z0-9_-]+/gi, '[REDACTED]')
105
+ // Google (ya29.) and GitHub (gho_/ghu_/ghp_) OAuth token shapes used by
106
+ // the Gemini/Copilot quota providers.
107
+ .replace(/ya29\.[A-Za-z0-9._-]+/g, '[REDACTED]')
108
+ .replace(/gh[opusr]_[A-Za-z0-9_]+/g, '[REDACTED]')
109
+ .replace(/eyJ[A-Za-z0-9._-]+/g, '[REDACTED]')
110
+ .slice(0, 240);
111
+ }
112
+ function assertSafeMode(stats, filePath) {
113
+ if (!stats.isFile())
114
+ throw new Error(`Credential path is not a regular file: ${filePath}`);
115
+ // POSIX mode bits are meaningless for Windows ACLs, where stats.mode would
116
+ // otherwise reject every credential file.
117
+ if (process.platform !== 'win32' && (stats.mode & 0o077) !== 0)
118
+ throw new Error(`Credential file permissions are too broad: ${filePath}`);
119
+ }
120
+ export async function readSecureFile(filePath, maxBytes = 64 * 1024) {
121
+ let before;
122
+ try {
123
+ before = await lstat(filePath);
124
+ }
125
+ catch (error) {
126
+ if (error.code === 'ENOENT')
127
+ return null;
128
+ throw error;
129
+ }
130
+ if (before.isSymbolicLink())
131
+ throw new Error(`Refusing symbolic link: ${filePath}`);
132
+ assertSafeMode(before, filePath);
133
+ if (before.size > maxBytes)
134
+ throw new Error(`Credential file exceeds ${maxBytes} bytes: ${filePath}`);
135
+ const handle = await open(filePath, constants.O_RDONLY | NOFOLLOW);
136
+ try {
137
+ const after = await handle.stat();
138
+ assertSafeMode(after, filePath);
139
+ if (after.dev !== before.dev || after.ino !== before.ino)
140
+ throw new Error(`Credential file changed while opening: ${filePath}`);
141
+ if (after.size > maxBytes)
142
+ throw new Error(`Credential file exceeds ${maxBytes} bytes: ${filePath}`);
143
+ return await handle.readFile({ encoding: 'utf8' });
144
+ }
145
+ finally {
146
+ await handle.close();
147
+ }
148
+ }
149
+ /** Synchronous twin of {@link readSecureFile}, for the rotation path that must
150
+ * not yield to the event loop between reading and writing a credential. */
151
+ export function readSecureFileSync(filePath, maxBytes = 64 * 1024) {
152
+ let before;
153
+ try {
154
+ before = lstatSync(filePath);
155
+ }
156
+ catch (error) {
157
+ if (error.code === 'ENOENT')
158
+ return null;
159
+ throw error;
160
+ }
161
+ if (before.isSymbolicLink())
162
+ throw new Error(`Refusing symbolic link: ${filePath}`);
163
+ assertSafeMode(before, filePath);
164
+ if (before.size > maxBytes)
165
+ throw new Error(`Credential file exceeds ${maxBytes} bytes: ${filePath}`);
166
+ const fd = openSync(filePath, constants.O_RDONLY | NOFOLLOW);
167
+ try {
168
+ const after = fstatSync(fd);
169
+ assertSafeMode(after, filePath);
170
+ if (after.dev !== before.dev || after.ino !== before.ino)
171
+ throw new Error(`Credential file changed while opening: ${filePath}`);
172
+ if (after.size > maxBytes)
173
+ throw new Error(`Credential file exceeds ${maxBytes} bytes: ${filePath}`);
174
+ return readFileSync(fd, { encoding: 'utf8' });
175
+ }
176
+ finally {
177
+ closeSync(fd);
178
+ }
179
+ }
180
+ // Rewrite a credential with exactly the owner-only permissions it already had,
181
+ // so a refreshed token neither widens the file the user chose nor drops a
182
+ // tighter mode like 0o400. Group or world bits (or Windows, where mode bits are
183
+ // not the access control) mean there is nothing safe to copy: use owner rw.
184
+ function privateModeFor(filePath) {
185
+ if (process.platform === 'win32')
186
+ return 0o600;
187
+ try {
188
+ const stats = lstatSync(filePath);
189
+ if (!stats.isFile())
190
+ return 0o600;
191
+ const mode = stats.mode & 0o777;
192
+ return mode !== 0 && (mode & 0o077) === 0 ? mode : 0o600;
193
+ }
194
+ catch {
195
+ return 0o600;
196
+ }
197
+ }
198
+ /**
199
+ * Writes a credential file atomically and synchronously. Synchronous on
200
+ * purpose: a caller holding a freshly rotated token has to get it onto disk
201
+ * without an await for an abort, a timeout or a quit to land in.
202
+ */
203
+ export function atomicWriteSecureFileSync(filePath, contents) {
204
+ const mode = privateModeFor(filePath);
205
+ const dir = path.dirname(filePath);
206
+ mkdirSync(dir, { recursive: true, mode: 0o700 });
207
+ const tempPath = path.join(dir, `.${path.basename(filePath)}.${process.pid}.${Date.now()}.tmp`);
208
+ try {
209
+ const fd = openSync(tempPath, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL, mode);
210
+ try {
211
+ writeFileSync(fd, contents, 'utf8');
212
+ fsyncSync(fd);
213
+ }
214
+ finally {
215
+ closeSync(fd);
216
+ }
217
+ if (process.platform !== 'win32')
218
+ chmodSync(tempPath, mode);
219
+ renameSync(tempPath, filePath);
220
+ }
221
+ catch (error) {
222
+ try {
223
+ unlinkSync(tempPath);
224
+ }
225
+ catch { /* nothing to clean up */ }
226
+ throw error;
227
+ }
228
+ }
229
+ export async function atomicWriteSecureFile(filePath, contents) {
230
+ await mkdir(path.dirname(filePath), { recursive: true, mode: 0o700 });
231
+ const tempPath = path.join(path.dirname(filePath), `.${path.basename(filePath)}.${process.pid}.${Date.now()}.tmp`);
232
+ const handle = await open(tempPath, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL, 0o600);
233
+ try {
234
+ await handle.writeFile(contents, 'utf8');
235
+ await handle.sync();
236
+ }
237
+ catch (error) {
238
+ await handle.close();
239
+ await unlink(tempPath).catch(() => undefined);
240
+ throw error;
241
+ }
242
+ await handle.close();
243
+ await chmod(tempPath, 0o600);
244
+ try {
245
+ await rename(tempPath, filePath);
246
+ }
247
+ catch (error) {
248
+ await unlink(tempPath).catch(() => undefined);
249
+ throw error;
250
+ }
251
+ }
252
+ export function quotaRequestSignal(parent) {
253
+ const timeout = AbortSignal.timeout(30_000);
254
+ return parent ? AbortSignal.any([parent, timeout]) : timeout;
255
+ }
256
+ export function fraction(value) {
257
+ if (typeof value !== 'number' || !Number.isFinite(value))
258
+ return null;
259
+ return Math.min(1, Math.max(0, value / 100));
260
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,80 @@
1
+ // Where a card runs (spec §5.5): its own git worktree on chompyy/<id>, or a draft folder.
2
+ import { execFileSync } from 'node:child_process';
3
+ import { existsSync, mkdirSync } from 'node:fs';
4
+ import { homePath } from './home.js';
5
+ function git(cwd, args) {
6
+ return execFileSync('git', ['-C', cwd, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim();
7
+ }
8
+ export function gitRoot(cwd) {
9
+ if (!existsSync(cwd))
10
+ return null;
11
+ try {
12
+ return git(cwd, ['rev-parse', '--show-toplevel']);
13
+ }
14
+ catch {
15
+ return null;
16
+ }
17
+ }
18
+ function branchExists(root, branch) {
19
+ try {
20
+ git(root, ['rev-parse', '--verify', '--quiet', `refs/heads/${branch}`]);
21
+ return true;
22
+ }
23
+ catch {
24
+ return false;
25
+ }
26
+ }
27
+ /** What prepareWorkspace would do, without touching anything (for --dry-run). */
28
+ export function planWorkspace(card) {
29
+ const root = gitRoot(card.cwd);
30
+ if (root)
31
+ return { kind: 'worktree', dir: homePath('worktrees', card.id), branch: `chompyy/${card.id}` };
32
+ return { kind: 'draft', dir: homePath('runs', card.id, 'work') };
33
+ }
34
+ export function prepareWorkspace(card) {
35
+ const plan = planWorkspace(card);
36
+ if (plan.kind === 'draft') {
37
+ mkdirSync(plan.dir, { recursive: true });
38
+ return plan;
39
+ }
40
+ const root = gitRoot(card.cwd);
41
+ const branch = plan.branch;
42
+ const gitDir = git(root, ['rev-parse', '--path-format=absolute', '--git-common-dir']);
43
+ 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'];
47
+ git(root, args);
48
+ return { ...plan, gitDir };
49
+ }
50
+ /** Files a run may leave that never belong in the user's repo. */
51
+ export const NEVER_COMMIT = ['QUESTIONS.md', '.claude'];
52
+ /** OS clutter that appears when you open the card's copy in Finder or Explorer; never committed. */
53
+ export const JUNK_FILES = ['.DS_Store', 'Thumbs.db', 'desktop.ini'];
54
+ /**
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.
58
+ */
59
+ export function commitLeftovers(ws, card) {
60
+ if (ws.kind !== 'worktree' || !existsSync(ws.dir))
61
+ 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]);
64
+ const staged = git(ws.dir, ['diff', '--cached', '--name-only']);
65
+ if (!staged)
66
+ 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.`]);
68
+ return true;
69
+ }
70
+ /** Uncommitted changes in a worktree that keep would lose (ignores QUESTIONS.md and .claude). */
71
+ export function uncommittedWork(dir) {
72
+ if (!existsSync(dir))
73
+ 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}`)));
80
+ }
package/package.json CHANGED
@@ -1,6 +1,49 @@
1
1
  {
2
2
  "name": "chompyy",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
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
+ "keywords": [
6
+ "claude-code",
7
+ "claude",
8
+ "tokens",
9
+ "quota",
10
+ "agent",
11
+ "kanban"
12
+ ],
13
+ "homepage": "https://github.com/BranchWork-HQ/Chompyy#readme",
14
+ "bugs": {
15
+ "url": "https://github.com/BranchWork-HQ/Chompyy/issues"
16
+ },
17
+ "repository": {
18
+ "type": "git",
19
+ "url": "git+https://github.com/BranchWork-HQ/Chompyy.git",
20
+ "directory": "cli"
21
+ },
22
+ "license": "MIT",
23
+ "type": "module",
24
+ "bin": {
25
+ "chompyy": "dist/cli.js"
26
+ },
27
+ "files": [
28
+ "dist",
29
+ "skills",
30
+ "LICENSE",
31
+ "THIRD_PARTY_NOTICES.md"
32
+ ],
33
+ "engines": {
34
+ "node": ">=20"
35
+ },
36
+ "scripts": {
37
+ "build": "tsc -p tsconfig.json && chmod +x dist/cli.js",
38
+ "test": "vitest run",
39
+ "typecheck": "tsc -p tsconfig.json --noEmit",
40
+ "prepare": "npm run build",
41
+ "prepack": "npm run build && cp ../LICENSE ../THIRD_PARTY_NOTICES.md .",
42
+ "postpack": "rm -f LICENSE THIRD_PARTY_NOTICES.md"
43
+ },
44
+ "devDependencies": {
45
+ "@types/node": "^20.19.43",
46
+ "typescript": "^5.9.3",
47
+ "vitest": "^3.2.7"
48
+ }
49
+ }
@@ -0,0 +1,26 @@
1
+ ---
2
+ name: away
3
+ description: Run approved Chompyy cards headless while the user steps away, using quota that would otherwise reset. Use when the user types /away <duration> or says "I'm stepping out for an hour, run the queue", "run my cards while I'm away".
4
+ ---
5
+
6
+ # /away
7
+
8
+ Start a Chompyy away run for the duration in `$ARGUMENTS` (for example `1h`, `30m`, `1h30m`).
9
+
10
+ 1. If no duration was given, ask for one and stop.
11
+ 2. Show the plan first, without starting anything:
12
+
13
+ ```bash
14
+ chompyy away <duration> --dry-run
15
+ ```
16
+
17
+ If the gate is closed (little left in the 5h window, weekly reserve reached, or no fresh snapshot), report why and stop. Don't pass `--force` unless the user asks for it by name.
18
+ 3. Start the real run in the background so it survives this session, and tell the user where the output goes:
19
+
20
+ ```bash
21
+ nohup chompyy away <duration> > ~/.chompyy/away.log 2>&1 &
22
+ ```
23
+
24
+ 4. Reply in two lines: which cards will run, and that `chompyy report` shows the results when they're back.
25
+
26
+ The run is safe by design: each card works in its own git worktree (branch `chompyy/<id>`) or a draft folder, with no push, merge, PR, sending or posting. Don't change that.
@@ -0,0 +1,18 @@
1
+ ---
2
+ name: eat-tokens
3
+ description: Show how much of the Claude 5-hour window is left and which Chompyy cards fit in it. Use when the user types /eat-tokens or asks "what can I run with what's left?", "how much quota is left?", "anything to use my leftover tokens on?".
4
+ ---
5
+
6
+ # /eat-tokens
7
+
8
+ Answer "what can I run with what's left?" from the Chompyy board. Read only: never send a message just to check quota, and don't start runs unless the user picks cards.
9
+
10
+ 1. Run:
11
+
12
+ ```bash
13
+ chompyy eat-tokens
14
+ ```
15
+
16
+ 2. Read the numbers: % left in the 5h window, time to reset, pace per hour, weekly used. If the snapshot is stale or missing, say so plainly (the window has reset or the status line isn't set up) and stop there: there's no leftover to plan for.
17
+ 3. Suggest which cards fit, in a short table: card, column, why it fits or doesn't. The command lists approved and later cards but doesn't estimate runtime; use the blueprint to judge scope and avoid pretending to know token cost. Prefer approved cards; mention later cards that need a blueprint and approval first. Leave room for the weekly reserve if weekly used is high.
18
+ 4. Offer the next step in one line, for example: `chompyy approve 3 && chompyy away 1h`, or `/away 40m`. Run it only if the user says yes.
@@ -0,0 +1,20 @@
1
+ ---
2
+ name: later
3
+ description: Park an idea on the Chompyy board without switching tasks, so it can run later on leftover quota. Use when the user types /later <idea>, or says "do that later", "park this", "add to later".
4
+ ---
5
+
6
+ # /later
7
+
8
+ Park the idea in the user's arguments as a Chompyy card. Don't start working on it.
9
+
10
+ 1. Take the idea from the arguments: `$ARGUMENTS`. If it's empty, use the idea the user just mentioned in the conversation, written as one self-contained sentence (someone reading it tomorrow, without this chat, must understand it). If there's no idea at all, ask for one and stop.
11
+ 2. Run it from the directory the idea is about (normally the current one), so the card remembers that repo:
12
+
13
+ ```bash
14
+ chompyy later "<idea>"
15
+ ```
16
+
17
+ Quote the idea safely for the shell. The blueprint is drafted in the background with a cheap model.
18
+ 3. Reply in one or two lines: the card number, and that `chompyy show <id>` shows the blueprint and `chompyy approve <id>` queues it for `/away`. Then go back to what the user was doing.
19
+
20
+ If `chompyy` isn't found, say so and point to `cli/README.md` in the Chompyy repo for install.
@@ -0,0 +1,16 @@
1
+ ---
2
+ name: taste
3
+ description: Show the user's Chompyy taste.md, what Chompyy has learned about how they like work done. Use when the user types /taste or asks "what have you learned about me?", "show my taste file".
4
+ ---
5
+
6
+ # /taste
7
+
8
+ 1. Run:
9
+
10
+ ```bash
11
+ chompyy taste
12
+ ```
13
+
14
+ It prints `~/.chompyy/taste.md`, creating a stub with a header the first time.
15
+ 2. Show the content as is. If it's only the stub, say that preferences aren't distilled yet: ratings from `chompyy rate` collect in `~/.chompyy/signals.jsonl` until the distiller exists.
16
+ 3. If the user wants to change something, edit `~/.chompyy/taste.md` directly. The user's edits always win; keep each line short and under a `## <scope>` heading.