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 +21 -0
- package/README.md +179 -2
- package/THIRD_PARTY_NOTICES.md +31 -0
- package/dist/appstate.js +75 -0
- package/dist/away.js +225 -0
- package/dist/blueprint.js +91 -0
- package/dist/board.js +156 -0
- package/dist/cli.js +479 -0
- package/dist/config.js +54 -0
- package/dist/duration.js +36 -0
- package/dist/gate.js +40 -0
- package/dist/home.js +34 -0
- package/dist/livequota.js +78 -0
- package/dist/macapp.js +57 -0
- package/dist/projects.js +114 -0
- package/dist/quota.js +127 -0
- package/dist/report.js +119 -0
- package/dist/review.js +130 -0
- package/dist/runner.js +97 -0
- package/dist/vendor/codeburn/claude.js +255 -0
- package/dist/vendor/codeburn/security.js +260 -0
- package/dist/vendor/codeburn/types.js +1 -0
- package/dist/workspace.js +80 -0
- package/package.json +47 -4
- package/skills/away/SKILL.md +26 -0
- package/skills/eat-tokens/SKILL.md +18 -0
- package/skills/later/SKILL.md +20 -0
- package/skills/taste/SKILL.md +16 -0
package/dist/duration.js
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
/** Parse "1h", "30m", "1h30m", "45s" or a bare number of minutes into milliseconds. */
|
|
2
|
+
export function parseDuration(text) {
|
|
3
|
+
const s = text.trim().toLowerCase();
|
|
4
|
+
if (/^\d+(\.\d+)?$/.test(s))
|
|
5
|
+
return checked(Number(s) * 60_000, text);
|
|
6
|
+
const re = /(\d+(?:\.\d+)?)\s*(h|m|s)/g;
|
|
7
|
+
let ms = 0;
|
|
8
|
+
let consumed = '';
|
|
9
|
+
for (const m of s.matchAll(re)) {
|
|
10
|
+
const n = Number(m[1]);
|
|
11
|
+
ms += m[2] === 'h' ? n * 3_600_000 : m[2] === 'm' ? n * 60_000 : n * 1000;
|
|
12
|
+
consumed += m[0];
|
|
13
|
+
}
|
|
14
|
+
if (consumed.replace(/\s/g, '') !== s.replace(/\s/g, ''))
|
|
15
|
+
throw new Error(`Can't read duration "${text}". Try 1h, 30m or 1h30m.`);
|
|
16
|
+
return checked(ms, text);
|
|
17
|
+
}
|
|
18
|
+
function checked(ms, text) {
|
|
19
|
+
if (!Number.isFinite(ms) || ms <= 0)
|
|
20
|
+
throw new Error(`Duration must be more than zero: "${text}"`);
|
|
21
|
+
return Math.round(ms);
|
|
22
|
+
}
|
|
23
|
+
/** 6000000 → "1h40m", 2400000 → "40m", 30000 → "<1m". */
|
|
24
|
+
export function formatDuration(ms) {
|
|
25
|
+
if (ms < 60_000)
|
|
26
|
+
return '<1m';
|
|
27
|
+
const totalMin = Math.floor(ms / 60_000);
|
|
28
|
+
const d = Math.floor(totalMin / 1440);
|
|
29
|
+
const h = Math.floor((totalMin % 1440) / 60);
|
|
30
|
+
const m = totalMin % 60;
|
|
31
|
+
if (d > 0)
|
|
32
|
+
return `${d}d${h}h`;
|
|
33
|
+
if (h > 0)
|
|
34
|
+
return m > 0 ? `${h}h${String(m).padStart(2, '0')}m` : `${h}h`;
|
|
35
|
+
return `${m}m`;
|
|
36
|
+
}
|
package/dist/gate.js
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
// Budget gate (spec §5.2): only spend what would otherwise reset; stay on an even weekly pace, hard stop at 90%.
|
|
2
|
+
import { windowView } from './quota.js';
|
|
3
|
+
const WEEK_MS = 7 * 24 * 3600_000;
|
|
4
|
+
/** How far through the 7-day window we are, as a % (an even pace would have used this much). */
|
|
5
|
+
export function weekElapsedPct(msLeft) {
|
|
6
|
+
return Math.min(100, Math.max(0, (1 - msLeft / WEEK_MS) * 100));
|
|
7
|
+
}
|
|
8
|
+
export function budgetGate(snap, cfg, now) {
|
|
9
|
+
const reasons = [];
|
|
10
|
+
const notes = [];
|
|
11
|
+
const five = windowView(snap?.fiveHour, now);
|
|
12
|
+
if (!five.known) {
|
|
13
|
+
// A reset (or no) window means running would *start* a fresh window, which isn't leftover capacity.
|
|
14
|
+
reasons.push(five.reason === 'stale'
|
|
15
|
+
? '5h window unknown: the snapshot is from a window that has reset'
|
|
16
|
+
: '5h window unknown: no quota snapshot (set up `chompyy statusline`)');
|
|
17
|
+
}
|
|
18
|
+
else if (five.leftPct < cfg.min5hLeftPct) {
|
|
19
|
+
reasons.push(`5h window has ${Math.round(five.leftPct)}% left, under the ${cfg.min5hLeftPct}% minimum`);
|
|
20
|
+
}
|
|
21
|
+
const week = windowView(snap?.sevenDay, now);
|
|
22
|
+
const maxWeeklyUsed = 100 - cfg.weeklyReservePct;
|
|
23
|
+
if (!week.known) {
|
|
24
|
+
notes.push('weekly usage unknown; reserve not checked');
|
|
25
|
+
}
|
|
26
|
+
else if (week.usedPct > maxWeeklyUsed) {
|
|
27
|
+
reasons.push(`weekly usage is ${Math.round(week.usedPct)}%, over the ${maxWeeklyUsed}% hard stop`);
|
|
28
|
+
}
|
|
29
|
+
else if (cfg.weeklyPace) {
|
|
30
|
+
// Spend only what you haven't used so far this week; never borrow from the days ahead.
|
|
31
|
+
const pace = weekElapsedPct(week.msLeft);
|
|
32
|
+
if (week.usedPct > pace) {
|
|
33
|
+
reasons.push(`ahead of pace this week: ${Math.round(week.usedPct)}% used, an even pace is ${Math.round(pace)}% by now`);
|
|
34
|
+
}
|
|
35
|
+
else {
|
|
36
|
+
notes.push(`${Math.round(pace - week.usedPct)}% of the week unspent so far (${Math.round(week.usedPct)}% used, even pace ${Math.round(pace)}%)`);
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
return { ok: reasons.length === 0, reasons, notes };
|
|
40
|
+
}
|
package/dist/home.js
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
// All Chompyy state lives in one folder of plain files: ~/.chompyy/ (or $CHOMPYY_HOME).
|
|
2
|
+
import { appendFileSync, existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs';
|
|
3
|
+
import { homedir } from 'node:os';
|
|
4
|
+
import { dirname, join } from 'node:path';
|
|
5
|
+
export function chompyyHome() {
|
|
6
|
+
return process.env.CHOMPYY_HOME || join(homedir(), '.chompyy');
|
|
7
|
+
}
|
|
8
|
+
/** Path inside the Chompyy home. Creates the parent folder. */
|
|
9
|
+
export function homePath(...parts) {
|
|
10
|
+
const path = join(chompyyHome(), ...parts);
|
|
11
|
+
mkdirSync(dirname(path), { recursive: true });
|
|
12
|
+
return path;
|
|
13
|
+
}
|
|
14
|
+
export function readJson(path, fallback) {
|
|
15
|
+
if (!existsSync(path))
|
|
16
|
+
return fallback;
|
|
17
|
+
try {
|
|
18
|
+
return JSON.parse(readFileSync(path, 'utf8'));
|
|
19
|
+
}
|
|
20
|
+
catch {
|
|
21
|
+
return fallback;
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
/** Write via a temp file and rename, so a crash or a parallel reader never sees half a file. */
|
|
25
|
+
export function writeJson(path, data) {
|
|
26
|
+
mkdirSync(dirname(path), { recursive: true });
|
|
27
|
+
const tmp = `${path}.${process.pid}.tmp`;
|
|
28
|
+
writeFileSync(tmp, JSON.stringify(data, null, 2) + '\n');
|
|
29
|
+
renameSync(tmp, path);
|
|
30
|
+
}
|
|
31
|
+
export function appendJsonl(path, record) {
|
|
32
|
+
mkdirSync(dirname(path), { recursive: true });
|
|
33
|
+
appendFileSync(path, JSON.stringify(record) + '\n');
|
|
34
|
+
}
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
// Live Claude quota from Anthropic's usage endpoint, via codeburn's reader (src/vendor/codeburn).
|
|
2
|
+
// Uses the login Claude Code already saved (macOS Keychain or ~/.claude/.credentials.json).
|
|
3
|
+
// It sends no message, so it never starts a 5-hour window. Chosen over the status-line
|
|
4
|
+
// snapshot on 2026-11-15 because it is fresh even when no Claude Code session is open.
|
|
5
|
+
import { fetchClaudeQuota } from './vendor/codeburn/claude.js';
|
|
6
|
+
import { homePath, readJson, writeJson } from './home.js';
|
|
7
|
+
import { loadSnapshot, mergeSnapshot, saveSnapshot } from './quota.js';
|
|
8
|
+
/** Don't ask the endpoint more often than this. */
|
|
9
|
+
export const MIN_INTERVAL_MS = 5 * 60_000;
|
|
10
|
+
const statePath = () => homePath('livequota.json');
|
|
11
|
+
export const loadLiveState = () => readJson(statePath(), {});
|
|
12
|
+
function windowFrom(provider, label) {
|
|
13
|
+
const row = provider.details.find((d) => d.label === label);
|
|
14
|
+
if (!row || !row.resetsAt)
|
|
15
|
+
return undefined;
|
|
16
|
+
return { usedPct: Math.round(row.percent * 1000) / 10, resetsAt: Math.floor(Date.parse(row.resetsAt) / 1000) };
|
|
17
|
+
}
|
|
18
|
+
/** Turn codeburn's provider result into Chompyy's snapshot shape. */
|
|
19
|
+
export function snapshotFromProvider(provider, now) {
|
|
20
|
+
if (provider.connection !== 'connected')
|
|
21
|
+
return null;
|
|
22
|
+
const snap = { capturedAt: now.toISOString(), source: 'api' };
|
|
23
|
+
const five = windowFrom(provider, '5-hour');
|
|
24
|
+
const week = windowFrom(provider, 'Weekly');
|
|
25
|
+
if (five)
|
|
26
|
+
snap.fiveHour = five;
|
|
27
|
+
if (week)
|
|
28
|
+
snap.sevenDay = week;
|
|
29
|
+
return snap;
|
|
30
|
+
}
|
|
31
|
+
/**
|
|
32
|
+
* Refresh the snapshot from the endpoint. `force` skips the 5-minute spacing (not a 429 backoff).
|
|
33
|
+
* `allowKeychain` lets macOS show its one-time "allow access to the Claude Code login?" prompt.
|
|
34
|
+
*/
|
|
35
|
+
export async function refreshLiveQuota(opts = {}) {
|
|
36
|
+
const now = opts.now ?? new Date();
|
|
37
|
+
const state = loadLiveState();
|
|
38
|
+
const current = loadSnapshot();
|
|
39
|
+
if (state.retryAfterAt && Date.parse(state.retryAfterAt) > now.getTime()) {
|
|
40
|
+
return { ok: false, snapshot: current, message: `Anthropic asked us to wait until ${new Date(state.retryAfterAt).toLocaleTimeString()}.` };
|
|
41
|
+
}
|
|
42
|
+
if (!opts.force && state.lastTryAt && now.getTime() - Date.parse(state.lastTryAt) < MIN_INTERVAL_MS && current?.source === 'api') {
|
|
43
|
+
return { ok: true, snapshot: current, message: 'Fresh enough.' };
|
|
44
|
+
}
|
|
45
|
+
const fetchQuota = opts.fetchQuota ?? ((o) => fetchClaudeQuota(o));
|
|
46
|
+
const result = await fetchQuota({ allowKeychain: opts.allowKeychain ?? true });
|
|
47
|
+
const next = {
|
|
48
|
+
lastTryAt: now.toISOString(),
|
|
49
|
+
connection: result.quota.connection,
|
|
50
|
+
plan: result.quota.planLabel,
|
|
51
|
+
};
|
|
52
|
+
if (result.retryAfterSeconds)
|
|
53
|
+
next.retryAfterAt = new Date(now.getTime() + result.retryAfterSeconds * 1000).toISOString();
|
|
54
|
+
const snap = snapshotFromProvider(result.quota, now);
|
|
55
|
+
if (!snap) {
|
|
56
|
+
next.note = result.quota.footerLines.join(' ') || result.quota.connection;
|
|
57
|
+
writeJson(statePath(), next);
|
|
58
|
+
return { ok: false, snapshot: current, message: explain(result.quota) };
|
|
59
|
+
}
|
|
60
|
+
const merged = mergeSnapshot(current, snap);
|
|
61
|
+
saveSnapshot(merged);
|
|
62
|
+
writeJson(statePath(), next);
|
|
63
|
+
return { ok: true, snapshot: merged, message: `Updated from Anthropic${result.quota.planLabel ? ` (${result.quota.planLabel})` : ''}.` };
|
|
64
|
+
}
|
|
65
|
+
function explain(p) {
|
|
66
|
+
const extra = p.footerLines.length ? ` ${p.footerLines.join(' ')}` : '';
|
|
67
|
+
switch (p.connection) {
|
|
68
|
+
case 'accessDenied':
|
|
69
|
+
return `macOS didn't allow reading the Claude Code login.${extra}`;
|
|
70
|
+
case 'keychainUnchecked':
|
|
71
|
+
case 'disconnected':
|
|
72
|
+
return 'No Claude Code login found. Sign in to Claude Code once, then try again.';
|
|
73
|
+
case 'terminalFailure':
|
|
74
|
+
return `Anthropic refused the request.${extra}`;
|
|
75
|
+
default:
|
|
76
|
+
return `Couldn't reach Anthropic right now.${extra}`;
|
|
77
|
+
}
|
|
78
|
+
}
|
package/dist/macapp.js
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
// `chompyy app`: download the Mac app from this version's GitHub Release into ~/Applications and open it.
|
|
2
|
+
// The app is a thin window over this CLI, so the two versions are kept in step.
|
|
3
|
+
import { execFileSync } from 'node:child_process';
|
|
4
|
+
import { existsSync, mkdirSync, mkdtempSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs';
|
|
5
|
+
import { homedir, tmpdir } from 'node:os';
|
|
6
|
+
import { dirname, join } from 'node:path';
|
|
7
|
+
import { fileURLToPath } from 'node:url';
|
|
8
|
+
export const REPO = 'BranchWork-HQ/Chompyy';
|
|
9
|
+
/** The CLI's own version, from its package.json. */
|
|
10
|
+
export function cliVersion() {
|
|
11
|
+
const pkg = join(dirname(fileURLToPath(import.meta.url)), '..', 'package.json');
|
|
12
|
+
return JSON.parse(readFileSync(pkg, 'utf8')).version;
|
|
13
|
+
}
|
|
14
|
+
export function appZipUrl(version) {
|
|
15
|
+
return `https://github.com/${REPO}/releases/download/v${version}/Chompyy-${version}.zip`;
|
|
16
|
+
}
|
|
17
|
+
const defaultDeps = () => ({
|
|
18
|
+
fetch: (url) => fetch(url),
|
|
19
|
+
exec: (cmd, args) => {
|
|
20
|
+
execFileSync(cmd, args, { stdio: 'ignore' });
|
|
21
|
+
},
|
|
22
|
+
platform: process.platform,
|
|
23
|
+
appsDir: join(homedir(), 'Applications'),
|
|
24
|
+
});
|
|
25
|
+
/** Install (or update) Chompyy.app. Returns where it went. */
|
|
26
|
+
export async function installApp(opts = {}, deps = defaultDeps()) {
|
|
27
|
+
if (deps.platform !== 'darwin')
|
|
28
|
+
throw new Error('The Chompyy app is macOS only for now. The CLI works everywhere: `chompyy help`.');
|
|
29
|
+
const version = opts.version ?? cliVersion();
|
|
30
|
+
const url = appZipUrl(version);
|
|
31
|
+
const res = await deps.fetch(url);
|
|
32
|
+
if (!res.ok)
|
|
33
|
+
throw new Error(`Couldn't download the app (HTTP ${res.status}) from ${url}`);
|
|
34
|
+
const tmp = mkdtempSync(join(tmpdir(), 'chompyy-app-'));
|
|
35
|
+
try {
|
|
36
|
+
const zip = join(tmp, 'Chompyy.zip');
|
|
37
|
+
writeFileSync(zip, Buffer.from(await res.arrayBuffer()));
|
|
38
|
+
deps.exec('ditto', ['-x', '-k', zip, tmp]);
|
|
39
|
+
const unpacked = join(tmp, 'Chompyy.app');
|
|
40
|
+
if (!existsSync(unpacked))
|
|
41
|
+
throw new Error('The download had no Chompyy.app in it.');
|
|
42
|
+
mkdirSync(deps.appsDir, { recursive: true });
|
|
43
|
+
const target = join(deps.appsDir, 'Chompyy.app');
|
|
44
|
+
try {
|
|
45
|
+
deps.exec('pkill', ['-x', 'Chompyy']); // an older copy may be running
|
|
46
|
+
}
|
|
47
|
+
catch { }
|
|
48
|
+
rmSync(target, { recursive: true, force: true });
|
|
49
|
+
renameSync(unpacked, target);
|
|
50
|
+
if (opts.open !== false)
|
|
51
|
+
deps.exec('open', [target]);
|
|
52
|
+
return target;
|
|
53
|
+
}
|
|
54
|
+
finally {
|
|
55
|
+
rmSync(tmp, { recursive: true, force: true });
|
|
56
|
+
}
|
|
57
|
+
}
|
package/dist/projects.js
ADDED
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
// Recent projects, so you can pick where a card runs from a list instead of a folder dialog.
|
|
2
|
+
// Reads only the working folder ("cwd") from your Claude Code transcripts, locally, plus folders of past cards.
|
|
3
|
+
import { closeSync, existsSync, openSync, readSync, readdirSync, realpathSync, statSync } from 'node:fs';
|
|
4
|
+
import { homedir } from 'node:os';
|
|
5
|
+
import { basename, dirname, join } from 'node:path';
|
|
6
|
+
/** Walk up to the folder holding .git, without starting git (fast enough for hundreds of folders). */
|
|
7
|
+
function findGitRoot(dir) {
|
|
8
|
+
let d = dir;
|
|
9
|
+
for (let i = 0; i < 30; i++) {
|
|
10
|
+
if (existsSync(join(d, '.git')))
|
|
11
|
+
return d;
|
|
12
|
+
const up = dirname(d);
|
|
13
|
+
if (up === d)
|
|
14
|
+
return null;
|
|
15
|
+
d = up;
|
|
16
|
+
}
|
|
17
|
+
return null;
|
|
18
|
+
}
|
|
19
|
+
/** Folders people usually keep code in; scanned two levels deep for git repos. */
|
|
20
|
+
const CODE_FOLDERS = ['orca', 'Desktop', 'Developer', 'code', 'Code', 'projects', 'Projects', 'src', 'dev', 'repos', 'GitHub', 'Documents/GitHub'];
|
|
21
|
+
const isTemp = (p) => /^\/(private\/)?(var|tmp)\//.test(p) || p.includes('/.chompyy/') || p.includes('/node_modules/');
|
|
22
|
+
/** The first "cwd" in the first 64 KB of a transcript. */
|
|
23
|
+
function cwdOf(file) {
|
|
24
|
+
let fd = null;
|
|
25
|
+
try {
|
|
26
|
+
fd = openSync(file, 'r');
|
|
27
|
+
const buf = Buffer.alloc(64 * 1024);
|
|
28
|
+
const n = readSync(fd, buf, 0, buf.length, 0);
|
|
29
|
+
const m = buf.subarray(0, n).toString('utf8').match(/"cwd"\s*:\s*"((?:[^"\\]|\\.)*)"/);
|
|
30
|
+
return m ? JSON.parse(`"${m[1]}"`) : null;
|
|
31
|
+
}
|
|
32
|
+
catch {
|
|
33
|
+
return null;
|
|
34
|
+
}
|
|
35
|
+
finally {
|
|
36
|
+
if (fd !== null)
|
|
37
|
+
closeSync(fd);
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
export function recentProjects(board, opts = {}) {
|
|
41
|
+
const claudeDir = opts.claudeDir ?? join(homedir(), '.claude', 'projects');
|
|
42
|
+
const seen = new Map();
|
|
43
|
+
const add = (dir, at) => {
|
|
44
|
+
if (!dir || isTemp(dir) || !existsSync(dir))
|
|
45
|
+
return;
|
|
46
|
+
const root = findGitRoot(dir);
|
|
47
|
+
if (!root || root === homedir() || isTemp(root))
|
|
48
|
+
return; // cards run best in git repos
|
|
49
|
+
let path = root;
|
|
50
|
+
try {
|
|
51
|
+
path = realpathSync.native(root); // one entry per repo even when folder names differ in case (code vs Code)
|
|
52
|
+
}
|
|
53
|
+
catch { }
|
|
54
|
+
const prev = seen.get(path);
|
|
55
|
+
if (prev && Date.parse(prev.lastUsed) >= at)
|
|
56
|
+
return;
|
|
57
|
+
seen.set(path, { path, name: basename(path), lastUsed: new Date(at).toISOString(), isGit: true });
|
|
58
|
+
};
|
|
59
|
+
if (existsSync(claudeDir)) {
|
|
60
|
+
for (const entry of readdirSync(claudeDir, { withFileTypes: true })) {
|
|
61
|
+
if (!entry.isDirectory())
|
|
62
|
+
continue;
|
|
63
|
+
const folder = join(claudeDir, entry.name);
|
|
64
|
+
let newest = null;
|
|
65
|
+
for (const f of readdirSync(folder)) {
|
|
66
|
+
if (!f.endsWith('.jsonl'))
|
|
67
|
+
continue;
|
|
68
|
+
const mtime = statSync(join(folder, f)).mtimeMs;
|
|
69
|
+
if (!newest || mtime > newest.mtime)
|
|
70
|
+
newest = { file: join(folder, f), mtime };
|
|
71
|
+
}
|
|
72
|
+
if (newest) {
|
|
73
|
+
const cwd = cwdOf(newest.file);
|
|
74
|
+
if (cwd)
|
|
75
|
+
add(cwd, newest.mtime);
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
for (const card of board.cards)
|
|
80
|
+
add(card.cwd, Date.parse(card.updatedAt) || 0);
|
|
81
|
+
// Repos you haven't used with Claude Code yet: look in the usual code folders.
|
|
82
|
+
const home = opts.home ?? homedir();
|
|
83
|
+
const scan = (dir, depth) => {
|
|
84
|
+
let entries;
|
|
85
|
+
try {
|
|
86
|
+
entries = readdirSync(dir, { withFileTypes: true });
|
|
87
|
+
}
|
|
88
|
+
catch {
|
|
89
|
+
return;
|
|
90
|
+
}
|
|
91
|
+
for (const e of entries) {
|
|
92
|
+
if (!e.isDirectory() || e.name.startsWith('.') || e.name === 'node_modules')
|
|
93
|
+
continue;
|
|
94
|
+
const sub = join(dir, e.name);
|
|
95
|
+
if (existsSync(join(sub, '.git'))) {
|
|
96
|
+
{
|
|
97
|
+
let at = 0;
|
|
98
|
+
try {
|
|
99
|
+
at = statSync(join(sub, '.git')).mtimeMs;
|
|
100
|
+
}
|
|
101
|
+
catch { }
|
|
102
|
+
add(sub, at);
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
else if (depth > 1)
|
|
106
|
+
scan(sub, depth - 1);
|
|
107
|
+
}
|
|
108
|
+
};
|
|
109
|
+
for (const f of CODE_FOLDERS)
|
|
110
|
+
scan(join(home, f), 3);
|
|
111
|
+
return [...seen.values()]
|
|
112
|
+
.sort((a, b) => b.lastUsed.localeCompare(a.lastUsed))
|
|
113
|
+
.slice(0, opts.limit ?? 20);
|
|
114
|
+
}
|
package/dist/quota.js
ADDED
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
// Quota snapshot (spec §5.1). Read from Claude Code's status line JSON, never by sending a
|
|
2
|
+
// message: if no window is active, the first message would start a new 5-hour window.
|
|
3
|
+
import { formatDuration } from './duration.js';
|
|
4
|
+
import { homePath, readJson, writeJson } from './home.js';
|
|
5
|
+
function num(v) {
|
|
6
|
+
if (typeof v === 'number' && Number.isFinite(v))
|
|
7
|
+
return v;
|
|
8
|
+
if (typeof v === 'string' && v.trim() !== '' && Number.isFinite(Number(v)))
|
|
9
|
+
return Number(v);
|
|
10
|
+
return undefined;
|
|
11
|
+
}
|
|
12
|
+
function readWindow(raw) {
|
|
13
|
+
if (!raw || typeof raw !== 'object')
|
|
14
|
+
return undefined;
|
|
15
|
+
const r = raw;
|
|
16
|
+
const usedPct = num(r.used_percentage);
|
|
17
|
+
let resetsAt = num(r.resets_at);
|
|
18
|
+
if (resetsAt === undefined && typeof r.resets_at === 'string') {
|
|
19
|
+
const t = Date.parse(r.resets_at);
|
|
20
|
+
if (!Number.isNaN(t))
|
|
21
|
+
resetsAt = Math.floor(t / 1000);
|
|
22
|
+
}
|
|
23
|
+
if (usedPct === undefined || resetsAt === undefined)
|
|
24
|
+
return undefined;
|
|
25
|
+
if (resetsAt > 1e12)
|
|
26
|
+
resetsAt = Math.floor(resetsAt / 1000); // tolerate milliseconds
|
|
27
|
+
return { usedPct: Math.min(100, Math.max(0, usedPct)), resetsAt };
|
|
28
|
+
}
|
|
29
|
+
/** Parse the status line JSON. Tolerant: bad or partial input gives a snapshot with fewer windows. */
|
|
30
|
+
export function parseStatusline(input, now) {
|
|
31
|
+
const snap = { capturedAt: now.toISOString() };
|
|
32
|
+
let data;
|
|
33
|
+
try {
|
|
34
|
+
data = JSON.parse(input);
|
|
35
|
+
}
|
|
36
|
+
catch {
|
|
37
|
+
return snap;
|
|
38
|
+
}
|
|
39
|
+
const limits = data?.rate_limits;
|
|
40
|
+
if (!limits || typeof limits !== 'object')
|
|
41
|
+
return snap;
|
|
42
|
+
const fiveHour = readWindow(limits.five_hour);
|
|
43
|
+
const sevenDay = readWindow(limits.seven_day);
|
|
44
|
+
if (fiveHour)
|
|
45
|
+
snap.fiveHour = fiveHour;
|
|
46
|
+
if (sevenDay)
|
|
47
|
+
snap.sevenDay = sevenDay;
|
|
48
|
+
return snap;
|
|
49
|
+
}
|
|
50
|
+
/**
|
|
51
|
+
* Keep windows the new input doesn't carry. Before the first reply of a session the status line
|
|
52
|
+
* has no rate_limits, but the previous snapshot stays true until its resets_at.
|
|
53
|
+
*/
|
|
54
|
+
export function mergeSnapshot(prev, next) {
|
|
55
|
+
return {
|
|
56
|
+
capturedAt: next.capturedAt,
|
|
57
|
+
...(next.source ? { source: next.source } : {}),
|
|
58
|
+
fiveHour: next.fiveHour ?? prev?.fiveHour,
|
|
59
|
+
sevenDay: next.sevenDay ?? prev?.sevenDay,
|
|
60
|
+
};
|
|
61
|
+
}
|
|
62
|
+
/** % left, time left and pace for one window. Past resets_at the window has reset: unknown. */
|
|
63
|
+
export function windowView(w, now) {
|
|
64
|
+
if (!w)
|
|
65
|
+
return { known: false, reason: 'missing' };
|
|
66
|
+
const msLeft = w.resetsAt * 1000 - now.getTime();
|
|
67
|
+
if (msLeft <= 0)
|
|
68
|
+
return { known: false, reason: 'stale', resetsAt: w.resetsAt };
|
|
69
|
+
const leftPct = 100 - w.usedPct;
|
|
70
|
+
const hoursLeft = Math.max(msLeft, 60_000) / 3_600_000;
|
|
71
|
+
return { known: true, usedPct: w.usedPct, leftPct, msLeft, pacePerHour: leftPct / hoursLeft, resetsAt: w.resetsAt };
|
|
72
|
+
}
|
|
73
|
+
const pct = (n) => `${Math.round(n)}%`;
|
|
74
|
+
/** One short line for Claude Code's status bar: "🍪 5h 62% left · 1h40m · ~37%/h | 7d 41% used". */
|
|
75
|
+
export function statusLineText(snap, now) {
|
|
76
|
+
const five = windowView(snap.fiveHour, now);
|
|
77
|
+
const week = windowView(snap.sevenDay, now);
|
|
78
|
+
const fivePart = five.known
|
|
79
|
+
? `5h ${pct(five.leftPct)} left · ${formatDuration(five.msLeft)} · ~${pct(five.pacePerHour)}/h`
|
|
80
|
+
: five.reason === 'stale'
|
|
81
|
+
? '5h reset'
|
|
82
|
+
: '5h ?';
|
|
83
|
+
const weekPart = week.known ? ` | 7d ${pct(week.usedPct)} used` : '';
|
|
84
|
+
return `🍪 ${fivePart}${weekPart}`;
|
|
85
|
+
}
|
|
86
|
+
/** Multi-line `chompyy status` text. */
|
|
87
|
+
export function statusText(snap, now) {
|
|
88
|
+
if (!snap || (!snap.fiveHour && !snap.sevenDay)) {
|
|
89
|
+
return [
|
|
90
|
+
'No quota snapshot yet.',
|
|
91
|
+
'Add `chompyy statusline` as your Claude Code statusLine command (see cli/README.md),',
|
|
92
|
+
'then send one message in any Claude Code session.',
|
|
93
|
+
].join('\n');
|
|
94
|
+
}
|
|
95
|
+
const clock = (unix) => new Date(unix * 1000).toLocaleString('en-US', { weekday: 'short', hour: '2-digit', minute: '2-digit' });
|
|
96
|
+
const lines = [];
|
|
97
|
+
const five = windowView(snap.fiveHour, now);
|
|
98
|
+
if (five.known) {
|
|
99
|
+
lines.push(`5h window ${pct(five.leftPct)} left · resets in ${formatDuration(five.msLeft)} (${clock(five.resetsAt)}) · pace ~${pct(five.pacePerHour)}/h`);
|
|
100
|
+
}
|
|
101
|
+
else if (five.reason === 'stale') {
|
|
102
|
+
lines.push(`5h window unknown: the snapshot's window reset at ${clock(five.resetsAt)}. Open Claude Code to refresh it.`);
|
|
103
|
+
}
|
|
104
|
+
else {
|
|
105
|
+
lines.push('5h window unknown: not in the snapshot (Pro/Max only, and only after the first reply of a session)');
|
|
106
|
+
}
|
|
107
|
+
const week = windowView(snap.sevenDay, now);
|
|
108
|
+
if (week.known) {
|
|
109
|
+
lines.push(`7d window ${pct(week.usedPct)} used · resets in ${formatDuration(week.msLeft)} (${clock(week.resetsAt)})`);
|
|
110
|
+
}
|
|
111
|
+
else {
|
|
112
|
+
lines.push(`7d window unknown${week.reason === 'stale' ? ' (snapshot is from before the weekly reset)' : ''}`);
|
|
113
|
+
}
|
|
114
|
+
const age = now.getTime() - Date.parse(snap.capturedAt);
|
|
115
|
+
const stale = !five.known;
|
|
116
|
+
lines.push(`snapshot taken ${formatDuration(age)} ago${stale ? ' · STALE' : ''}`);
|
|
117
|
+
return lines.join('\n');
|
|
118
|
+
}
|
|
119
|
+
export function snapshotPath() {
|
|
120
|
+
return homePath('quota.json');
|
|
121
|
+
}
|
|
122
|
+
export function loadSnapshot() {
|
|
123
|
+
return readJson(snapshotPath(), null);
|
|
124
|
+
}
|
|
125
|
+
export function saveSnapshot(snap) {
|
|
126
|
+
writeJson(snapshotPath(), snap);
|
|
127
|
+
}
|
package/dist/report.js
ADDED
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
// "While you were away" report and rating (spec §5.7).
|
|
2
|
+
import { existsSync, readFileSync, writeFileSync } from 'node:fs';
|
|
3
|
+
import { getCard } from './board.js';
|
|
4
|
+
import { formatDuration } from './duration.js';
|
|
5
|
+
import { wrap } from './review.js';
|
|
6
|
+
import { appendJsonl, homePath, readJson, writeJson } from './home.js';
|
|
7
|
+
const statePath = () => homePath('state.json');
|
|
8
|
+
export function lastReportAt() {
|
|
9
|
+
return readJson(statePath(), {}).lastReportAt ?? null;
|
|
10
|
+
}
|
|
11
|
+
export function markReported(now) {
|
|
12
|
+
writeJson(statePath(), { ...readJson(statePath(), {}), lastReportAt: now.toISOString() });
|
|
13
|
+
}
|
|
14
|
+
/** Cards whose last run finished after `since` (all runs when null), oldest first. */
|
|
15
|
+
export function cardsSince(board, since) {
|
|
16
|
+
return board.cards
|
|
17
|
+
.filter((c) => c.run && (!since || c.run.finishedAt > since))
|
|
18
|
+
.sort((a, b) => a.run.finishedAt.localeCompare(b.run.finishedAt));
|
|
19
|
+
}
|
|
20
|
+
/** The one thing to do about each run, most urgent first. */
|
|
21
|
+
const ACTION = {
|
|
22
|
+
questions: { icon: '❓', rank: 0, text: 'Answer its question, then keep or undo' },
|
|
23
|
+
failed: { icon: '❌', rank: 1, text: "It didn't finish. Look at what happened, then undo or run it again" },
|
|
24
|
+
error: { icon: '⚠️', rank: 1, text: "It couldn't start. Look at what happened" },
|
|
25
|
+
timeout: { icon: '⏱', rank: 2, text: 'It ran out of time. Check what it got done, then keep or undo' },
|
|
26
|
+
ok: { icon: '✅', rank: 3, text: 'Check the change, then keep or undo' },
|
|
27
|
+
};
|
|
28
|
+
/** Finished, but its own checks didn't pass: say so instead of a plain ✅. */
|
|
29
|
+
const UNCHECKED = {
|
|
30
|
+
failed: { icon: '⚠️', rank: 1, text: 'It finished, but its checks fail. See why before you keep it' },
|
|
31
|
+
notRun: { icon: '🔍', rank: 2, text: "It finished but couldn't check its work. Check it yourself, then keep or undo" },
|
|
32
|
+
};
|
|
33
|
+
/** Once you've kept or undone a card, the only thing left is the rating. */
|
|
34
|
+
const DECIDED = {
|
|
35
|
+
kept: { icon: '📥', rank: 4, text: 'Kept. Rate it so Chompyy learns your taste' },
|
|
36
|
+
undone: { icon: '↩️', rank: 4, text: 'Undone. Rate it so Chompyy learns what missed' },
|
|
37
|
+
};
|
|
38
|
+
function filesLine(files) {
|
|
39
|
+
if (!files.length)
|
|
40
|
+
return 'no files changed';
|
|
41
|
+
const shown = files.slice(0, 3).join(', ');
|
|
42
|
+
return files.length > 3 ? `${shown} +${files.length - 3} more` : shown;
|
|
43
|
+
}
|
|
44
|
+
/** Short and action-first; details come from `show`, `diff`, `keep`, `undo` on request. */
|
|
45
|
+
export function formatReport(cards, since, facts) {
|
|
46
|
+
if (cards.length === 0)
|
|
47
|
+
return since ? 'Nothing new since your last report.' : 'Nothing has run yet.';
|
|
48
|
+
const actionOf = (c) => {
|
|
49
|
+
if (c.outcome)
|
|
50
|
+
return DECIDED[c.outcome];
|
|
51
|
+
if (c.run.status === 'ok' && c.run.checks && c.run.checks.result !== 'passed') {
|
|
52
|
+
return c.run.checks.result === 'failed' ? UNCHECKED.failed : UNCHECKED.notRun;
|
|
53
|
+
}
|
|
54
|
+
return ACTION[c.run.status];
|
|
55
|
+
};
|
|
56
|
+
const rank = (c) => actionOf(c)?.rank ?? 9;
|
|
57
|
+
const sorted = [...cards].sort((a, b) => rank(a) - rank(b));
|
|
58
|
+
const out = [`🍪 While you were away · ${cards.length} card${cards.length === 1 ? '' : 's'}`, ''];
|
|
59
|
+
for (const c of sorted) {
|
|
60
|
+
const decided = c.outcome ? DECIDED[c.outcome] : undefined;
|
|
61
|
+
const action = actionOf(c) ?? { icon: '•', text: 'Take a look' };
|
|
62
|
+
const { files, questions } = decided ? { files: [], questions: [] } : facts(c);
|
|
63
|
+
out.push(`${action.icon} #${c.id} ${c.title}`);
|
|
64
|
+
out.push(` → ${action.text}`);
|
|
65
|
+
if (!decided && action !== ACTION[c.run.status] && c.run.checks?.why)
|
|
66
|
+
wrap(c.run.checks.why, 70).forEach((part, i) => out.push(` ${i === 0 ? '·' : ' '} ${part}`));
|
|
67
|
+
for (const q of questions)
|
|
68
|
+
wrap(q, 70).forEach((part, i) => out.push(` ${i === 0 ? '·' : ' '} ${part}`));
|
|
69
|
+
if (!decided)
|
|
70
|
+
out.push(` changed: ${filesLine(files)} · took ${formatDuration(c.run.durationMs)}`);
|
|
71
|
+
out.push('');
|
|
72
|
+
}
|
|
73
|
+
const top = sorted[0];
|
|
74
|
+
const id = top.id;
|
|
75
|
+
out.push(top.outcome
|
|
76
|
+
? `More on a card: chompyy show ${id} · rate ${id} <1-5>`
|
|
77
|
+
: `More on a card: chompyy show ${id} · diff ${id} · keep ${id} · undo ${id} · rate ${id} <1-5>`);
|
|
78
|
+
return out.join('\n');
|
|
79
|
+
}
|
|
80
|
+
export function rateCard(board, id, score, reason, now, toFive = []) {
|
|
81
|
+
if (!Number.isInteger(score) || score < 1 || score > 5)
|
|
82
|
+
throw new Error('Rating must be a whole number from 1 to 5.');
|
|
83
|
+
const card = getCard(board, id);
|
|
84
|
+
if (card.column !== 'review' && card.column !== 'done') {
|
|
85
|
+
throw new Error(`Card #${card.id} is in ${card.column}; only cards that ran (review or done) can be rated.`);
|
|
86
|
+
}
|
|
87
|
+
const at = now.toISOString();
|
|
88
|
+
card.rating = { score, ...(reason ? { reason } : {}), ...(toFive.length ? { toFive } : {}), at };
|
|
89
|
+
// A card is done once you've kept or undone it. Rating first keeps it in review, so Keep/Undo stay available.
|
|
90
|
+
if (card.outcome)
|
|
91
|
+
card.column = 'done';
|
|
92
|
+
card.updatedAt = at;
|
|
93
|
+
// Raw material for taste distillation (spec §5.8). The distiller is not built yet.
|
|
94
|
+
appendJsonl(homePath('signals.jsonl'), {
|
|
95
|
+
at,
|
|
96
|
+
card: card.id,
|
|
97
|
+
title: card.title,
|
|
98
|
+
rating: score,
|
|
99
|
+
reason: reason ?? null,
|
|
100
|
+
toFive: toFive.length ? toFive : null,
|
|
101
|
+
blueprint: card.blueprint,
|
|
102
|
+
status: card.run?.status ?? null,
|
|
103
|
+
});
|
|
104
|
+
return card;
|
|
105
|
+
}
|
|
106
|
+
export const TASTE_STUB = `# taste.md
|
|
107
|
+
|
|
108
|
+
What Chompyy has learned about how you like work done. Plain text: edit it freely, your edits win.
|
|
109
|
+
Nothing is distilled yet; ratings collect in signals.jsonl until the distiller exists.
|
|
110
|
+
|
|
111
|
+
## Everywhere
|
|
112
|
+
`;
|
|
113
|
+
export function readTaste() {
|
|
114
|
+
const path = homePath('taste.md');
|
|
115
|
+
if (existsSync(path))
|
|
116
|
+
return { path, text: readFileSync(path, 'utf8'), created: false };
|
|
117
|
+
writeFileSync(path, TASTE_STUB);
|
|
118
|
+
return { path, text: TASTE_STUB, created: true };
|
|
119
|
+
}
|