chompyy 0.4.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.
- package/README.md +2 -0
- package/dist/cli.js +23 -2
- package/dist/detect.js +511 -0
- package/dist/pacing.js +5 -0
- package/dist/premise.js +122 -0
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -128,6 +128,8 @@ Each card in a git repo runs in its own worktree at `~/.chompyy/worktrees/<id>`
|
|
|
128
128
|
| `chompyy taste retire <id>` | Stop using a preference; it stays in `taste list` with the reason |
|
|
129
129
|
| `chompyy distill [--force]` | Read new signals and update preferences now (also runs after every away run) |
|
|
130
130
|
| `chompyy trends` | Last 7 days vs the 7 before: cost per card, keep rate, rating, blueprint edits |
|
|
131
|
+
| `chompyy premise [--json]` | How often a 5-hour window reset with 20%+ left in a week that still had 10%+ spare: the capacity away runs can use. From your quota readings; every ended window is kept in `windows.jsonl` (numbers only), so it grows past the 8 days of `quota-history.json`. `--json` to share it |
|
|
132
|
+
| `chompyy detect [--days 30] [--all] [--json]` | The detective: what wastes tokens in your setup and habits, from your own files. One screen: the findings ranked by tokens and the fix to start with; `--all` adds each finding's count, measured or estimated, what it doesn't prove, and every fix. A mid-session cache rebuild names its cause (e.g. Tool Search loading an MCP server's tools). Works cold with `npx chompyy detect`, nothing else installed. This version checks startup tax (long CLAUDE.md, unused skills and MCP servers, cut-off MEMORY.md) and cache (cold returns, mid-session rebuilds). Reads only; changes nothing |
|
|
131
133
|
| `chompyy triggers on\|off` | Install or remove the macOS LaunchAgent that runs `chompyy tick` every 5 minutes |
|
|
132
134
|
| `chompyy bedtime <23:30\|off>` / `last-hour <on\|off>` / `missed-reset <on\|off>` | Turn the bedtime, last-hour-before-reset and missed-reset (first tick after an unused reset, default off) triggers on or off |
|
|
133
135
|
|
package/dist/cli.js
CHANGED
|
@@ -22,6 +22,8 @@ import { changedFiles, diffCard, keepCard, overlaps, questionsOf, undoCard } fro
|
|
|
22
22
|
import { CappedText, ClaudeRunner, claudeAvailable } from './runner.js';
|
|
23
23
|
import { branchOf, commitLeftovers, gitRoot, planWorkspace, prepareWorkspace } from './workspace.js';
|
|
24
24
|
import { answerCard, appState, cardView, currentBranch, editBlueprint, editIdea, recordCliLocation } from './appstate.js';
|
|
25
|
+
import { detect, detectText } from './detect.js';
|
|
26
|
+
import { allWindowEnds, archiveWindowEnds, premise, premiseText } from './premise.js';
|
|
25
27
|
import { keychainAllowed, loadLiveState, refreshLiveQuota } from './livequota.js';
|
|
26
28
|
import { recentProjects } from './projects.js';
|
|
27
29
|
import { cliVersion, installApp } from './macapp.js';
|
|
@@ -31,7 +33,7 @@ import { keepHistory } from './claudesettings.js';
|
|
|
31
33
|
import { blueprintHash, drawPicture } from './picture.js';
|
|
32
34
|
import { costRange, formatCostRange, readRuns, trendLines } from './costs.js';
|
|
33
35
|
import { answerPreference, distill, distillDue, formatPrefs, formatQuestion, formatWhy, getPref, loadStore, nextQuestion, readSignals, recordOutcome, retirePreference, syncTasteFile, tasteChangesSince, } from './taste.js';
|
|
34
|
-
import { cachedWorkspaces, dream, dreamDue, formatDream, formatWorkspaces, readLogPath, setTicked } from './dream.js';
|
|
36
|
+
import { cachedWorkspaces, dream, dreamDue, formatDream, formatWorkspaces, projectsDir, readLogPath, setTicked } from './dream.js';
|
|
35
37
|
import { byKind, compare, formatExtras, formatUsage, loadLedger, periodDays, PERIODS, prCosts, usageView } from './usage.js';
|
|
36
38
|
import { formatTrace, traceSession } from './trace.js';
|
|
37
39
|
import { homedir } from 'node:os';
|
|
@@ -45,6 +47,8 @@ Quota
|
|
|
45
47
|
chompyy status % left, time to reset, pace, weekly used, staleness
|
|
46
48
|
chompyy quota [--refresh] read live quota from Anthropic now (uses Claude Code's saved login; sends no message)
|
|
47
49
|
chompyy quota --allow-keychain | --no-keychain allow (or stop) reading that login from the macOS Keychain
|
|
50
|
+
chompyy detect [--days 30] [--all] [--json] what wastes tokens in your setup and habits, ranked, on one screen (--all: evidence and every fix)
|
|
51
|
+
chompyy premise [--json] how often a 5-hour window reset with capacity left while the week still had room
|
|
48
52
|
chompyy eat-tokens show leftover quota and cards you could choose to run (read-only)
|
|
49
53
|
|
|
50
54
|
Board
|
|
@@ -471,7 +475,8 @@ async function main(argv) {
|
|
|
471
475
|
const [command, ...args] = values.help ? ["help"] : positionals;
|
|
472
476
|
const now = new Date();
|
|
473
477
|
const json = (data) => console.log(JSON.stringify(data, null, 2));
|
|
474
|
-
|
|
478
|
+
// detect and premise only read: run once through npx, they must not point the app at npx's temporary copy.
|
|
479
|
+
if (command !== 'statusline' && command !== 'detect' && command !== 'premise')
|
|
475
480
|
recordCliLocation();
|
|
476
481
|
/** Fresh quota before anything that reads it (at most every 5 minutes unless forced). */
|
|
477
482
|
const freshQuota = async (force = false) => {
|
|
@@ -1091,6 +1096,22 @@ async function main(argv) {
|
|
|
1091
1096
|
console.log(await distillNow(now, Boolean(values.force)));
|
|
1092
1097
|
return;
|
|
1093
1098
|
}
|
|
1099
|
+
case 'detect': {
|
|
1100
|
+
const r = detect({ days: values.days ? Number(values.days) : 30, now });
|
|
1101
|
+
if (values.json)
|
|
1102
|
+
return json(r);
|
|
1103
|
+
console.log(detectText(r, { all: Boolean(values.all), projects: projectsDir().replace(homedir(), '~') }).join('\n'));
|
|
1104
|
+
return;
|
|
1105
|
+
}
|
|
1106
|
+
case 'premise': {
|
|
1107
|
+
const ends = allWindowEnds(loadSamples(), now.getTime());
|
|
1108
|
+
archiveWindowEnds(loadSamples(), now.getTime());
|
|
1109
|
+
const p = premise(ends);
|
|
1110
|
+
if (values.json)
|
|
1111
|
+
return json({ ...p, windows: ends });
|
|
1112
|
+
console.log(premiseText(p).join('\n'));
|
|
1113
|
+
return;
|
|
1114
|
+
}
|
|
1094
1115
|
case 'trends': {
|
|
1095
1116
|
const lines = trendLines(readRuns(), readSignals(), now);
|
|
1096
1117
|
console.log(lines.length ? lines.join('\n') : 'Not enough runs yet for trends (needs 3).');
|
package/dist/detect.js
ADDED
|
@@ -0,0 +1,511 @@
|
|
|
1
|
+
// `chompyy detect` (FEATURES §8, step 2 of the detective): runs the rulebook (research/detective/RULEBOOK.md) on
|
|
2
|
+
// your own local files and lists what it finds. This first version covers the two chapters that weigh most:
|
|
3
|
+
// startup tax (S2–S5: what loads before you type) and cache (C1, C2: context rebuilt from scratch).
|
|
4
|
+
//
|
|
5
|
+
// The rulebook's personality applies to every finding: evidence first with a count, measured vs estimated
|
|
6
|
+
// labelled, what it doesn't prove said out loud, no dollars on a subscription, smallest fix first.
|
|
7
|
+
import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs';
|
|
8
|
+
import { homedir } from 'node:os';
|
|
9
|
+
import { basename, dirname, join } from 'node:path';
|
|
10
|
+
import { projectsDir } from './dream.js';
|
|
11
|
+
/**
|
|
12
|
+
* Folders under ~/.claude/projects made by automated runs in temp folders (benchmarks, sandboxes, Chompyy's own
|
|
13
|
+
* cards): not your sessions, so they don't count for or against you.
|
|
14
|
+
*/
|
|
15
|
+
export const isAutomated = (folder) => /^-private-|^-var-folders-|^-tmp-|-T-|chompyy-worktrees|\.chompyy-worktrees/.test(folder);
|
|
16
|
+
const num = (v) => (typeof v === 'number' && Number.isFinite(v) ? v : 0);
|
|
17
|
+
export function readSession(file) {
|
|
18
|
+
const turns = new Map();
|
|
19
|
+
let cwd = '';
|
|
20
|
+
let id = basename(file, '.jsonl');
|
|
21
|
+
const skills = new Map();
|
|
22
|
+
const commands = new Map();
|
|
23
|
+
const mcp = new Map();
|
|
24
|
+
// What changed since the last request: read back when the next request says the tool list changed.
|
|
25
|
+
let loaded = [];
|
|
26
|
+
let after = '';
|
|
27
|
+
for (const line of readFileSync(file, 'utf8').split('\n')) {
|
|
28
|
+
if (!line.includes('"assistant"') && !line.includes('<command-name>') && !line.includes('deferred_tools_record'))
|
|
29
|
+
continue;
|
|
30
|
+
let e;
|
|
31
|
+
try {
|
|
32
|
+
e = JSON.parse(line);
|
|
33
|
+
}
|
|
34
|
+
catch {
|
|
35
|
+
continue;
|
|
36
|
+
}
|
|
37
|
+
if (!cwd && typeof e.cwd === 'string')
|
|
38
|
+
cwd = e.cwd;
|
|
39
|
+
const att = e.attachment;
|
|
40
|
+
if (e.type === 'attachment' && att?.type === 'deferred_tools_record' && att.entries?.length) {
|
|
41
|
+
// Tool Search loaded these tools into the list; an MCP tool counts as its server.
|
|
42
|
+
loaded = [...new Set(att.entries.map((x) => String(x.name ?? '')).filter(Boolean).map((n) => (n.startsWith('mcp__') ? n.split('__')[1] : n)))];
|
|
43
|
+
continue;
|
|
44
|
+
}
|
|
45
|
+
if (typeof e.sessionId === 'string')
|
|
46
|
+
id = e.sessionId;
|
|
47
|
+
const msg = e.message;
|
|
48
|
+
const content = msg?.content;
|
|
49
|
+
if (typeof content === 'string' || Array.isArray(content)) {
|
|
50
|
+
const text = typeof content === 'string' ? content : content.map((b) => (typeof b?.text === 'string' ? b.text : '')).join('');
|
|
51
|
+
for (const m of text.matchAll(/<command-name>\/?([^<\s]+)<\/command-name>/g)) {
|
|
52
|
+
commands.set(m[1], (commands.get(m[1]) ?? 0) + 1);
|
|
53
|
+
if (/^(mcp|model|plugin|config|permissions)$/.test(m[1]))
|
|
54
|
+
after = `/${m[1]}`;
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
if (e.type !== 'assistant' || !msg?.usage || e.isSidechain)
|
|
58
|
+
continue;
|
|
59
|
+
if (Array.isArray(content)) {
|
|
60
|
+
for (const b of content) {
|
|
61
|
+
if (b?.type !== 'tool_use' || !b.name)
|
|
62
|
+
continue;
|
|
63
|
+
if (b.name === 'Skill' && typeof b.input?.skill === 'string')
|
|
64
|
+
skills.set(b.input.skill, (skills.get(b.input.skill) ?? 0) + 1);
|
|
65
|
+
if (b.name.startsWith('mcp__')) {
|
|
66
|
+
const server = b.name.split('__')[1];
|
|
67
|
+
mcp.set(server, (mcp.get(server) ?? 0) + 1);
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
const u = msg.usage;
|
|
72
|
+
const cc = (u.cache_creation ?? {});
|
|
73
|
+
const diag = (msg.diagnostics ?? e.diagnostics) ?? {};
|
|
74
|
+
const reason = (diag.cache_miss_reason ?? {});
|
|
75
|
+
const key = msg.id ?? `${turns.size}`;
|
|
76
|
+
const turn = {
|
|
77
|
+
at: Date.parse(String(e.timestamp ?? '')) || 0,
|
|
78
|
+
cacheRead: num(u.cache_read_input_tokens),
|
|
79
|
+
cacheWrite: num(u.cache_creation_input_tokens),
|
|
80
|
+
wrote1h: num(cc.ephemeral_1h_input_tokens) > 0,
|
|
81
|
+
...(reason.type ? { miss: reason.type } : {}),
|
|
82
|
+
...(reason.cache_missed_input_tokens ? { missedTokens: num(reason.cache_missed_input_tokens) } : {}),
|
|
83
|
+
};
|
|
84
|
+
// One request is logged once per content block: keep the first time and the largest numbers.
|
|
85
|
+
const had = turns.get(key);
|
|
86
|
+
if (!had) {
|
|
87
|
+
if (turn.miss === 'tools_changed') {
|
|
88
|
+
if (loaded.length)
|
|
89
|
+
turn.loaded = loaded;
|
|
90
|
+
if (after)
|
|
91
|
+
turn.after = after;
|
|
92
|
+
}
|
|
93
|
+
loaded = [];
|
|
94
|
+
after = '';
|
|
95
|
+
}
|
|
96
|
+
turns.set(key, had ? { ...turn, at: had.at || turn.at, miss: had.miss ?? turn.miss, loaded: had.loaded, after: had.after, cacheWrite: Math.max(had.cacheWrite, turn.cacheWrite), cacheRead: Math.max(had.cacheRead, turn.cacheRead) } : turn);
|
|
97
|
+
}
|
|
98
|
+
if (!turns.size)
|
|
99
|
+
return null;
|
|
100
|
+
const session = {
|
|
101
|
+
id,
|
|
102
|
+
cwd,
|
|
103
|
+
turns: [...turns.values()].filter((t) => t.at).sort((a, b) => a.at - b.at),
|
|
104
|
+
};
|
|
105
|
+
return Object.assign(session, { skills, commands, mcp });
|
|
106
|
+
}
|
|
107
|
+
/** Your sessions from the last `days` days (by file time), automated runs left out. */
|
|
108
|
+
export function scan(opts = {}) {
|
|
109
|
+
const now = (opts.now ?? new Date()).getTime();
|
|
110
|
+
const since = now - (opts.days ?? 30) * 86_400_000;
|
|
111
|
+
const root = opts.root ?? projectsDir();
|
|
112
|
+
const out = { sessions: [], skills: new Map(), commands: new Map(), mcp: new Map(), firstAt: Infinity, lastAt: 0 };
|
|
113
|
+
if (!existsSync(root))
|
|
114
|
+
return { ...out, firstAt: 0 };
|
|
115
|
+
for (const folder of readdirSync(root)) {
|
|
116
|
+
if (isAutomated(folder))
|
|
117
|
+
continue;
|
|
118
|
+
const dir = join(root, folder);
|
|
119
|
+
let names;
|
|
120
|
+
try {
|
|
121
|
+
names = readdirSync(dir).filter((n) => n.endsWith('.jsonl'));
|
|
122
|
+
}
|
|
123
|
+
catch {
|
|
124
|
+
continue;
|
|
125
|
+
}
|
|
126
|
+
for (const n of names) {
|
|
127
|
+
const file = join(dir, n);
|
|
128
|
+
try {
|
|
129
|
+
if (statSync(file).mtimeMs < since)
|
|
130
|
+
continue;
|
|
131
|
+
}
|
|
132
|
+
catch {
|
|
133
|
+
continue;
|
|
134
|
+
}
|
|
135
|
+
const s = readSession(file);
|
|
136
|
+
if (!s || !s.turns.length)
|
|
137
|
+
continue;
|
|
138
|
+
out.sessions.push({ id: s.id, cwd: s.cwd, turns: s.turns });
|
|
139
|
+
out.firstAt = Math.min(out.firstAt, s.turns[0].at);
|
|
140
|
+
out.lastAt = Math.max(out.lastAt, s.turns.at(-1).at);
|
|
141
|
+
for (const [k, v] of s.skills)
|
|
142
|
+
out.skills.set(k, (out.skills.get(k) ?? 0) + v);
|
|
143
|
+
for (const [k, v] of s.commands)
|
|
144
|
+
out.commands.set(k, (out.commands.get(k) ?? 0) + v);
|
|
145
|
+
for (const [k, v] of s.mcp) {
|
|
146
|
+
const m = out.mcp.get(k) ?? { calls: 0, projects: new Set() };
|
|
147
|
+
m.calls += v;
|
|
148
|
+
m.projects.add(s.cwd);
|
|
149
|
+
out.mcp.set(k, m);
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
if (out.firstAt === Infinity)
|
|
154
|
+
out.firstAt = 0;
|
|
155
|
+
return out;
|
|
156
|
+
}
|
|
157
|
+
/** Characters ÷ 4: every tool uses this; label it estimated. */
|
|
158
|
+
export const tokensOf = (text) => Math.ceil(text.length / 4);
|
|
159
|
+
function skillAt(file, source, plugin) {
|
|
160
|
+
let text;
|
|
161
|
+
try {
|
|
162
|
+
text = readFileSync(file, 'utf8');
|
|
163
|
+
}
|
|
164
|
+
catch {
|
|
165
|
+
return null;
|
|
166
|
+
}
|
|
167
|
+
const front = text.match(/^---\n([\s\S]*?)\n---/)?.[1] ?? '';
|
|
168
|
+
const name = front.match(/^name:\s*(.+)$/m)?.[1]?.trim().replace(/^["']|["']$/g, '') || basename(dirname(file));
|
|
169
|
+
const description = front.match(/^description:\s*([\s\S]*?)(?=\n[a-z_-]+:|$)/m)?.[1]?.trim() ?? '';
|
|
170
|
+
return { name, calledAs: plugin ? `${plugin}:${name}` : name, descriptionTokens: tokensOf(`${name}: ${description}`), source, installedAt: statSync(file).mtimeMs };
|
|
171
|
+
}
|
|
172
|
+
const skillFiles = (dir, depth = 3) => {
|
|
173
|
+
if (!existsSync(dir))
|
|
174
|
+
return [];
|
|
175
|
+
const out = [];
|
|
176
|
+
for (const n of readdirSync(dir, { withFileTypes: true })) {
|
|
177
|
+
const p = join(dir, n.name);
|
|
178
|
+
if (n.isFile() && n.name === 'SKILL.md')
|
|
179
|
+
out.push(p);
|
|
180
|
+
else if (n.isDirectory() && depth > 0 && n.name !== 'node_modules' && !n.name.startsWith('_archived'))
|
|
181
|
+
out.push(...skillFiles(p, depth - 1));
|
|
182
|
+
}
|
|
183
|
+
return out;
|
|
184
|
+
};
|
|
185
|
+
/** A plugin's skills: the ones its manifest lists (it can ship more than it exposes), else everything under skills/. */
|
|
186
|
+
function pluginSkillFiles(installPath) {
|
|
187
|
+
try {
|
|
188
|
+
const manifest = JSON.parse(readFileSync(join(installPath, '.claude-plugin', 'plugin.json'), 'utf8'));
|
|
189
|
+
if (Array.isArray(manifest.skills)) {
|
|
190
|
+
return manifest.skills.filter((p) => typeof p === 'string').map((p) => (p.endsWith('SKILL.md') ? join(installPath, p) : join(installPath, p, 'SKILL.md'))).filter(existsSync);
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
catch { }
|
|
194
|
+
return skillFiles(join(installPath, 'skills'), 2);
|
|
195
|
+
}
|
|
196
|
+
/** Your skills (~/.claude/skills, including account-synced ones) and the skills of enabled plugins. */
|
|
197
|
+
export function installedSkills(claudeDir = join(homedir(), '.claude')) {
|
|
198
|
+
const skills = [];
|
|
199
|
+
const mine = join(claudeDir, 'skills');
|
|
200
|
+
for (const f of skillFiles(mine)) {
|
|
201
|
+
const s = skillAt(f, f.includes('/synced/') ? 'synced' : 'yours');
|
|
202
|
+
if (s)
|
|
203
|
+
skills.push(s);
|
|
204
|
+
}
|
|
205
|
+
let enabled = {};
|
|
206
|
+
try {
|
|
207
|
+
enabled = JSON.parse(readFileSync(join(claudeDir, 'settings.json'), 'utf8')).enabledPlugins ?? {};
|
|
208
|
+
}
|
|
209
|
+
catch { }
|
|
210
|
+
let installed = {};
|
|
211
|
+
try {
|
|
212
|
+
const j = JSON.parse(readFileSync(join(claudeDir, 'plugins', 'installed_plugins.json'), 'utf8'));
|
|
213
|
+
installed = j.plugins ?? j;
|
|
214
|
+
}
|
|
215
|
+
catch { }
|
|
216
|
+
for (const [id, on] of Object.entries(enabled)) {
|
|
217
|
+
if (!on)
|
|
218
|
+
continue;
|
|
219
|
+
const plugin = id.split('@')[0];
|
|
220
|
+
for (const inst of installed[id] ?? []) {
|
|
221
|
+
if (!inst.installPath)
|
|
222
|
+
continue;
|
|
223
|
+
for (const f of pluginSkillFiles(inst.installPath)) {
|
|
224
|
+
const s = skillAt(f, 'plugin', plugin);
|
|
225
|
+
if (s)
|
|
226
|
+
skills.push(s);
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
return skills;
|
|
231
|
+
}
|
|
232
|
+
/** MCP servers from ~/.claude.json (user and per-project) and each project's .mcp.json. */
|
|
233
|
+
export function configuredMcp(workspaces, home = homedir()) {
|
|
234
|
+
const out = [];
|
|
235
|
+
try {
|
|
236
|
+
const j = JSON.parse(readFileSync(join(home, '.claude.json'), 'utf8'));
|
|
237
|
+
for (const n of Object.keys(j.mcpServers ?? {}))
|
|
238
|
+
out.push({ name: n, scope: 'user' });
|
|
239
|
+
for (const [p, v] of Object.entries(j.projects ?? {}))
|
|
240
|
+
for (const n of Object.keys(v.mcpServers ?? {}))
|
|
241
|
+
out.push({ name: n, scope: p });
|
|
242
|
+
}
|
|
243
|
+
catch { }
|
|
244
|
+
for (const w of new Set(workspaces)) {
|
|
245
|
+
try {
|
|
246
|
+
const j = JSON.parse(readFileSync(join(w, '.mcp.json'), 'utf8'));
|
|
247
|
+
for (const n of Object.keys(j.mcpServers ?? {}))
|
|
248
|
+
out.push({ name: n, scope: w });
|
|
249
|
+
}
|
|
250
|
+
catch { }
|
|
251
|
+
}
|
|
252
|
+
return out;
|
|
253
|
+
}
|
|
254
|
+
// ---------- the rules ----------
|
|
255
|
+
const DAY = 86_400_000;
|
|
256
|
+
const fmt = (n) => (n >= 1_000_000 ? `${(n / 1_000_000).toFixed(n >= 10_000_000 ? 0 : 1)}M` : n >= 1000 ? `${(n / 1000).toFixed(n >= 10_000 ? 0 : 1)}k` : String(Math.round(n)));
|
|
257
|
+
const median = (xs) => {
|
|
258
|
+
const s = [...xs].sort((a, b) => a - b);
|
|
259
|
+
return s.length ? (s.length % 2 ? s[(s.length - 1) / 2] : (s[s.length / 2 - 1] + s[s.length / 2]) / 2) : 0;
|
|
260
|
+
};
|
|
261
|
+
const home = (p) => p.replace(homedir(), '~');
|
|
262
|
+
/** S2: CLAUDE.md over 200 lines or 2,000 tokens, charged to the sessions that load it. */
|
|
263
|
+
export function ruleS2(s, claudeDir = join(homedir(), '.claude')) {
|
|
264
|
+
const files = new Map(); // file → sessions that load it
|
|
265
|
+
const userMd = join(claudeDir, 'CLAUDE.md');
|
|
266
|
+
for (const ses of s.sessions) {
|
|
267
|
+
for (const f of [userMd, ses.cwd ? join(ses.cwd, 'CLAUDE.md') : ''])
|
|
268
|
+
if (f && existsSync(f))
|
|
269
|
+
files.set(f, (files.get(f) ?? 0) + 1);
|
|
270
|
+
}
|
|
271
|
+
const out = [];
|
|
272
|
+
for (const [f, sessions] of files) {
|
|
273
|
+
const text = readFileSync(f, 'utf8');
|
|
274
|
+
const lines = text.split('\n').length;
|
|
275
|
+
const tokens = tokensOf(text);
|
|
276
|
+
if (lines <= 200 && tokens <= 2000)
|
|
277
|
+
continue;
|
|
278
|
+
out.push({
|
|
279
|
+
rule: 'S2',
|
|
280
|
+
title: 'CLAUDE.md is long',
|
|
281
|
+
say: `${home(f)} is ${lines} lines (~${fmt(tokens)} tokens) and loads in every session there: ${sessions} sessions in this scan.`,
|
|
282
|
+
basis: 'estimated',
|
|
283
|
+
tokens: tokens * sessions,
|
|
284
|
+
tokensHow: `~${fmt(tokens)} × ${sessions} sessions`,
|
|
285
|
+
notProve: "Long isn't wrong: lines that stop the agent repeating a mistake earn their place.",
|
|
286
|
+
fix: 'A card to tier it: keep identity, critical rules and key paths; move workflows into skills and long guides into files it reads when needed. No rule deleted without saying where it went.',
|
|
287
|
+
lane: 'work',
|
|
288
|
+
});
|
|
289
|
+
}
|
|
290
|
+
return out;
|
|
291
|
+
}
|
|
292
|
+
/** S3: installed skills with no use, when there's enough history to say so. */
|
|
293
|
+
export function ruleS3(s, skills, now) {
|
|
294
|
+
const spanDays = s.sessions.length ? (s.lastAt - s.firstAt) / DAY : 0;
|
|
295
|
+
if (s.sessions.length < 20 || spanDays < 14)
|
|
296
|
+
return [];
|
|
297
|
+
const used = new Set([...s.skills.keys(), ...s.commands.keys()]);
|
|
298
|
+
const isUsed = (k) => used.has(k.calledAs) || used.has(k.name) || [...used].some((u) => u.endsWith(`:${k.name}`));
|
|
299
|
+
const unused = skills.filter((k) => !isUsed(k) && now - k.installedAt > DAY && !/chompyy/i.test(k.name));
|
|
300
|
+
if (unused.length < 5)
|
|
301
|
+
return [];
|
|
302
|
+
const tokens = unused.reduce((a, k) => a + k.descriptionTokens, 0);
|
|
303
|
+
const bySource = (src) => unused.filter((k) => k.source === src);
|
|
304
|
+
const parts = ['plugin', 'synced', 'yours'].map((src) => [src, bySource(src)]).filter(([, l]) => l.length);
|
|
305
|
+
const label = { plugin: 'from plugins', synced: 'synced from your claude.ai account', yours: 'in ~/.claude/skills' };
|
|
306
|
+
return [
|
|
307
|
+
{
|
|
308
|
+
rule: 'S3',
|
|
309
|
+
title: 'Skills you never use still load every session',
|
|
310
|
+
say: `${unused.length} of ${skills.length} installed skills had no use in ${s.sessions.length} sessions over ${Math.round(spanDays)} days (${parts.map(([src, l]) => `${l.length} ${label[src]}`).join(', ')}). Their names and descriptions add ~${fmt(tokens)} tokens to every session start. Examples: ${unused.slice(0, 5).map((k) => k.calledAs).join(', ')}.`,
|
|
311
|
+
basis: 'estimated',
|
|
312
|
+
tokens: tokens * s.sessions.length,
|
|
313
|
+
tokensHow: `~${fmt(tokens)} × ${s.sessions.length} sessions`,
|
|
314
|
+
notProve: "Not seeing a skill used doesn't prove you'll never need it.",
|
|
315
|
+
fix: [
|
|
316
|
+
bySource('plugin').length ? 'Turn off plugins you don\'t use (`/plugin`, or enabledPlugins in ~/.claude/settings.json)' : '',
|
|
317
|
+
bySource('synced').length ? 'turn off synced skills you don\'t use in claude.ai settings' : '',
|
|
318
|
+
bySource('yours').length ? 'move your own unused skills outside ~/.claude/skills (an _archived folder inside still loads)' : '',
|
|
319
|
+
].filter(Boolean).join('; ') + '.',
|
|
320
|
+
lane: 'settings',
|
|
321
|
+
},
|
|
322
|
+
];
|
|
323
|
+
}
|
|
324
|
+
/** S4: configured MCP servers with no calls. */
|
|
325
|
+
export function ruleS4(s, servers) {
|
|
326
|
+
if (s.sessions.length < 2)
|
|
327
|
+
return [];
|
|
328
|
+
const idle = servers.filter((m) => !s.mcp.has(m.name));
|
|
329
|
+
if (!idle.length)
|
|
330
|
+
return [];
|
|
331
|
+
return [
|
|
332
|
+
{
|
|
333
|
+
rule: 'S4',
|
|
334
|
+
title: 'MCP servers you never call',
|
|
335
|
+
say: `${idle.length} configured MCP server${idle.length > 1 ? 's were' : ' was'} never called in ${s.sessions.length} sessions: ${idle.map((m) => `${m.name} (${m.scope === 'user' ? 'all projects' : home(m.scope)})`).join(', ')}.`,
|
|
336
|
+
basis: 'estimated',
|
|
337
|
+
notProve: "With Tool Search deferral (the default now) an idle server costs little at startup. A server that reconnects mid-session does cost a cache rebuild, though (C2).",
|
|
338
|
+
fix: 'Remove it, or move it to the one project that needs it.',
|
|
339
|
+
lane: 'settings',
|
|
340
|
+
},
|
|
341
|
+
];
|
|
342
|
+
}
|
|
343
|
+
/** S5: MEMORY.md past what Claude Code loads (200 lines or 25 KB). */
|
|
344
|
+
export function ruleS5(root = projectsDir()) {
|
|
345
|
+
const out = [];
|
|
346
|
+
if (!existsSync(root))
|
|
347
|
+
return out;
|
|
348
|
+
for (const folder of readdirSync(root)) {
|
|
349
|
+
if (isAutomated(folder))
|
|
350
|
+
continue;
|
|
351
|
+
const f = join(root, folder, 'memory', 'MEMORY.md');
|
|
352
|
+
if (!existsSync(f))
|
|
353
|
+
continue;
|
|
354
|
+
const text = readFileSync(f, 'utf8');
|
|
355
|
+
const lines = text.split('\n').length;
|
|
356
|
+
const bytes = Buffer.byteLength(text);
|
|
357
|
+
if (lines <= 200 && bytes <= 25_000)
|
|
358
|
+
continue;
|
|
359
|
+
out.push({
|
|
360
|
+
rule: 'S5',
|
|
361
|
+
title: 'MEMORY.md is cut off',
|
|
362
|
+
say: `${home(f)} is ${lines} lines (${Math.round(bytes / 1000)} KB). Claude Code loads only the first 200 lines or 25 KB, so the rest never reaches the agent.`,
|
|
363
|
+
basis: 'measured',
|
|
364
|
+
fix: 'Compress the index to one line per memory, and move duplicates out.',
|
|
365
|
+
lane: 'work',
|
|
366
|
+
});
|
|
367
|
+
}
|
|
368
|
+
return out;
|
|
369
|
+
}
|
|
370
|
+
/** C1: coming back after the cache expired, so the whole context is written again. */
|
|
371
|
+
export function ruleC1(s, now) {
|
|
372
|
+
const since = now - 14 * DAY;
|
|
373
|
+
const cold = [];
|
|
374
|
+
let allWrites = 0;
|
|
375
|
+
for (const ses of s.sessions) {
|
|
376
|
+
for (let i = 0; i < ses.turns.length; i++) {
|
|
377
|
+
const t = ses.turns[i];
|
|
378
|
+
if (t.at < since)
|
|
379
|
+
continue;
|
|
380
|
+
allWrites += t.cacheWrite;
|
|
381
|
+
const prev = ses.turns[i - 1];
|
|
382
|
+
if (!prev || t.miss !== 'previous_message_not_found')
|
|
383
|
+
continue;
|
|
384
|
+
const ttl = prev.wrote1h ? 60 * 60_000 : 5 * 60_000;
|
|
385
|
+
if (t.at - prev.at > ttl)
|
|
386
|
+
cold.push(t.cacheWrite);
|
|
387
|
+
}
|
|
388
|
+
}
|
|
389
|
+
const coldWrites = cold.reduce((a, b) => a + b, 0);
|
|
390
|
+
const share = allWrites ? coldWrites / allWrites : 0;
|
|
391
|
+
if (cold.length < 3 && share < 0.05)
|
|
392
|
+
return [];
|
|
393
|
+
return [
|
|
394
|
+
{
|
|
395
|
+
rule: 'C1',
|
|
396
|
+
title: 'Coming back after the cache expired',
|
|
397
|
+
say: `${cold.length} times in the last 14 days you came back to a session after its cache had expired (an hour for the main conversation), so the whole context was written again: median ${fmt(median(cold))} tokens each, ${fmt(coldWrites)} in all, ${Math.round(share * 100)}% of your cache writes.`,
|
|
398
|
+
basis: 'measured',
|
|
399
|
+
notProve: "Some of these returns were worth it: a long session with context you'd otherwise have to rebuild.",
|
|
400
|
+
tokens: coldWrites,
|
|
401
|
+
fix: 'Before a long break, finish the thought and leave a short note; start fresh from the note when you return. Or /compact before leaving so the rewrite is small. Never automated keep-warm pings (rulebook T2).',
|
|
402
|
+
lane: 'habit',
|
|
403
|
+
},
|
|
404
|
+
];
|
|
405
|
+
}
|
|
406
|
+
/** C2: the cache thrown away mid-session (the tool list or earlier messages changed), with what caused it. */
|
|
407
|
+
export function ruleC2(s) {
|
|
408
|
+
const hits = [];
|
|
409
|
+
let sessionsHit = 0;
|
|
410
|
+
for (const ses of s.sessions) {
|
|
411
|
+
const here = ses.turns.filter((t) => t.miss === 'tools_changed' || t.miss === 'messages_changed');
|
|
412
|
+
hits.push(...here);
|
|
413
|
+
if (here.length)
|
|
414
|
+
sessionsHit++;
|
|
415
|
+
}
|
|
416
|
+
const size = (t) => t.missedTokens ?? t.cacheWrite;
|
|
417
|
+
if (sessionsHit < 2 && !hits.some((t) => size(t) >= 50_000))
|
|
418
|
+
return [];
|
|
419
|
+
const total = hits.reduce((a, t) => a + size(t), 0);
|
|
420
|
+
// Group by cause: "loaded claude-in-chrome", "/mcp", or unknown.
|
|
421
|
+
const causes = new Map();
|
|
422
|
+
for (const t of hits) {
|
|
423
|
+
const cause = t.miss === 'messages_changed' ? 'messages' : t.loaded?.length ? `loaded ${t.loaded.join(', ')}` : t.after ?? 'tools';
|
|
424
|
+
causes.set(cause, [...(causes.get(cause) ?? []), t]);
|
|
425
|
+
}
|
|
426
|
+
const sorted = [...causes].sort((x, y) => y[1].reduce((a, t) => a + size(t), 0) - x[1].reduce((a, t) => a + size(t), 0));
|
|
427
|
+
const said = (cause, ts) => {
|
|
428
|
+
const n = ts.length === 1 ? 'once' : `${ts.length} times`;
|
|
429
|
+
const sizes = `${ts.map((t) => fmt(size(t))).join(', ')} re-cached`;
|
|
430
|
+
if (cause.startsWith('loaded '))
|
|
431
|
+
return `${n} right after Tool Search loaded ${cause.slice(7)}'s tools mid-session (${sizes})`;
|
|
432
|
+
if (cause.startsWith('/'))
|
|
433
|
+
return `${n} right after you ran ${cause} (${sizes})`;
|
|
434
|
+
if (cause === 'messages')
|
|
435
|
+
return `${n} because earlier messages changed (${sizes})`;
|
|
436
|
+
return `${n} because the tool list changed, cause not logged (${sizes})`;
|
|
437
|
+
};
|
|
438
|
+
const fixes = [];
|
|
439
|
+
const servers = [...new Set(hits.flatMap((t) => t.loaded ?? []))];
|
|
440
|
+
if (servers.length)
|
|
441
|
+
fixes.push(`Load ${servers.join(', ')} at the start of a session, or do that work in its own session: loading a tool mid-session puts it at the front of the context and everything after it is written again.`);
|
|
442
|
+
if (hits.some((t) => t.after))
|
|
443
|
+
fixes.push('Change MCP servers, models, plugins or settings between sessions, not in the middle of one.');
|
|
444
|
+
if (hits.some((t) => t.miss === 'tools_changed' && !t.loaded?.length && !t.after))
|
|
445
|
+
fixes.push('Usually an MCP server connecting or disconnecting: keep flaky servers off for that project.');
|
|
446
|
+
if (hits.some((t) => t.miss === 'messages_changed'))
|
|
447
|
+
fixes.push('Earlier messages change when you rewind or edit a message: start fresh rather than editing far back.');
|
|
448
|
+
return [
|
|
449
|
+
{
|
|
450
|
+
rule: 'C2',
|
|
451
|
+
title: 'Cache thrown away mid-session',
|
|
452
|
+
say: `${hits.length} time${hits.length > 1 ? 's' : ''} in ${sessionsHit} session${sessionsHit > 1 ? 's' : ''} the whole context was written again mid-session: ${sorted.map(([c, ts]) => said(c, ts)).join('; ')}.`,
|
|
453
|
+
basis: 'measured',
|
|
454
|
+
tokens: total,
|
|
455
|
+
fix: fixes.join(' '),
|
|
456
|
+
lane: 'habit',
|
|
457
|
+
},
|
|
458
|
+
];
|
|
459
|
+
}
|
|
460
|
+
export function detect(opts = {}) {
|
|
461
|
+
const now = (opts.now ?? new Date()).getTime();
|
|
462
|
+
const s = scan({ days: opts.days ?? 30, now: new Date(now), ...(opts.root ? { root: opts.root } : {}) });
|
|
463
|
+
const skills = installedSkills(opts.claudeDir);
|
|
464
|
+
const servers = configuredMcp(s.sessions.map((x) => x.cwd).filter(Boolean), opts.home);
|
|
465
|
+
const findings = [
|
|
466
|
+
...ruleC1(s, now),
|
|
467
|
+
...ruleC2(s),
|
|
468
|
+
...ruleS3(s, skills, now),
|
|
469
|
+
...ruleS2(s, opts.claudeDir),
|
|
470
|
+
...ruleS4(s, servers),
|
|
471
|
+
...ruleS5(opts.root),
|
|
472
|
+
];
|
|
473
|
+
return { scanned: { sessions: s.sessions.length, days: opts.days ?? 30, skills: skills.length, mcpServers: servers.length }, findings };
|
|
474
|
+
}
|
|
475
|
+
const short = (text) => text.split(/(?<=\.)\s/)[0];
|
|
476
|
+
/**
|
|
477
|
+
* One screen: what it read, the findings ranked by tokens, and the one fix to start with. `all` adds each
|
|
478
|
+
* finding's evidence, what it doesn't prove, and every fix.
|
|
479
|
+
*/
|
|
480
|
+
export function detectText(r, opts = {}) {
|
|
481
|
+
const { sessions, days, skills, mcpServers } = r.scanned;
|
|
482
|
+
if (!sessions) {
|
|
483
|
+
return [
|
|
484
|
+
`No Claude Code sessions from the last ${days} days in ${opts.projects ?? '~/.claude/projects'}.`,
|
|
485
|
+
'detect reads the transcripts Claude Code keeps on this computer. Use Claude Code for a few days, then run it again.',
|
|
486
|
+
];
|
|
487
|
+
}
|
|
488
|
+
const lines = [`Read ${sessions} of your Claude Code sessions from the last ${days} days, ${skills} installed skills and ${mcpServers} MCP servers. Nothing left this computer.`];
|
|
489
|
+
if (!r.findings.length)
|
|
490
|
+
return [...lines, '', 'Nothing to fix in what this version checks (startup tax and cache).'];
|
|
491
|
+
const ranked = [...r.findings].sort((a, b) => (b.tokens ?? -1) - (a.tokens ?? -1));
|
|
492
|
+
const cost = (f) => (f.tokens === undefined ? '' : `${f.basis === 'estimated' ? '~' : ''}${fmt(f.tokens)} tokens`);
|
|
493
|
+
const w = Math.max(...ranked.map((f) => f.title.length));
|
|
494
|
+
const cw = Math.max(...ranked.map((f) => cost(f).length));
|
|
495
|
+
lines.push('');
|
|
496
|
+
for (const f of ranked)
|
|
497
|
+
lines.push(` ${f.title.padEnd(w)} ${cost(f).padStart(cw)} ${f.basis.padEnd(9)} ${f.rule}`);
|
|
498
|
+
if (sessions < 20)
|
|
499
|
+
lines.push('', `Only ${sessions} sessions: some checks wait for 20 sessions over 14 days before calling anything unused.`);
|
|
500
|
+
if (!opts.all) {
|
|
501
|
+
lines.push('', `Start here: ${short(ranked[0].fix)}`, '', 'Evidence and every fix: chompyy detect --all');
|
|
502
|
+
return lines;
|
|
503
|
+
}
|
|
504
|
+
for (const f of ranked) {
|
|
505
|
+
lines.push('', `${f.rule} · ${f.title} (${f.basis}${f.tokensHow ? `: ${f.tokensHow}` : ''})`, ` ${f.say}`);
|
|
506
|
+
if (f.notProve)
|
|
507
|
+
lines.push(` What this doesn't prove: ${f.notProve}`);
|
|
508
|
+
lines.push(` Fix (${f.lane}): ${f.fix}`);
|
|
509
|
+
}
|
|
510
|
+
return lines;
|
|
511
|
+
}
|
package/dist/pacing.js
CHANGED
|
@@ -9,6 +9,7 @@
|
|
|
9
9
|
// The burn rate comes from a small history of quota readings (quota-history.json), saved whenever the snapshot
|
|
10
10
|
// changes, so no extra calls are made.
|
|
11
11
|
import { homePath, readJson, writeJson } from './home.js';
|
|
12
|
+
import { archiveWindowEnds } from './premise.js';
|
|
12
13
|
import { windowView } from './quota.js';
|
|
13
14
|
export const FIVE_HOURS = 5 * 3600_000;
|
|
14
15
|
export const WEEK = 7 * 24 * 3600_000;
|
|
@@ -34,6 +35,10 @@ export function recordSample(snap, nowMs = Date.parse(snap.capturedAt)) {
|
|
|
34
35
|
return false; // out of order
|
|
35
36
|
samples.push({ at: nowMs, ...(snap.fiveHour ? { five: snap.fiveHour } : {}), ...(snap.sevenDay ? { week: snap.sevenDay } : {}) });
|
|
36
37
|
writeJson(historyPath(), { samples: samples.filter((s) => s.at > nowMs - KEEP_MS) });
|
|
38
|
+
try {
|
|
39
|
+
archiveWindowEnds(samples, nowMs); // windows that ended, kept beyond the 8 days (premise.ts)
|
|
40
|
+
}
|
|
41
|
+
catch { }
|
|
37
42
|
return true;
|
|
38
43
|
}
|
|
39
44
|
// ---------- pace delta ----------
|
package/dist/premise.js
ADDED
|
@@ -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/package.json
CHANGED