limitcast 0.15.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/guard.mjs CHANGED
@@ -64,6 +64,7 @@ function blockingForecast(tool, forecasts, now, minutes) {
64
64
  export async function runGuard(hook, now, minutes, { preview = false } = {}) {
65
65
  const tool = String(hook?.tool_name ?? hook?.toolName ?? hook?.tool ?? '');
66
66
  const src = spawnSource(tool);
67
+ const operation = hook?.tool_use_id ?? hook?.toolUseId ?? hook?.call_id;
67
68
  // Codex: only the last two hours of rollouts, so the hook stays fast. Grok: spend vs the user's dollar cap.
68
69
  const samples =
69
70
  src === 'claude'
@@ -81,6 +82,7 @@ export async function runGuard(hook, now, minutes, { preview = false } = {}) {
81
82
  const sid = f.src === 'claude' ? samples.find((s) => s.src === 'claude' && s.sid)?.sid : undefined;
82
83
  try {
83
84
  logBlock({
85
+ ...(typeof operation === 'string' ? { operation } : {}),
84
86
  t: now,
85
87
  src: f.src,
86
88
  win: f.win,
@@ -102,6 +104,7 @@ export async function runGuard(hook, now, minutes, { preview = false } = {}) {
102
104
  if (day && (preview || getTodayHold())) {
103
105
  try {
104
106
  logBlock({
107
+ ...(typeof operation === 'string' ? { operation } : {}),
105
108
  t: now,
106
109
  kind: 'today',
107
110
  src: day.src,
@@ -126,6 +129,7 @@ export async function runGuard(hook, now, minutes, { preview = false } = {}) {
126
129
  if (spent >= budget) {
127
130
  try {
128
131
  logBlock({
132
+ ...(typeof operation === 'string' ? { operation } : {}),
129
133
  t: now,
130
134
  kind: 'budget',
131
135
  src: 'claude',
@@ -147,13 +151,14 @@ export async function runGuard(hook, now, minutes, { preview = false } = {}) {
147
151
  const tight = forecasts.find((x) => x.src === 'claude' && (x.verdict === 'AT_RISK' || x.verdict === 'NEAR'));
148
152
  const type = String(input?.subagent_type ?? input?.subagentType ?? '');
149
153
  const pinned = isUnset(input?.model) && type ? pinnedModel(type) : undefined;
150
- if (src === 'grok') return grokPinOrNotice(input, type, pinned, forecasts, now, preview);
154
+ if (src === 'grok') return grokPinOrNotice(input, type, pinned, forecasts, now, preview, operation);
151
155
  if (src !== 'claude') return null;
152
156
  const model = pinned ?? input?.model;
153
157
  if (!tight || !switchable(model)) {
154
158
  if (pinned) {
155
159
  try {
156
160
  logBlock({
161
+ ...(typeof operation === 'string' ? { operation } : {}),
157
162
  t: now,
158
163
  kind: 'default',
159
164
  src: 'claude',
@@ -183,6 +188,7 @@ export async function runGuard(hook, now, minutes, { preview = false } = {}) {
183
188
  }
184
189
  try {
185
190
  logBlock({
191
+ ...(typeof operation === 'string' ? { operation } : {}),
186
192
  t: now,
187
193
  kind: 'switch',
188
194
  src: 'claude',
@@ -238,13 +244,15 @@ const isUnset = (model) => model === undefined || model === null || model === ''
238
244
  * @param {ReturnType<typeof import('./forecast.mjs').forecastAll>} forecasts
239
245
  * @param {number} now
240
246
  * @param {boolean} preview
247
+ * @param {unknown} operation
241
248
  */
242
- function grokPinOrNotice(input, type, pinned, forecasts, now, preview) {
249
+ function grokPinOrNotice(input, type, pinned, forecasts, now, preview, operation) {
243
250
  const grokPin = pinned && /^grok-/i.test(pinned) ? pinned : undefined;
244
251
  const hasModelField = input && typeof input === 'object' && Object.hasOwn(input, 'model');
245
252
  if (grokPin && hasModelField) {
246
253
  try {
247
254
  logBlock({
255
+ ...(typeof operation === 'string' ? { operation } : {}),
248
256
  t: now,
249
257
  kind: 'default',
250
258
  src: 'grok',
@@ -0,0 +1,127 @@
1
+ // @ts-check
2
+ import { fmtBig, valuePeriod } from './value.mjs';
3
+
4
+ const DAY = 86400_000;
5
+ const ACTIONS = {
6
+ hold: 'Forecast holds',
7
+ budget: 'Subagent-budget holds',
8
+ today: 'Daily-share holds',
9
+ switch: 'Tight-window model changes',
10
+ default: 'Per-type model choices',
11
+ cold: 'Cold-cache holds',
12
+ };
13
+
14
+ /** Totals without prompts, projects, paths, account names or session IDs.
15
+ * @param {{value:import('./value.mjs').Value, usage:import('./usage.mjs').Usage[], blocks:import('./results.mjs').Block[], since:number, until:number}} r
16
+ */
17
+ export function periodInsights({ value, usage, blocks, since, until }) {
18
+ const current = usage.filter((u) => u.t >= since && u.t < until);
19
+ const providers = ['claude', 'codex', 'grok'].map((src) => {
20
+ const mine = current.filter((u) => u.src === src);
21
+ return {
22
+ src,
23
+ calls: mine.length,
24
+ activeDays: new Set(mine.map((u) => new Date(u.t).toISOString().slice(0, 10))).size,
25
+ fresh: mine.reduce((n, u) => n + u.input + u.cacheWrite, 0),
26
+ read: mine.reduce((n, u) => n + u.cacheRead, 0),
27
+ output: mine.reduce((n, u) => n + u.output, 0),
28
+ };
29
+ });
30
+ const seen = new Set();
31
+ const actions = Object.fromEntries(Object.keys(ACTIONS).map((kind) => [kind, { actual: 0, preview: 0 }]));
32
+ let attempts = 0;
33
+ for (const b of blocks.filter((b) => b.t >= since && b.t < until)) {
34
+ const kind = b.kind ?? 'hold';
35
+ if (!actions[kind]) continue;
36
+ // Older hooks have no operation ID: retain and label their attempts instead of guessing duplicates.
37
+ const key = b.operation ? JSON.stringify([b.src, b.sid, b.operation, Boolean(b.shadow)]) : null;
38
+ if (key && seen.has(key)) continue;
39
+ if (key) seen.add(key);
40
+ else attempts++;
41
+ actions[kind][b.shadow ? 'preview' : 'actual']++;
42
+ }
43
+ const previous = valuePeriod(value, since - (until - since), since);
44
+ const context = valuePeriod(value, since, until);
45
+ const comparison =
46
+ value.contextSince && value.contextSince <= since - (until - since) && !context.legacy && !previous.legacy ? previous.tokens : null;
47
+ return {
48
+ since,
49
+ until,
50
+ days: (until - since) / DAY,
51
+ providers,
52
+ actions,
53
+ attempts,
54
+ context,
55
+ contextAvailable: Number.isFinite(value.contextSince),
56
+ previousContext: comparison,
57
+ };
58
+ }
59
+
60
+ /** @param {ReturnType<typeof periodInsights>} r @param {boolean} pro */
61
+ export function insightsReport(r, pro) {
62
+ const out = [
63
+ '## Your capacity report',
64
+ '',
65
+ `${new Date(r.since).toISOString()} to ${new Date(r.until).toISOString()} (UTC; activity timestamps).`,
66
+ '',
67
+ '| Tool | New input + cache writes | Cached reads | Output | Active days |',
68
+ '|---|---:|---:|---:|---:|',
69
+ ];
70
+ for (const p of r.providers) out.push(`| ${p.src} | ${fmtBig(p.fresh)} | ${fmtBig(p.read)} | ${fmtBig(p.output)} | ${p.activeDays} |`);
71
+ out.push('', 'Usage above is recorded consumption, not savings. No recorded activity does not prove a tool was unused.');
72
+ if (pro) {
73
+ if (r.contextAvailable)
74
+ out.push(
75
+ '',
76
+ `Claude context reduction: **estimated ${fmtBig(r.context.tokens)} input tokens not re-sent** across ${r.context.calls} calls in this period, relative to your first recorded starting context (characters / 4).`,
77
+ );
78
+ else out.push('Claude context reduction: unavailable. Run `limitcast trim` to record a baseline before estimating avoided input.');
79
+ out.push(
80
+ 'This estimate can include project or manual configuration changes. It is not proof that Limitcast caused the reduction. Codex/Grok context savings: unavailable.',
81
+ );
82
+ if (r.context.legacy) out.push(`${r.context.legacy} legacy session record(s) lack timestamps and are excluded from this period estimate.`);
83
+ if (r.previousContext !== null)
84
+ out.push(`Previous equal period: estimated ${fmtBig(r.previousContext)} context tokens not re-sent. Neither figure measures cash savings.`);
85
+ else out.push('Previous-period comparison: unavailable until two complete periods have been observed.');
86
+ }
87
+ out.push('', '| Protection event | Applied | Historical preview: would have acted |', '|---|---:|---:|');
88
+ for (const [kind, label] of Object.entries(ACTIONS)) out.push(`| ${label} | ${r.actions[kind].actual} | ${r.actions[kind].preview} |`);
89
+ out.push(
90
+ '',
91
+ `Operation IDs deduplicate retries when supplied. ${r.attempts} older/unidentified event(s) are recorded attempts. Holds and warnings are not measured saved tokens or proven prevented interruptions.`,
92
+ );
93
+ out.push('', '### What to do next');
94
+ const claude = r.providers[0];
95
+ const held = Object.values(r.actions).reduce((n, a) => n + a.actual, 0);
96
+ const previewed = Object.values(r.actions).reduce((n, a) => n + a.preview, 0);
97
+ if (!r.providers.some((p) => p.calls)) out.push('- Run `limitcast onboard` to check setup and the next useful step.');
98
+ else if (r.actions.cold.actual || r.actions.cold.preview)
99
+ out.push('- Before resuming a long idle Claude session, consider `/compact`; a warning alone does not reduce its input.');
100
+ else if (claude.fresh > 0)
101
+ out.push('- Run `limitcast report --why` to find the largest sources of new Claude tokens before changing a budget or model.');
102
+ else out.push('- Check `limitcast status` before a heavy run; each provider has its own limits.');
103
+ if (!held && !previewed)
104
+ out.push('- No protection actions recorded. `limitcast onboard` distinguishes missing setup from a period that needed no intervention.');
105
+ if (!pro && previewed)
106
+ out.push(
107
+ `- ${previewed} historical preview event(s) were recorded. All features are now free; enable protection with limitcast install --guard --alerts.`,
108
+ );
109
+ out.push('- Share voluntarily with `limitcast results --share`; nothing is uploaded automatically.');
110
+ return out.join('\n');
111
+ }
112
+
113
+ /** @param {ReturnType<typeof periodInsights>} r @param {boolean} pro */
114
+ export function insightsShare(r, pro) {
115
+ const parts = r.providers
116
+ .filter((p) => p.calls)
117
+ .map(
118
+ (p) =>
119
+ `${p.src}: ${p.activeDays} UTC active days, ${fmtBig(p.fresh)} new input/write, ${fmtBig(p.read)} cached, ${fmtBig(p.output)} output tokens`,
120
+ );
121
+ const actual = Object.values(r.actions).reduce((n, a) => n + a.actual, 0);
122
+ const preview = Object.values(r.actions).reduce((n, a) => n + a.preview, 0);
123
+ parts.push(`${actual} applied protection events; ${preview} historical-preview events (${r.attempts} unidentified attempts)`);
124
+ if (pro && r.contextAvailable) parts.push(`estimated ${fmtBig(r.context.tokens)} Claude context tokens not re-sent this period vs baseline`);
125
+ if (pro && !r.contextAvailable) parts.push('Claude context estimate unavailable');
126
+ return `Voluntary capacity check-in, ${r.days} days: ${parts.join('; ')}. No prompts, project names or account IDs. https://limitcast.dev`;
127
+ }
package/src/install.mjs CHANGED
@@ -280,11 +280,11 @@ function codexGuardCheck(codexPath) {
280
280
  }
281
281
 
282
282
  /**
283
- * Health checks: settings wired, the node path in them still exists, data arriving, license state.
284
- * @param {{path?:string, codexPath?:string, samplesAgeMs:number|null, license:ReturnType<typeof import('./license.mjs').currentLicense>}} info
283
+ * Health checks: settings wired, the node path in them still exists, data arriving, and the free distribution.
284
+ * @param {{path?:string, codexPath?:string, samplesAgeMs:number|null, license?:ReturnType<typeof import('./license.mjs').currentLicense>}} info
285
285
  * @returns {{ok:boolean, line:string}[]}
286
286
  */
287
- export function doctor({ path = settingsPath(), codexPath = codexHooksPath(), samplesAgeMs, license }) {
287
+ export function doctor({ path = settingsPath(), codexPath = codexHooksPath(), samplesAgeMs }) {
288
288
  /** @type {{ok:boolean, line:string}[]} */
289
289
  const out = [];
290
290
  const major = Number(process.versions.node.split('.')[0]);
@@ -332,7 +332,7 @@ export function doctor({ path = settingsPath(), codexPath = codexHooksPath(), sa
332
332
  const newer = (hooks.UserPromptSubmit ?? []).some(isPromptCheck) && (hooks.SubagentStop ?? []).some(isReceipt);
333
333
  if (guard && !newer)
334
334
  out.push({
335
- ok: !license?.ok,
335
+ ok: false,
336
336
  line: 'Cold-cache warning and subagent receipts not installed yet: run `limitcast doctor --fix`',
337
337
  });
338
338
  if (existsSync(codexPath)) out.push(codexGuardCheck(codexPath));
@@ -343,16 +343,8 @@ export function doctor({ path = settingsPath(), codexPath = codexHooksPath(), sa
343
343
  : { ok: samplesAgeMs < 24 * 3600_000, line: `Last Claude reading ${Math.round(samplesAgeMs / 60_000)} min ago` },
344
344
  );
345
345
  out.push({
346
- ok: license?.ok !== false,
347
- line: license === null ? 'Free tier' : license.ok ? `Pro: ${license.claims.e}${proTerm(license.claims)}` : `License problem: ${license.reason}`,
346
+ ok: true,
347
+ line: 'Free and open source (MIT License); all features available',
348
348
  });
349
349
  return out;
350
350
  }
351
-
352
- /** @param {{p:string, i:number, x:number}} c */
353
- function proTerm(c) {
354
- const day = (/** @type {number} */ s) => new Date(s * 1000).toISOString().slice(0, 10);
355
- if (c.x) return `, ${c.p === 'polar' ? 'valid until' : 'renews'} ${day(c.x)}`;
356
- // A Polar key has no end date for Lifetime or an active subscription; the weekly check is what keeps it honest.
357
- return c.p === 'polar' ? `, last checked with Polar ${day(c.i)}` : ', lifetime';
358
- }
package/src/license.mjs CHANGED
@@ -69,7 +69,8 @@ export function activate(key) {
69
69
  return res;
70
70
  }
71
71
 
72
- export const isPro = () => currentLicense()?.ok === true || trialStatus()?.active === true;
72
+ // Compatibility for old integrations; feature access no longer depends on billing state.
73
+ export const isPro = () => true;
73
74
 
74
75
  const TRIAL_MS = 7 * 86400_000;
75
76
  const trialFile = () => join(stateDir(), 'trial.json');
package/src/notify.mjs CHANGED
@@ -2,7 +2,6 @@
2
2
  import { spawn, spawnSync } from 'node:child_process';
3
3
  import { appendFileSync, existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
4
4
  import { join } from 'node:path';
5
- import { isPro } from './license.mjs';
6
5
  import { stateDir } from './store.mjs';
7
6
 
8
7
  // Desktop notifications (Pro, opt-in): one per change of state, raised from the status line.
@@ -97,7 +96,7 @@ export function notifyChanges(rows, clock) {
97
96
  export function send(message) {
98
97
  // Pro: the same message to the phone (ntfy) or a chat webhook, by a detached curl so no hook waits on the network.
99
98
  try {
100
- if (isPro()) for (const a of remoteArgs(loadChannels(), message)) run('curl', a);
99
+ for (const a of remoteArgs(loadChannels(), message)) run('curl', a);
101
100
  } catch {
102
101
  /* a broken channel config must not stop the desktop notification */
103
102
  }
@@ -0,0 +1,46 @@
1
+ // @ts-check
2
+
3
+ /** Read-only guidance; installation and cuts always remain explicit commands.
4
+ * @param {{checks:{ok:boolean,line:string}[], features:{statusLine:boolean,guard:boolean,alerts:boolean}, contextTokens:number|null, providers:string[]}} r
5
+ */
6
+ export function onboardingReport({ checks, features, contextTokens, providers }) {
7
+ const out = [
8
+ '# Get started with limitcast',
9
+ '',
10
+ `Found local setup/logs for: ${providers.join(', ') || 'none yet'}.`,
11
+ 'Free and open source (MIT License). All features are available without an account, license key or trial.',
12
+ '',
13
+ '## Setup checks',
14
+ ];
15
+ for (const c of checks) out.push(`- ${c.ok ? 'OK' : 'Needs attention'}: ${c.line}`);
16
+ out.push('', '## Your next step');
17
+ if (!features.statusLine)
18
+ out.push('1. Run `limitcast install` to back up settings and add the recorder. Restart your coding tool, then run `limitcast doctor`.');
19
+ else out.push('1. Run `limitcast status` for your current windows. No readings yet? Restart your tool and complete one normal turn.');
20
+ if (contextTokens !== null)
21
+ out.push(
22
+ `2. Your latest Claude starting context contains about ${Math.round(contextTokens).toLocaleString('en-US')} tokens of controllable setup. Run limitcast trim to inspect unused items.`,
23
+ );
24
+ else
25
+ out.push(
26
+ '2. After a normal session, run `limitcast trim` (Claude), `limitcast trim --codex`, or `limitcast trim --grok` for a personal finding. Doctor checks setup; Trim analyzes context.',
27
+ );
28
+ if (!features.guard || !features.alerts)
29
+ out.push(
30
+ '3. Run limitcast install --guard --alerts to configure protection and weekly summaries. Restart; approve the Codex hook if asked. Run limitcast doctor to check configuration.',
31
+ );
32
+ else
33
+ out.push(
34
+ 'Protection is configured. Configuration is not proof of a live block: confirm the hook is loaded in your coding tool; review real events with `limitcast results`.',
35
+ );
36
+ out.push(
37
+ '',
38
+ '## Stay in control',
39
+ '- Inspect first. Add essential servers/skills with `limitcast trim keep <name>` before choosing `trim --apply`. Undo with `limitcast trim --undo` (add `--codex` or `--grok` for that tool).',
40
+ '- The guard holds new spawns; it does not cancel existing agents or guarantee no lockouts. `LIMITCAST_ALLOW=1` bypasses a hold for a command/session; unset it to restore protection.',
41
+ '- Grok needs an explicit dollar cap for blocking: `limitcast budget grok <usd>`. Claude model defaults/budgets and cold-cache notices do not have identical support in every host.',
42
+ '- In a week, run `limitcast results`. It separates usage, estimated context reduction, applied controls and historical previews. Share totals voluntarily with `limitcast results --share`.',
43
+ '- Nothing here changes settings or uploads usage. `limitcast uninstall` restores the recorder setup; trim changes have their own undo.',
44
+ );
45
+ return out.join('\n');
46
+ }
package/src/pilot.mjs ADDED
@@ -0,0 +1,92 @@
1
+ // @ts-check
2
+ const DAY = 86400_000;
3
+
4
+ /** Local operator-entered evidence only. Missing follow-up is unknown, never invented churn.
5
+ * @param {unknown} input
6
+ * @param {number} now
7
+ */
8
+ export function pilotMetrics(input, now) {
9
+ if (!Array.isArray(input) || !Number.isFinite(now)) throw new Error('Expected a participant array and a valid as-of timestamp.');
10
+ const ids = new Set();
11
+ const date = (value, field) => {
12
+ if (value === undefined || value === null) return null;
13
+ if (typeof value !== 'string' || !/^\d{4}-\d{2}-\d{2}T.*Z$/.test(value) || !Number.isFinite(Date.parse(value)))
14
+ throw new Error(`Invalid UTC timestamp: ${field}`);
15
+ const parsed = Date.parse(value);
16
+ if (new Date(parsed).toISOString().slice(0, 10) !== value.slice(0, 10)) throw new Error(`Invalid UTC timestamp: ${field}`);
17
+ return parsed;
18
+ };
19
+ const people = [];
20
+ for (const p of input) {
21
+ if (!p || typeof p !== 'object' || typeof p.id !== 'string' || !p.id || ids.has(p.id))
22
+ throw new Error('Each participant needs a unique nonempty id.');
23
+ ids.add(p.id);
24
+ if (p.consent !== true) continue;
25
+ const invited = date(p.invitedAt, 'invitedAt');
26
+ if (invited === null) throw new Error('A consenting participant needs invitedAt.');
27
+ const activated = date(p.activatedAt, 'activatedAt');
28
+ const paid = date(p.paidAt, 'paidAt');
29
+ const due = date(p.renewalDueAt, 'renewalDueAt');
30
+ const renewed = date(p.renewedAt, 'renewedAt');
31
+ if (activated !== null && activated < invited) throw new Error('activatedAt precedes invitedAt.');
32
+ if (due !== null && (paid === null || due <= paid)) throw new Error('renewalDueAt needs an earlier paidAt.');
33
+ if (renewed !== null && (due === null || renewed < due)) throw new Error('renewedAt needs a reached renewalDueAt.');
34
+ if (p.checkIns !== undefined && !Array.isArray(p.checkIns)) throw new Error('checkIns must be an array.');
35
+ const checks = (p.checkIns ?? [])
36
+ .map((c) => {
37
+ if (!c || typeof c !== 'object' || typeof c.active !== 'boolean' || typeof c.protectionEnabled !== 'boolean' || typeof c.useful !== 'boolean')
38
+ throw new Error('Each check-in needs active, protectionEnabled and useful booleans.');
39
+ const at = date(c.at, 'checkIns.at');
40
+ if (at === null || activated === null || at < activated) throw new Error('A check-in needs an activation and a later timestamp.');
41
+ return { ...c, at };
42
+ })
43
+ .filter((c) => c.at <= now)
44
+ .sort((a, b) => b.at - a.at);
45
+ if (invited <= now)
46
+ people.push({
47
+ activated: activated !== null && activated <= now ? activated : null,
48
+ paid: p.paymentVerified === true && paid !== null && paid <= now,
49
+ due,
50
+ renewed: p.renewalVerified === true && renewed !== null && renewed <= now,
51
+ checks,
52
+ });
53
+ }
54
+ const retention = (day) => {
55
+ const eligible = people.filter((p) => p.activated !== null && now >= p.activated + day * DAY);
56
+ let retained = 0;
57
+ let inactive = 0;
58
+ for (const p of eligible) {
59
+ const c = p.checks.find((c) => c.at >= p.activated + day * DAY && c.at < p.activated + (day + 7) * DAY);
60
+ if (c?.active === true) retained++;
61
+ if (c?.active === false) inactive++;
62
+ }
63
+ return {
64
+ eligible: eligible.length,
65
+ retained,
66
+ inactive,
67
+ unknown: eligible.length - retained - inactive,
68
+ confirmedFraction: eligible.length ? retained / eligible.length : null,
69
+ };
70
+ };
71
+ const recent = people.flatMap((p) => (p.checks[0]?.at >= now - 7 * DAY ? [p.checks[0]] : []));
72
+ const renewals = people.filter((p) => p.paid && p.due !== null && p.due <= now);
73
+ return {
74
+ asOf: new Date(now).toISOString(),
75
+ consentingInvited: people.length,
76
+ activated: people.filter((p) => p.activated !== null).length,
77
+ verifiedPaid: people.filter((p) => p.paid).length,
78
+ day7: retention(7),
79
+ day30: retention(30),
80
+ recentCheckIns: {
81
+ observed: recent.length,
82
+ protectionEnabled: recent.filter((c) => c.protectionEnabled).length,
83
+ useful: recent.filter((c) => c.useful).length,
84
+ },
85
+ renewals: {
86
+ eligible: renewals.length,
87
+ verified: renewals.filter((p) => p.renewed).length,
88
+ unconfirmed: renewals.filter((p) => !p.renewed).length,
89
+ },
90
+ note: 'Operator-recorded, consenting cohort only. Unknown follow-up is not churn; unconfirmed renewal is not a verified cancellation. Small cohorts do not establish market-wide demand.',
91
+ };
92
+ }
package/src/results.mjs CHANGED
@@ -5,7 +5,7 @@ import { claudeAccounts, forecast } from './forecast.mjs';
5
5
  import { stateDir } from './store.mjs';
6
6
 
7
7
  /** @typedef {import('./forecast.mjs').Sample} Sample */
8
- /** @typedef {{t:number, src:string, win:string, pct:number, wall:number, reset:number, sid?:string, shadow?:boolean, kind?:string, from?:string, to?:string, type?:string, tokens?:number}} Block t, wall, reset: epoch ms; shadow: a free install's preview, not acted on; kind "switch": a subagent moved to Sonnet instead of blocked, "budget": a subagent held over the budget, "cold": a message held after the prompt cache expired (pct: its cost, tokens: context re-sent), "today": a subagent held once today's share of a weekly window was used up (pct: used today); no kind: a forecast block */
8
+ /** @typedef {{t:number, src:string, win:string, pct:number, wall:number, reset:number, sid?:string, operation?:string, shadow?:boolean, kind?:string, from?:string, to?:string, type?:string, tokens?:number}} Block t, wall, reset: epoch ms; shadow: a free install's preview, not acted on; operation: host-supplied tool call ID when available; kind "switch": a subagent moved to Sonnet instead of blocked, "budget": a subagent held over the budget, "cold": a message held after the prompt cache expired (pct: its cost, tokens: context re-sent), "today": a subagent held once today's share of a weekly window was used up (pct: used today); no kind: a forecast block */
9
9
 
10
10
  const JITTER_MS = 120_000; // Codex resets_at drifts by seconds between events
11
11
  const NAMES = { claude: 'Claude', codex: 'Codex', grok: 'Grok' };
@@ -25,16 +25,32 @@ export function logBlock(b) {
25
25
  /** @param {number} since epoch ms @returns {Block[]} */
26
26
  export function loadBlocks(since) {
27
27
  if (!existsSync(blockFile())) return [];
28
- return readFileSync(blockFile(), 'utf8')
29
- .split('\n')
30
- .flatMap((line) => {
31
- try {
32
- const b = JSON.parse(line);
33
- return b.t >= since ? [b] : [];
34
- } catch {
35
- return [];
36
- }
37
- });
28
+ return distinctBlocks(
29
+ readFileSync(blockFile(), 'utf8')
30
+ .split('\n')
31
+ .flatMap((line) => {
32
+ try {
33
+ const b = JSON.parse(line);
34
+ return b.t >= since ? [b] : [];
35
+ } catch {
36
+ return [];
37
+ }
38
+ }),
39
+ );
40
+ }
41
+
42
+ /** Keep one decision per host operation and tier; unidentified legacy attempts remain visible.
43
+ * @param {Block[]} blocks
44
+ */
45
+ export function distinctBlocks(blocks) {
46
+ const seen = new Set();
47
+ return blocks.filter((b) => {
48
+ if (!b.operation) return true;
49
+ const key = JSON.stringify([b.src, b.sid, b.operation, Boolean(b.shadow)]);
50
+ if (seen.has(key)) return false;
51
+ seen.add(key);
52
+ return true;
53
+ });
38
54
  }
39
55
 
40
56
  /**
@@ -121,7 +137,7 @@ export function resultsStats({ now, days, samples, blocks, pro }) {
121
137
  const hits = limitHits(samples.filter((s) => s.t >= since));
122
138
  const watched = hits.filter((h) => !h.unseen);
123
139
  const leads = hits.flatMap((h) => (h.warnedAt === null ? [] : [Math.round((h.at - h.warnedAt) / 60_000)]));
124
- const mine = blocks.filter((b) => b.t >= since && Boolean(b.shadow) === !pro);
140
+ const mine = distinctBlocks(blocks).filter((b) => b.t >= since && b.t <= now && Boolean(b.shadow) === !pro);
125
141
  const outcomes = blockOutcomes(
126
142
  mine.filter((b) => !b.kind),
127
143
  samples,
@@ -162,7 +178,7 @@ export function resultsShare(st, { days, pro, savedPerSession, notResent = 0 })
162
178
  if (st.switches) parts.push(`${pro ? 'moved' : 'would have moved'} ${st.switches} subagent${st.switches === 1 ? '' : 's'} to Sonnet`);
163
179
  if (st.defaults) parts.push(`${pro ? 'ran' : 'would have run'} ${st.defaults} on the model you set for their type`);
164
180
  if (savedPerSession && savedPerSession > 0) parts.push(`starting context ${fmtK(savedPerSession)} tokens smaller per session`);
165
- if (notResent > 0) parts.push(`${fmtK(notResent)} tokens not re-sent since install`);
181
+ if (pro && notResent > 0) parts.push(`estimated ${fmtK(notResent)} context tokens not re-sent since install vs baseline`);
166
182
  return `${parts[0]} ${parts.slice(1).join('; ')}. https://limitcast.dev`;
167
183
  }
168
184
 
@@ -174,7 +190,7 @@ export function resultsShare(st, { days, pro, savedPerSession, notResent = 0 })
174
190
  */
175
191
  export function weeklyLine(st, savedPerSession, notResent = 0) {
176
192
  const parts = [`${st.hits.length} limit${st.hits.length === 1 ? '' : 's'} reached`];
177
- if (st.leads.length) parts.push(`warned ahead on ${st.leads.length} (avg ${avg(st.leads)} min)`);
193
+ if (st.leads.length) parts.push(`forecast risk on ${st.leads.length} (avg ${avg(st.leads)} min)`);
178
194
  parts.push(`guard blocked ${st.outcomes.length} subagent${st.outcomes.length === 1 ? '' : 's'}`);
179
195
  if (st.switches) parts.push(`moved ${st.switches} to Sonnet`);
180
196
  if (st.defaults) parts.push(`ran ${st.defaults} on their set model`);
@@ -182,7 +198,7 @@ export function weeklyLine(st, savedPerSession, notResent = 0) {
182
198
  if (st.todays) parts.push(`held ${st.todays} once today's share was used`);
183
199
  if (st.colds) parts.push(`caught ${st.colds} cold-cache message${st.colds === 1 ? '' : 's'}`);
184
200
  if (savedPerSession && savedPerSession > 0) parts.push(`starting context ${fmtK(savedPerSession)} tokens smaller`);
185
- if (notResent > 0) parts.push(`${fmtK(notResent)} tokens not re-sent`);
201
+ if (notResent > 0) parts.push(`estimated ${fmtK(notResent)} context tokens not re-sent vs baseline`);
186
202
  return `limitcast this week: ${parts.join(', ')}. Details: limitcast results`;
187
203
  }
188
204
 
package/src/trim.mjs CHANGED
@@ -149,14 +149,14 @@ export function trimReport(base, c, used, days) {
149
149
  const lines = ['# limitcast trim', ''];
150
150
  if (base) {
151
151
  lines.push(
152
- `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)}).`,
153
153
  'That context is re-sent on every turn and to every subagent, so every token you cut stretches your limit windows.',
154
154
  '',
155
155
  );
156
156
  } else lines.push('No interactive Claude Code sessions in the period yet.', '');
157
157
 
158
158
  const pct = base && s.skillTokens ? ` (${Math.round((s.skillTokens / base.median) * 100)}% of your fixed overhead)` : '';
159
- lines.push(`## Measured savings: ~${fmt(s.skillTokens)} tokens per session${pct}`, '');
159
+ lines.push(`## Estimated removable context: ~${fmt(s.skillTokens)} tokens per session${pct}`, '');
160
160
  if (s.unusedSkills.length) {
161
161
  const names = s.unusedSkills.slice(0, 12).map((k) => k.name);
162
162
  lines.push(
@@ -236,13 +236,18 @@ export function startupReport(base, b, used, days, keep = []) {
236
236
  const lines = ['# limitcast trim', ''];
237
237
  if (base) {
238
238
  lines.push(
239
- `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).`,
240
240
  'That context is re-sent on every turn and to every subagent, so every token you cut stretches your limit windows.',
241
241
  '',
242
242
  );
243
243
  }
244
244
  const pct = median ? ` (${Math.round((s.tokens / median) * 100)}% of your starting context)` : '';
245
- 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
+ );
246
251
  if (s.unusedMcp.length) {
247
252
  const total = s.unusedMcp.reduce((a, m) => a + m.chars, 0);
248
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) {