limitcast 0.14.0 → 0.16.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/src/trim.mjs CHANGED
@@ -2,6 +2,7 @@
2
2
  import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs';
3
3
  import { homedir } from 'node:os';
4
4
  import { join } from 'node:path';
5
+ import { memoryDir } from './memory.mjs';
5
6
  import { fmt } from './report.mjs';
6
7
 
7
8
  /** @typedef {import('./usage.mjs').Usage} Usage */
@@ -50,7 +51,7 @@ export function contributors({ home = homedir(), cwd = process.cwd() } = {}) {
50
51
  file(join(claudeDir, 'CLAUDE.md'), 'Global CLAUDE.md');
51
52
  if (cwd !== home) file(join(cwd, 'CLAUDE.md'), 'Project CLAUDE.md');
52
53
  file(join(home, 'CLAUDE.md'), 'Home CLAUDE.md');
53
- file(join(claudeDir, 'projects', cwd.replace(/[^A-Za-z0-9]/g, '-'), 'memory', 'MEMORY.md'), 'Auto-memory index');
54
+ file(join(memoryDir({ home, cwd }), 'MEMORY.md'), 'Auto-memory index');
54
55
  files.sort((a, b) => b.tokens - a.tokens);
55
56
 
56
57
  const overrides = readJson(join(claudeDir, 'settings.json'))?.skillOverrides ?? {};
@@ -148,14 +149,14 @@ export function trimReport(base, c, used, days) {
148
149
  const lines = ['# limitcast trim', ''];
149
150
  if (base) {
150
151
  lines.push(
151
- `Every Claude Code session starts at **${fmt(base.median)} tokens** before your first message (median of ${base.sessions} interactive sessions, max ${fmt(base.max)}).`,
152
+ `Your recorded Claude Code sessions start at **${fmt(base.median)} tokens** before your first message (median of ${base.sessions} interactive sessions, max ${fmt(base.max)}).`,
152
153
  'That context is re-sent on every turn and to every subagent, so every token you cut stretches your limit windows.',
153
154
  '',
154
155
  );
155
156
  } else lines.push('No interactive Claude Code sessions in the period yet.', '');
156
157
 
157
158
  const pct = base && s.skillTokens ? ` (${Math.round((s.skillTokens / base.median) * 100)}% of your fixed overhead)` : '';
158
- lines.push(`## Measured savings: ~${fmt(s.skillTokens)} tokens per session${pct}`, '');
159
+ lines.push(`## Estimated removable context: ~${fmt(s.skillTokens)} tokens per session${pct}`, '');
159
160
  if (s.unusedSkills.length) {
160
161
  const names = s.unusedSkills.slice(0, 12).map((k) => k.name);
161
162
  lines.push(
@@ -235,13 +236,18 @@ export function startupReport(base, b, used, days, keep = []) {
235
236
  const lines = ['# limitcast trim', ''];
236
237
  if (base) {
237
238
  lines.push(
238
- `Every Claude Code session starts at **${fmt(median)} tokens** before your first message (median of ${base.sessions} interactive sessions).`,
239
+ `Your recorded Claude Code sessions start at **${fmt(median)} tokens** before your first message (median of ${base.sessions} interactive sessions).`,
239
240
  'That context is re-sent on every turn and to every subagent, so every token you cut stretches your limit windows.',
240
241
  '',
241
242
  );
242
243
  }
243
244
  const pct = median ? ` (${Math.round((s.tokens / median) * 100)}% of your starting context)` : '';
244
- lines.push(`## Measured savings: ~${fmt(s.tokens)} tokens per session${pct}`, '', `From things you haven't used in the last ${days} days:`, '');
245
+ lines.push(
246
+ `## Estimated removable context: ~${fmt(s.tokens)} tokens per session${pct}`,
247
+ '',
248
+ `From things you haven't used in the last ${days} days:`,
249
+ '',
250
+ );
245
251
  if (s.unusedMcp.length) {
246
252
  const total = s.unusedMcp.reduce((a, m) => a + m.chars, 0);
247
253
  lines.push(
package/src/value.mjs CHANGED
@@ -13,10 +13,10 @@ import { claudeUsage } from './usage.mjs';
13
13
 
14
14
  /** @typedef {import('./forecast.mjs').Sample} Sample */
15
15
  /** @typedef {import('./results.mjs').Block} Block */
16
- /** @typedef {{at:number, turns:number, savedPerTurn:number}} SessionValue savedPerTurn: tokens below the first measured start */
16
+ /** @typedef {{at:number, turns:number, savedPerTurn:number, calls?:number[]}} SessionValue calls: main-thread timestamps; absent in legacy records */
17
17
  /** @typedef {{src:string, win:string, at:number, lead:number|null, unseen:boolean}} HitValue lead: minutes of warning */
18
18
  /** @typedef {{t:number, src:string, win:string, shadow:boolean, outcome:string}} BlockValue */
19
- /** @typedef {{since:number, scanned:number, sessions:Record<string, SessionValue>, hits:Record<string, HitValue>, blocks:Record<string, BlockValue>, switches?:Record<string, {shadow:boolean}>, calib?:{fresh:number, read:number, n:number, at:number}, calibHistory?:{fresh:number, read:number, n:number, at:number}[], limitChange?:{from:number, to:number, at:number}}} Value
19
+ /** @typedef {{since:number, contextSince?:number, scanned:number, sessions:Record<string, SessionValue>, hits:Record<string, HitValue>, blocks:Record<string, BlockValue>, switches?:Record<string, {shadow:boolean}>, calib?:{fresh:number, read:number, n:number, at:number}, calibHistory?:{fresh:number, read:number, n:number, at:number}[], limitChange?:{from:number, to:number, at:number}}} Value
20
20
  * calibHistory: one calibration of the last 3 days per day, to notice limit changes */
21
21
 
22
22
  const file = () => join(stateDir(), 'value.json');
@@ -102,13 +102,13 @@ export async function sessionValue(path, baselineChars) {
102
102
  if (b.entry !== 'cli' || !b.pieces.length) return null;
103
103
  const chars = b.pieces.reduce((a, p) => a + p.chars, 0);
104
104
  const seen = new Set();
105
- let turns = 0;
105
+ const calls = [];
106
106
  const rl = createInterface({ input: createReadStream(path), crlfDelay: Infinity });
107
107
  for await (const line of rl) {
108
108
  const u = claudeUsage(line, seen, '');
109
- if (u && !u.sidechain) turns++;
109
+ if (u && !u.sidechain) calls.push(u.t);
110
110
  }
111
- return { at: b.at, turns, savedPerTurn: Math.max(0, tok(baselineChars - chars)) };
111
+ return { at: b.at, turns: calls.length, savedPerTurn: Math.max(0, tok(baselineChars - chars)), calls };
112
112
  }
113
113
 
114
114
  /**
@@ -118,6 +118,7 @@ export async function sessionValue(path, baselineChars) {
118
118
  */
119
119
  export async function scanSessions(v, { root, baseline, now }) {
120
120
  if (!baseline) return v;
121
+ v.contextSince ??= baseline.at;
121
122
  try {
122
123
  for (const proj of readdirSync(root, { withFileTypes: true })) {
123
124
  if (!proj.isDirectory()) continue;
@@ -125,9 +126,11 @@ export async function scanSessions(v, { root, baseline, now }) {
125
126
  if (!f.isFile() || !f.name.endsWith('.jsonl')) continue;
126
127
  const p = join(root, proj.name, f.name);
127
128
  const st = statSync(p);
128
- if (st.mtimeMs < Math.max(baseline.at, v.scanned) || (st.birthtimeMs || st.mtimeMs) < baseline.at - 86400_000) continue;
129
+ const id = f.name.replace(/\.jsonl$/, '');
130
+ const legacy = v.sessions[id] && !Array.isArray(v.sessions[id].calls);
131
+ if ((!legacy && st.mtimeMs < Math.max(baseline.at, v.scanned)) || (st.birthtimeMs || st.mtimeMs) < baseline.at - 86400_000) continue;
129
132
  const s = await sessionValue(p, baseline.chars);
130
- if (s && s.at >= baseline.at) v.sessions[f.name.replace(/\.jsonl$/, '')] = s;
133
+ if (s && s.at >= baseline.at) v.sessions[id] = s;
131
134
  }
132
135
  }
133
136
  } catch {
@@ -168,6 +171,29 @@ export function valueTotals(v) {
168
171
  };
169
172
  }
170
173
 
174
+ /** Activity in an exact half-open period; never assign an entire session to its start week.
175
+ * @param {Value} v
176
+ * @param {number} since
177
+ * @param {number} until
178
+ */
179
+ export function valuePeriod(v, since, until) {
180
+ let calls = 0;
181
+ let tokens = 0;
182
+ let sessions = 0;
183
+ let legacy = 0;
184
+ for (const s of Object.values(v.sessions)) {
185
+ if (!Array.isArray(s.calls)) {
186
+ if (s.at < until) legacy++;
187
+ continue;
188
+ }
189
+ const n = s.calls.filter((t) => t >= since && t < until).length;
190
+ if (n) sessions++;
191
+ calls += n;
192
+ tokens += n * s.savedPerTurn;
193
+ }
194
+ return { calls, tokens, sessions, legacy };
195
+ }
196
+
171
197
  /**
172
198
  * The "since you installed" section at the top of `limitcast results`.
173
199
  * @param {ReturnType<typeof valueTotals>} t
@@ -177,21 +203,21 @@ export function valueSection(t, { now, pro }) {
177
203
  if (!t.since) return '';
178
204
  const days = Math.max(1, Math.round((now - t.since) / 86400_000));
179
205
  const out = [`## Since limitcast started watching (${new Date(t.since).toLocaleDateString()}, ${days} day${days === 1 ? '' : 's'})`];
180
- if (t.tokens > 0) {
206
+ if (pro && t.tokens > 0) {
181
207
  out.push(
182
- `- **${fmtBig(t.tokens)} tokens not re-sent.** Your sessions now start smaller than the first one limitcast measured, and Claude Code re-sends the starting context on every model call: ${t.turns.toLocaleString()} calls across ${t.sessions} sessions. (Most of it would have been cached input.)`,
208
+ `- **Estimated ${fmtBig(t.tokens)} context tokens not re-sent.** Compared with your first recorded Claude Code starting context: ${t.turns.toLocaleString()} calls across ${t.sessions} sessions. Estimated from characters / 4; most would have been cached input. Project or manual configuration changes can also change this baseline; this is not a causal savings measurement.`,
183
209
  );
184
210
  if (t.windowPct !== null && t.calib)
185
211
  out.push(
186
212
  ` Against your limit: **≈ ${t.windowPct < 1 ? t.windowPct.toFixed(2) : t.windowPct.toFixed(1)}% of a 5-hour window.** From your own readings, 1% of it is about ${fmtBig(Math.round(1e6 / t.calib.fresh))} new tokens or ${fmtBig(Math.round(1e6 / t.calib.read))} cached ones, so cached context is cheap and new tokens (long sessions, subagents) are what run you out.`,
187
213
  );
188
- } else if (t.sessions) {
214
+ } else if (pro && t.sessions) {
189
215
  out.push(`- Starting context: no smaller than when limitcast first measured it. \`limitcast trim\` shows what to cut.`);
190
216
  }
191
217
  if (t.hits) {
192
218
  const avg = t.leads.length ? `, on average ${fmtMin(t.leads.reduce((a, b) => a + b, 0) / t.leads.length)} ahead` : '';
193
219
  out.push(
194
- `- **Warned you before ${t.leads.length} of the ${t.watched} limits it watched you approach**${avg}. (${t.hits} limits reached in all.)`,
220
+ `- **Forecast risk before ${t.leads.length} of the ${t.watched} limits it watched you approach**${avg}. (${t.hits} limits reached in all; replayed from recorded readings, not proof a notification was delivered.)`,
195
221
  );
196
222
  } else out.push('- No limit reached yet.');
197
223
  if (pro) {