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,208 @@
1
+ const FILE = /\b[\w./-]+\.(?:ts|tsx|js|mjs|swift|py|go|rs|rb|java|kt|md|json|yaml|yml|toml|sql|sh|css|html)\b/g;
2
+ const count = (text, re) => (text.match(re) ?? []).length;
3
+ const RULES = [
4
+ {
5
+ type: 'State machine', ref: 'type-state.md', weight: 1.3,
6
+ phrases: ['status(?:es)?', 'states?', 'transitions?', 'moves? (?:from|to|into|back)', 'lifecycle', 'retr(?:y|ies)', 'cancel(?:led|s)?', 'pending', 'stale', 'expires?', 'resets?', 'becomes?', 'column'],
7
+ min: 2,
8
+ },
9
+ {
10
+ type: 'Architecture delta', ref: 'type-architecture-delta.md', weight: 1.2,
11
+ phrases: ['adds?', 'replaces?', 'removes?', 'renames?', 'moves? .{0,20} (?:to|into) ', 'splits?', 'new (?:module|file|component|service|command)', 'refactor', 'migrat(?:e|ion)'],
12
+ min: 2,
13
+ structure: (t) => {
14
+ const files = new Set(t.match(FILE) ?? []);
15
+ return files.size >= 3 ? [files.size * 0.5, `${files.size} files touched`] : null;
16
+ },
17
+ structureNeedsPhrases: true,
18
+ },
19
+ {
20
+ type: 'Steps', ref: 'type-steps.md',
21
+ phrases: ['first', 'then', 'next', 'finally', 'step \\d', 'after that'],
22
+ min: 2,
23
+ structure: (t) => {
24
+ const n = count(t, /^\s*\d+[.)]\s/gm);
25
+ return n >= 3 ? [n * 0.4, `${n} numbered steps`] : null;
26
+ },
27
+ },
28
+ {
29
+ type: 'Flowchart', ref: 'type-flowchart.md', weight: 1.1,
30
+ phrases: ['if', 'else', 'otherwise', 'unless', 'when .{0,30} (?:fails?|missing|empty)', 'fall ?back', 'refuses?', 'decides?', 'either', 'or else', 'only when', 'in that case'],
31
+ min: 2,
32
+ },
33
+ {
34
+ type: 'Data flow', ref: 'type-data-flow.md',
35
+ phrases: ['inputs?', 'outputs?', 'reads?', 'writes?', 'parses?', 'transforms?', 'computes?', 'derives?', 'pipeline', 'feeds?', 'turns .{0,30} into', '→|->', 'formula', '= .{1,40} ÷'],
36
+ min: 3,
37
+ },
38
+ {
39
+ type: 'Sequence', ref: 'type-sequence.md', weight: 1.2,
40
+ phrases: ['requests?', 'responses?', 'calls?', 'sends?', 'replies', 'api', 'endpoint', 'hooks?', 'client', 'server', 'handshake', 'webhook', 'round[- ]trip'],
41
+ min: 3,
42
+ },
43
+ {
44
+ type: 'Timeline', ref: 'type-timeline.md',
45
+ phrases: ['timeline', 'milestones?', 'deadline', 'by (?:mon|tues|wednes|thurs|fri|satur|sun)day', 'q[1-4]', '\\d{4}-\\d{2}-\\d{2}', 'week \\d', 'phase \\d', 'release'],
46
+ min: 2,
47
+ },
48
+ {
49
+ type: 'Gantt', ref: 'type-gantt.md', weight: 1.2,
50
+ phrases: ['schedule', 'durations?', '\\d+ (?:days?|weeks?|hours?)', 'in parallel', 'overlap', 'blocks? on', 'critical path'],
51
+ min: 3,
52
+ },
53
+ {
54
+ type: 'Bar chart', ref: 'type-bar.md', weight: 1.1,
55
+ phrases: ['benchmarks?', 'compare .{0,20}(?:numbers|results|cost|tokens)', 'per (?:model|tool|project|day)', 'top \\d+', 'ranking', 'measure(?:d|s)?'],
56
+ min: 1,
57
+ structure: (t) => {
58
+ const n = count(t, /\b\d+(?:\.\d+)?\s?%/g);
59
+ return n >= 3 ? [n / 2, `${n} percentages`] : null;
60
+ },
61
+ },
62
+ {
63
+ type: 'Line chart', ref: 'type-line.md', weight: 1.1,
64
+ phrases: ['over time', 'trends?', 'per (?:day|week|month)', 'before and after', 'growth', 'declin(?:e|ing)', 'history of'],
65
+ min: 2,
66
+ },
67
+ {
68
+ type: 'Quadrant', ref: 'type-quadrant.md', weight: 1.2,
69
+ phrases: ['vs\\.?', 'versus', 'trade-?offs?', 'options?', 'compare', 'priorit(?:y|ize|ise)', 'effort', 'impact'],
70
+ min: 3,
71
+ },
72
+ {
73
+ type: 'Tree', ref: 'type-tree.md',
74
+ phrases: ['hierarchy', 'folders?', 'director(?:y|ies)', 'parent', 'children', 'sub-?(?:folder|section|task)s?', 'nested'],
75
+ min: 2,
76
+ },
77
+ {
78
+ type: 'Layer stack', ref: 'type-layers.md',
79
+ phrases: ['layers?', 'stack', 'tiers?', 'levels? of', 'on top of', 'underneath', 'abstraction'],
80
+ min: 2,
81
+ },
82
+ {
83
+ type: 'Swimlane', ref: 'type-swimlane.md', weight: 1.2,
84
+ phrases: ['hand ?offs?', 'you (?:approve|review|answer)', 'the agent', 'the user', 'reviewer', 'owner', 'who does'],
85
+ min: 3,
86
+ },
87
+ {
88
+ type: 'ER / data model', ref: 'type-er.md', weight: 1.2,
89
+ phrases: ['tables?', 'schema', 'fields?', 'entit(?:y|ies)', 'records?', 'foreign key', 'relations?(?:hip)?s?', 'json shape', 'interface \\w+'],
90
+ min: 3,
91
+ },
92
+ {
93
+ type: 'Dependency graph', ref: 'type-dependency.md', weight: 1.2,
94
+ phrases: ['depends on', 'dependenc(?:y|ies)', 'imports?', 'requires', 'cycles?', 'circular'],
95
+ min: 2,
96
+ },
97
+ {
98
+ type: 'Loop', ref: 'type-loop.md', weight: 1.3,
99
+ phrases: ['loop', 'cycle', 'feedback', 'feeds back', 'again and again', 'learns? from', 'closed loop', 'repeat(?:s|ed)?'],
100
+ min: 2,
101
+ },
102
+ {
103
+ type: 'User journey', ref: 'type-journey.md', weight: 1.2,
104
+ phrases: ['user journey', 'experience', 'onboarding', 'first (?:run|time|launch)', 'feels?', 'frustrat', 'delight', 'tester'],
105
+ min: 2,
106
+ },
107
+ {
108
+ type: 'Fishbone', ref: 'type-fishbone.md', weight: 1.3,
109
+ phrases: ['root cause', 'why (?:it|does|did)', 'causes?', 'diagnos', 'investigat', 'bug', 'regression'],
110
+ min: 3,
111
+ },
112
+ {
113
+ type: 'Sankey', ref: 'type-sankey.md', weight: 1.3,
114
+ phrases: ['split(?:s)? into', 'share of', 'breakdown', 'where .{0,20} goes', 'budget', 'allocation', 'flows? into'],
115
+ min: 2,
116
+ },
117
+ {
118
+ type: 'Waterfall', ref: 'type-waterfall.md', weight: 1.3,
119
+ phrases: ['bridge', 'adds up', 'from \\d+.{0,20} to \\d+', 'net (?:change|effect)', 'deltas?'],
120
+ min: 2,
121
+ },
122
+ {
123
+ type: 'Treemap', ref: 'type-treemap.md', weight: 1.2,
124
+ phrases: ['part of (?:the )?whole', 'biggest', 'proportion', 'what .{0,20} is made of', 'sizes?'],
125
+ min: 2,
126
+ },
127
+ {
128
+ type: 'Deployment', ref: 'type-deployment.md', weight: 1.2,
129
+ phrases: ['deploy', 'hosts?', 'containers?', 'launchagent', 'daemon', 'release zip', 'install(?:er|s)?', 'ports?', 'runs on'],
130
+ min: 2,
131
+ },
132
+ {
133
+ type: 'Requirement traceability', ref: 'type-requirement-traceability.md', weight: 1.2,
134
+ phrases: ['requirements?', 'acceptance', 'covered by', 'test(?:s)? for each', 'spec §', 'traceab'],
135
+ min: 2,
136
+ },
137
+ {
138
+ type: 'Unit Grid', ref: 'type-unit-grid.md', weight: 1.2,
139
+ phrases: ['out of 100', 'percent of', 'share left', 'used of', 'window left'],
140
+ min: 2,
141
+ },
142
+ ];
143
+ /** Blueprint sections that say what *not* to do or how it's checked: their words would mislead the signals. */
144
+ const SKIP_SECTION = /^(?:out of scope|won'?t touch|non-?goals|how it'?s checked|checks?|done when|questions)\b/i;
145
+ /** Card text the signals read: title, idea and the blueprint's goal/scope/shape, without code blocks. */
146
+ export function cardText(card) {
147
+ const kept = [];
148
+ let skip = false;
149
+ for (const line of (card.blueprint ?? '').split('\n')) {
150
+ const h = line.match(/^#{1,6}\s+(.*)/);
151
+ if (h)
152
+ skip = SKIP_SECTION.test(h[1].trim());
153
+ else if (!skip)
154
+ kept.push(line);
155
+ }
156
+ return [card.title, card.idea, kept.join('\n')].join('\n').replace(/```[\s\S]*?```/g, ' ');
157
+ }
158
+ /** Rank the visual types for a card, strongest first. Empty when nothing points anywhere. */
159
+ export function suggestTypes(card, max = 3) {
160
+ const text = cardText(card);
161
+ const out = [];
162
+ for (const rule of RULES) {
163
+ const evidence = [];
164
+ let hits = 0;
165
+ for (const p of rule.phrases) {
166
+ const m = text.match(new RegExp(`(?<![\\w])(?:${p})(?![\\w])`, 'gi'));
167
+ if (!m)
168
+ continue;
169
+ hits += m.length;
170
+ evidence.push(`"${m[0].trim().toLowerCase()}"${m.length > 1 ? ` ×${m.length}` : ''}`);
171
+ }
172
+ const distinct = evidence.length;
173
+ let score = distinct >= (rule.min ?? 1) ? distinct + Math.min(hits - distinct, distinct) * 0.25 : 0;
174
+ const s = rule.structureNeedsPhrases && score === 0 ? null : rule.structure?.(text);
175
+ if (s) {
176
+ score += s[0];
177
+ evidence.unshift(s[1]);
178
+ }
179
+ if (score > 0)
180
+ out.push({ type: rule.type, ref: rule.ref, score: Math.round(score * (rule.weight ?? 1) * 10) / 10, evidence: evidence.slice(0, 5) });
181
+ }
182
+ out.sort((a, b) => b.score - a.score);
183
+ return out.slice(0, max);
184
+ }
185
+ /** The suggestion block for the drawing prompt. */
186
+ export function typeHint(suggestions) {
187
+ const tail = 'HTML comment on the line right after <!DOCTYPE html>: <!-- type: <Type>; why: <one short reason> -->';
188
+ if (!suggestions.length) {
189
+ return [
190
+ 'No strong signal. Choose from the full visual-type guide in SKILL.md §3 by what the task produces; a',
191
+ 'flowchart only when there is real branching. If the task writes a document, picture what the document',
192
+ `explains, not its headings. Put an ${tail}`,
193
+ ].join('\n');
194
+ }
195
+ const [top, ...rest] = suggestions;
196
+ const line = (s) => `${s.type} (references/${s.ref}), because the card mentions ${s.evidence.join(', ')}`;
197
+ return [
198
+ `Suggested type: ${line(top)}.`,
199
+ ...(rest.length ? [`Also considered: ${rest.map(line).join('; ')}.`] : []),
200
+ 'Use the suggested type unless the task clearly fits another one in SKILL.md §3. Whichever you pick, put an',
201
+ tail,
202
+ ].join('\n');
203
+ }
204
+ /** The type and reason the drawing agent wrote in its leading comment, if any. */
205
+ export function chosenType(html) {
206
+ const m = html.match(/<!--\s*type:\s*([^;>]+?)\s*;\s*why:\s*([\s\S]*?)\s*-->/i);
207
+ return m ? { type: m[1].trim(), why: m[2].trim() } : null;
208
+ }
@@ -0,0 +1,168 @@
1
+ // Preflight (research/away-readiness.md, steps 1–2): before cards run in a repo, run the repo's own checks on
2
+ // clean latest main, in the same box an away run uses AND outside it. The difference is the verdict:
3
+ // passes in the box → ready
4
+ // fails only in the box → a box problem (the catalog says which, and how to fix it)
5
+ // fails outside the box too → main itself is broken (not the box, and not any card's fault)
6
+ // Outside-the-box runs only ever execute your own code on main, never an agent's change.
7
+ import { execFileSync } from 'node:child_process';
8
+ import { createHash } from 'node:crypto';
9
+ import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync } from 'node:fs';
10
+ import { basename, join, relative } from 'node:path';
11
+ import { cacheEnv } from './away.js';
12
+ import { diagnose } from './catalog.js';
13
+ import { hostsInErrors } from './permissions.js';
14
+ import { homePath, readJson, writeJson } from './home.js';
15
+ import { detectCheck, run, sandboxProfile } from './verify.js';
16
+ import { setupDependencies } from './deps.js';
17
+ import { latestMain } from './workspace.js';
18
+ export { latestMain };
19
+ const SKIP = new Set(['node_modules', '.git', '.build', 'dist', 'build', 'vendor', 'Pods', 'DerivedData', '.venv', 'venv', 'target']);
20
+ /** Every check the repo has, from what's in its folders (up to 3 levels deep). */
21
+ /**
22
+ * `swift build` as it can run in the away box: SwiftPM's own sandbox off (the box already sandboxes it; macOS
23
+ * forbids nesting) and its caches inside the box. Proven by preflight on 2026-11-18.
24
+ */
25
+ export function swiftBuildArgv(cacheDir) {
26
+ return ['swift', 'build', '--disable-sandbox', '--cache-path', `${cacheDir}/swiftpm/cache`, '--config-path', `${cacheDir}/swiftpm/config`, '--security-path', `${cacheDir}/swiftpm/security`];
27
+ }
28
+ export function detectChecks(root, cacheDir, maxDepth = 3) {
29
+ const checks = [];
30
+ const walk = (dir, depth) => {
31
+ const rel = relative(root, dir);
32
+ const test = detectCheck(dir);
33
+ if (test)
34
+ checks.push({ dir: rel, label: test.label, argv: test.argv, kind: 'test' });
35
+ const pkgPath = join(dir, 'package.json');
36
+ if (existsSync(pkgPath)) {
37
+ try {
38
+ const scripts = JSON.parse(readFileSync(pkgPath, 'utf8')).scripts ?? {};
39
+ if (scripts.typecheck)
40
+ checks.push({ dir: rel, label: 'npm run typecheck', argv: ['npm', 'run', 'typecheck'], kind: 'typecheck' });
41
+ }
42
+ catch { }
43
+ }
44
+ if (existsSync(join(dir, 'Package.swift'))) {
45
+ const argv = swiftBuildArgv(cacheDir);
46
+ checks.push({ dir: rel, label: argv.join(' '), argv, kind: 'build' });
47
+ }
48
+ if (depth >= maxDepth)
49
+ return;
50
+ let subdirs = [];
51
+ try {
52
+ subdirs = readdirSync(dir, { withFileTypes: true }).filter((d) => d.isDirectory() && !d.name.startsWith('.') && !SKIP.has(d.name)).map((d) => d.name);
53
+ }
54
+ catch { }
55
+ for (const name of subdirs)
56
+ walk(join(dir, name), depth + 1);
57
+ };
58
+ walk(root, 0);
59
+ return checks;
60
+ }
61
+ const git = (cwd, args) => execFileSync('git', ['-C', cwd, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim();
62
+ const tryGit = (cwd, args) => {
63
+ try {
64
+ return git(cwd, args);
65
+ }
66
+ catch {
67
+ return null;
68
+ }
69
+ };
70
+ /** Where a repo's profile lives: ~/.chompyy/repos/<name>-<hash>.json. */
71
+ export function profilePath(root) {
72
+ const hash = createHash('sha256').update(root).digest('hex').slice(0, 8);
73
+ return homePath('repos', `${basename(root)}-${hash}.json`);
74
+ }
75
+ export const loadProfile = (root) => readJson(profilePath(root), null);
76
+ export const saveProfile = (p) => writeJson(profilePath(p.root), p);
77
+ const clean = (text, lines = 12) => text.replace(/\u001b\[[0-9;]*[A-Za-z]/g, '').trimEnd().split('\n').slice(-lines).join('\n').slice(-1500);
78
+ /** Run the repo's checks on a clean copy of the latest main, in the box and outside it. Never touches your checkout. */
79
+ export async function preflight(root, opts) {
80
+ const now = opts.now ?? (() => new Date());
81
+ const base = opts.ref ? { ref: opts.ref, commit: git(root, ['rev-parse', '--verify', `${opts.ref}^{commit}`]) } : latestMain(root, opts.fetch ?? true);
82
+ const dir = homePath('preflight', basename(profilePath(root), '.json'));
83
+ if (existsSync(dir)) {
84
+ tryGit(root, ['worktree', 'remove', '--force', dir]);
85
+ rmSync(dir, { recursive: true, force: true });
86
+ }
87
+ mkdirSync(opts.cacheDir, { recursive: true });
88
+ git(root, ['worktree', 'add', '--detach', '--quiet', dir, base.commit]);
89
+ const results = [];
90
+ try {
91
+ setupDependencies(root, dir, basename(profilePath(root), '.json'), { env: cacheEnv(opts.cacheDir) });
92
+ const checks = detectChecks(dir, opts.cacheDir);
93
+ const env = { ...process.env, ...cacheEnv(opts.cacheDir), CI: '1', NO_COLOR: '1', FORCE_COLOR: '0' };
94
+ const exec = opts.exec ?? ((argv, cwd, e, t, boxed) => run(boxed ? ['/usr/bin/sandbox-exec', '-p', sandboxProfile({ writable: [dir, opts.cacheDir], denyRead: opts.denyRead }), ...argv] : argv, cwd, e, t));
95
+ const boxAvailable = opts.exec !== undefined || (process.platform === 'darwin' && existsSync('/usr/bin/sandbox-exec'));
96
+ for (const check of checks) {
97
+ const started = Date.now();
98
+ const cwd = join(dir, check.dir);
99
+ if (!boxAvailable) {
100
+ results.push({ check, verdict: 'not-run', why: 'needs the macOS sandbox (sandbox-exec)', ms: 0 });
101
+ continue;
102
+ }
103
+ let inBox;
104
+ try {
105
+ inBox = await exec(check.argv, cwd, env, opts.timeoutMs, true);
106
+ }
107
+ catch (err) {
108
+ results.push({ check, verdict: 'not-run', why: `couldn't start: ${err instanceof Error ? err.message : err}`, ms: Date.now() - started });
109
+ continue;
110
+ }
111
+ if (inBox.code === 0 && !inBox.timedOut) {
112
+ results.push({ check, verdict: 'ready', why: 'passes in the box', ms: Date.now() - started });
113
+ continue;
114
+ }
115
+ // Failed in the box: is it the box, or main itself? Run the same check on the same code outside it.
116
+ const outside = await exec(check.argv, cwd, env, opts.timeoutMs, false).catch((err) => ({ code: null, output: String(err), timedOut: false }));
117
+ const ms = Date.now() - started;
118
+ if (outside.code === 0 && !outside.timedOut) {
119
+ const diagnoses = diagnose(inBox.output).map((d) => ({ id: d.entry.id, title: d.entry.title, cause: d.entry.cause, fix: d.entry.fix, remedy: d.entry.remedy, evidence: d.evidence }));
120
+ results.push({
121
+ check,
122
+ verdict: 'box',
123
+ why: diagnoses.length
124
+ ? `passes outside the box, fails inside: ${diagnoses.map((d) => d.title.toLowerCase()).join('; ')}`
125
+ : "passes outside the box, fails inside, and the cause isn't in the catalog yet",
126
+ diagnoses,
127
+ tail: clean(inBox.output),
128
+ ms,
129
+ });
130
+ }
131
+ else {
132
+ results.push({ check, verdict: 'broken', why: inBox.timedOut && outside.timedOut ? 'times out on main, in and outside the box' : 'fails on main outside the box too: main itself is broken', tail: clean(outside.output), ms });
133
+ }
134
+ }
135
+ }
136
+ finally {
137
+ tryGit(root, ['worktree', 'remove', '--force', dir]);
138
+ rmSync(dir, { recursive: true, force: true });
139
+ }
140
+ return { at: now().toISOString(), root, base, ready: results.length > 0 && results.every((r) => r.verdict === 'ready'), results };
141
+ }
142
+ /** Preflight as you'd read it. */
143
+ export function formatPreflight(p) {
144
+ const mark = { ready: '✓', box: '✗', broken: '!', 'not-run': '·' };
145
+ const lines = [`Preflight for ${basename(p.root)} (${p.base.ref} @ ${p.base.commit.slice(0, 7)})${p.base.note ? `\n note: ${p.base.note}` : ''}`];
146
+ if (!p.results.length)
147
+ lines.push(' No checks found (tests, typecheck or build). Away cards here can\'t be checked.');
148
+ for (const r of p.results) {
149
+ lines.push(` ${mark[r.verdict]} ${r.check.dir || '.'}: ${r.check.label} — ${r.why} (${Math.round(r.ms / 1000)}s)`);
150
+ for (const d of r.diagnoses ?? []) {
151
+ lines.push(` ${d.title}. ${d.cause}`);
152
+ lines.push(` fix (${d.fix}): ${d.remedy}`);
153
+ lines.push(` seen: ${d.evidence}`);
154
+ }
155
+ if (r.verdict !== 'ready' && !r.diagnoses?.length && r.tail)
156
+ lines.push(...r.tail.split('\n').slice(-4).map((l) => ` | ${l}`));
157
+ }
158
+ const box = p.results.filter((r) => r.verdict === 'box').length;
159
+ const broken = p.results.filter((r) => r.verdict === 'broken').length;
160
+ lines.push(p.ready
161
+ ? 'Away-ready: yes. Every check passes in the box, so a card\'s "checks fail" will mean its change.'
162
+ : `Away-ready: no${box ? ` · ${box} check(s) blocked by the box` : ''}${broken ? ` · ${broken} failing on main itself` : ''}.`);
163
+ return lines.join('\n');
164
+ }
165
+ /** Hosts the repo's own checks tried to reach in the box (for the permission plan). */
166
+ export function preflightHosts(p) {
167
+ return [...new Set((p?.preflight?.results ?? []).filter((r) => r.verdict === 'box').flatMap((r) => (r.diagnoses ?? []).filter((d) => d.id === 'network').flatMap((d) => hostsInErrors(d.evidence))))];
168
+ }
@@ -0,0 +1,122 @@
1
+ // The premise (FEATURES §10, §11): how often a 5-hour window resets with capacity left while the weekly limit
2
+ // isn't what stops you. Chompyy's pitch rests on that number, so it's measured from your own quota readings, never
3
+ // assumed.
4
+ //
5
+ // quota-history.json keeps only 8 days, so every window that ends is also written to windows.jsonl, which is
6
+ // kept: one line per window, numbers only.
7
+ import { existsSync, readFileSync, appendFileSync } from 'node:fs';
8
+ import { homePath } from './home.js';
9
+ /** Anthropic's reset times wobble by a second or a minute (14:59:59 vs 15:00:00): the same window. */
10
+ const bucket = (resetsAt) => Math.floor((resetsAt + 300) / 600);
11
+ const key = (e) => `${e.kind}:${bucket(e.resetsAt)}`;
12
+ const EXACT_MS = 15 * 60_000;
13
+ /**
14
+ * Windows that have ended, from the readings. A reading after the reset that still shows the old window means no
15
+ * new window has started yet, so its number is the final one. A window is only returned once its number can't
16
+ * change any more: it is exact, or a newer window of the same kind has started.
17
+ */
18
+ export function windowEnds(samples, nowMs) {
19
+ const groups = new Map();
20
+ for (const s of samples) {
21
+ for (const [kind, w] of [['5h', s.five], ['week', s.week]]) {
22
+ if (!w)
23
+ continue;
24
+ const k = key({ kind, resetsAt: w.resetsAt });
25
+ const g = groups.get(k) ?? { kind, resetsAt: w.resetsAt, list: [] };
26
+ g.resetsAt = Math.max(g.resetsAt, w.resetsAt);
27
+ g.list.push({ at: s.at, usedPct: w.usedPct, ...(kind === '5h' && s.week ? { week: s.week } : {}) });
28
+ groups.set(k, g);
29
+ }
30
+ }
31
+ const latest = { '5h': 0, week: 0 };
32
+ for (const g of groups.values())
33
+ latest[g.kind] = Math.max(latest[g.kind], bucket(g.resetsAt));
34
+ const ends = [];
35
+ for (const g of groups.values()) {
36
+ const resetMs = g.resetsAt * 1000;
37
+ if (resetMs > nowMs)
38
+ continue; // still running
39
+ const list = g.list.sort((a, b) => a.at - b.at);
40
+ const before = list.filter((x) => x.at <= resetMs);
41
+ const after = list.filter((x) => x.at > resetMs);
42
+ const last = before.at(-1) ?? after[0];
43
+ const exact = after.length > 0 || resetMs - last.at <= EXACT_MS;
44
+ if (!exact && bucket(g.resetsAt) === latest[g.kind])
45
+ continue; // could still get a closer reading
46
+ const usedPct = Math.max(...(after.length ? [...before, ...after] : before).map((x) => x.usedPct));
47
+ const week = [...before, ...after].reverse().find((x) => x.week)?.week;
48
+ ends.push({ kind: g.kind, resetsAt: g.resetsAt, usedPct, exact, ...(week ? { weekUsedPct: week.usedPct, weekResetsAt: week.resetsAt } : {}) });
49
+ }
50
+ return ends.sort((a, b) => a.resetsAt - b.resetsAt);
51
+ }
52
+ const logPath = () => homePath('windows.jsonl');
53
+ export function loadWindowLog() {
54
+ if (!existsSync(logPath()))
55
+ return [];
56
+ return readFileSync(logPath(), 'utf8').split('\n').filter(Boolean).flatMap((l) => {
57
+ try {
58
+ return [JSON.parse(l)];
59
+ }
60
+ catch {
61
+ return [];
62
+ }
63
+ });
64
+ }
65
+ /** Write the windows that ended and aren't in windows.jsonl yet. Returns how many were added. */
66
+ export function archiveWindowEnds(samples, nowMs) {
67
+ const known = new Set(loadWindowLog().map(key));
68
+ const fresh = windowEnds(samples, nowMs).filter((e) => !known.has(key(e)));
69
+ if (fresh.length)
70
+ appendFileSync(logPath(), fresh.map((e) => JSON.stringify(e)).join('\n') + '\n');
71
+ return fresh.length;
72
+ }
73
+ /** Everything known: the log plus what the current readings add. */
74
+ export function allWindowEnds(samples, nowMs) {
75
+ const byKey = new Map(loadWindowLog().map((e) => [key(e), e]));
76
+ for (const e of windowEnds(samples, nowMs))
77
+ if (!byKey.has(key(e)) || (e.exact && !byKey.get(key(e)).exact))
78
+ byKey.set(key(e), e);
79
+ return [...byKey.values()].sort((a, b) => a.resetsAt - b.resetsAt);
80
+ }
81
+ /** A 5-hour window "had capacity left" at this much or more. */
82
+ export const LEFT_PCT = 20;
83
+ /** A week "wasn't binding" when it reset with at least this much left. */
84
+ export const WEEK_SLACK_PCT = 10;
85
+ export function premise(ends) {
86
+ const five = ends.filter((e) => e.kind === '5h');
87
+ const exact = five.filter((e) => e.exact);
88
+ const left = exact.map((e) => 100 - e.usedPct).sort((a, b) => a - b);
89
+ const median = left.length ? (left.length % 2 ? left[(left.length - 1) / 2] : (left[left.length / 2 - 1] + left[left.length / 2]) / 2) : null;
90
+ const weeks = ends.filter((e) => e.kind === 'week').map((e) => ({ resetsAt: e.resetsAt, leftPct: 100 - e.usedPct, exact: e.exact }));
91
+ const weekOf = new Map(weeks.map((w) => [bucket(w.resetsAt), w]));
92
+ const judged = exact.filter((e) => e.weekResetsAt !== undefined && weekOf.has(bucket(e.weekResetsAt)));
93
+ const hits = judged.filter((e) => 100 - e.usedPct >= LEFT_PCT && weekOf.get(bucket(e.weekResetsAt)).leftPct >= WEEK_SLACK_PCT);
94
+ return {
95
+ fiveHour: { ended: five.length, exact: exact.length, medianLeftPct: median, withLeft: left.filter((l) => l >= LEFT_PCT).length },
96
+ weeks,
97
+ premise: { windows: judged.length, hits: hits.length, sharePct: judged.length ? Math.round((hits.length / judged.length) * 100) : null },
98
+ };
99
+ }
100
+ const day = (sec) => new Date(sec * 1000).toLocaleDateString([], { weekday: 'short', day: 'numeric', month: 'short' });
101
+ export function premiseText(p) {
102
+ const lines = [];
103
+ const f = p.fiveHour;
104
+ if (!f.ended && !p.weeks.length)
105
+ return ['No 5-hour window has ended since Chompyy started reading your quota. Check back after the next reset.'];
106
+ if (!f.ended)
107
+ lines.push('5-hour windows: none ended yet.');
108
+ else
109
+ lines.push(`5-hour windows: ${f.ended} ended, ${f.exact} with a reading close enough to the reset to know the final number.`, f.exact ? ` Left at reset: median ${Math.round(f.medianLeftPct)}%; ${f.withLeft} of ${f.exact} had ${LEFT_PCT}% or more left.` : ' None measured exactly yet.');
110
+ if (p.weeks.length) {
111
+ lines.push('Weeks:');
112
+ for (const w of p.weeks)
113
+ lines.push(` week to ${day(w.resetsAt)}: ${Math.round(w.leftPct)}% of the weekly allowance reset unused${w.exact ? '' : ' (at most: the last reading came before the reset)'}`);
114
+ }
115
+ else
116
+ lines.push('Weeks: none finished yet, so the weekly side is still unknown.');
117
+ const q = p.premise;
118
+ lines.push(q.windows
119
+ ? `The premise: ${q.hits} of ${q.windows} measured windows (${q.sharePct}%) reset with ${LEFT_PCT}%+ left in a week that still had ${WEEK_SLACK_PCT}%+ spare. That is capacity an away run could have used.`
120
+ : 'The premise: not measurable yet (needs a finished week with measured windows in it).');
121
+ return lines;
122
+ }
package/dist/projects.js CHANGED
@@ -38,13 +38,14 @@ function cwdOf(file) {
38
38
  }
39
39
  }
40
40
  export function recentProjects(board, opts = {}) {
41
+ const temp = opts.isTemp ?? isTemp;
41
42
  const claudeDir = opts.claudeDir ?? join(homedir(), '.claude', 'projects');
42
43
  const seen = new Map();
43
44
  const add = (dir, at) => {
44
- if (!dir || isTemp(dir) || !existsSync(dir))
45
+ if (!dir || temp(dir) || !existsSync(dir))
45
46
  return;
46
47
  const root = findGitRoot(dir);
47
- if (!root || root === homedir() || isTemp(root))
48
+ if (!root || root === homedir() || temp(root))
48
49
  return; // cards run best in git repos
49
50
  let path = root;
50
51
  try {