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/LICENSE +21 -95
- package/README.md +61 -48
- package/bin/limitcast.mjs +103 -212
- package/package.json +2 -2
- package/src/guard.mjs +10 -2
- package/src/insights.mjs +127 -0
- package/src/install.mjs +6 -14
- package/src/license.mjs +2 -1
- package/src/memory.mjs +122 -0
- package/src/notify.mjs +1 -2
- package/src/onboarding.mjs +46 -0
- package/src/pilot.mjs +92 -0
- package/src/results.mjs +31 -15
- package/src/trim.mjs +11 -5
- package/src/value.mjs +37 -11
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',
|
package/src/insights.mjs
ADDED
|
@@ -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,
|
|
284
|
-
* @param {{path?:string, codexPath?:string, samplesAgeMs:number|null, license
|
|
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
|
|
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:
|
|
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:
|
|
347
|
-
line:
|
|
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
|
-
|
|
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/memory.mjs
ADDED
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
import { existsSync, readdirSync, readFileSync } from 'node:fs';
|
|
2
|
+
import { homedir } from 'node:os';
|
|
3
|
+
import { join } from 'node:path';
|
|
4
|
+
|
|
5
|
+
// Claude Code loads only the first 200 lines or 25 KB of MEMORY.md into every session; the rest is never read.
|
|
6
|
+
const INDEX_LINES = 200;
|
|
7
|
+
const INDEX_BYTES = 25 * 1024;
|
|
8
|
+
// A topic file is read whole when opened, so one past this is worth splitting by topic.
|
|
9
|
+
const BIG_LINES = 150;
|
|
10
|
+
const BIG_BYTES = 24 * 1024;
|
|
11
|
+
|
|
12
|
+
/** The auto-memory folder Claude Code keeps for a project.
|
|
13
|
+
* @param {{home?:string, cwd?:string}} [where] */
|
|
14
|
+
export function memoryDir({ home = homedir(), cwd = process.cwd() } = {}) {
|
|
15
|
+
return join(home, '.claude', 'projects', cwd.replace(/[^A-Za-z0-9]/g, '-'), 'memory');
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/** @param {string} text */
|
|
19
|
+
const lineCount = (text) => (text ? text.split('\n').length - (text.endsWith('\n') ? 1 : 0) : 0);
|
|
20
|
+
/** @param {string} s */
|
|
21
|
+
const slug = (s) => s.toLowerCase().replace(/\.md$/, '').replace(/[_\s]/g, '-');
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* What a memory folder looks like from the index down: how much of MEMORY.md loads, which links are broken,
|
|
25
|
+
* which topic files nothing reaches from the index, and which are big. Null when there is no index.
|
|
26
|
+
* @param {string} dir
|
|
27
|
+
*/
|
|
28
|
+
export function scanMemory(dir) {
|
|
29
|
+
const indexPath = join(dir, 'MEMORY.md');
|
|
30
|
+
if (!existsSync(indexPath)) return null;
|
|
31
|
+
const names = readdirSync(dir).filter((f) => f.endsWith('.md'));
|
|
32
|
+
/** @type {Map<string, string>} */
|
|
33
|
+
const text = new Map(names.map((f) => [f, readFileSync(join(dir, f), 'utf8')]));
|
|
34
|
+
const index = /** @type {string} */ (text.get('MEMORY.md'));
|
|
35
|
+
const bySlug = new Map(names.map((f) => [slug(f), f]));
|
|
36
|
+
|
|
37
|
+
const broken = /** @type {{from:string, target:string}[]} */ ([]);
|
|
38
|
+
const reached = new Set(['MEMORY.md']);
|
|
39
|
+
const queue = ['MEMORY.md'];
|
|
40
|
+
for (let f = queue.pop(); f; f = queue.pop()) {
|
|
41
|
+
const body = /** @type {string} */ (text.get(f));
|
|
42
|
+
const targets = [
|
|
43
|
+
...[...body.matchAll(/\]\(([^)\s#]+\.md)[^)]*\)/g)]
|
|
44
|
+
.map((m) => m[1])
|
|
45
|
+
.filter((t) => !/^[a-z]+:/.test(t))
|
|
46
|
+
.map((t) => {
|
|
47
|
+
if (!existsSync(join(dir, t))) broken.push({ from: f, target: t });
|
|
48
|
+
return t;
|
|
49
|
+
}),
|
|
50
|
+
// [[name]] links; one with no file yet is allowed (a note worth writing later), so never "broken".
|
|
51
|
+
...[...body.matchAll(/\[\[([^\]|#]+)/g)].map((m) => bySlug.get(slug(m[1].trim())) ?? ''),
|
|
52
|
+
];
|
|
53
|
+
for (const t of targets) {
|
|
54
|
+
if (!text.has(t) || reached.has(t)) continue;
|
|
55
|
+
reached.add(t);
|
|
56
|
+
queue.push(t);
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
const big = names
|
|
61
|
+
.filter((f) => f !== 'MEMORY.md')
|
|
62
|
+
.map((name) => ({
|
|
63
|
+
name,
|
|
64
|
+
lines: lineCount(/** @type {string} */ (text.get(name))),
|
|
65
|
+
bytes: Buffer.byteLength(/** @type {string} */ (text.get(name))),
|
|
66
|
+
}))
|
|
67
|
+
.filter((f) => f.lines > BIG_LINES || f.bytes > BIG_BYTES)
|
|
68
|
+
.sort((a, b) => b.lines - a.lines);
|
|
69
|
+
return {
|
|
70
|
+
dir,
|
|
71
|
+
index: { lines: lineCount(index), bytes: Buffer.byteLength(index) },
|
|
72
|
+
files: names.length - 1,
|
|
73
|
+
broken,
|
|
74
|
+
orphans: names.filter((f) => !reached.has(f)),
|
|
75
|
+
big,
|
|
76
|
+
};
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/** @param {NonNullable<ReturnType<typeof scanMemory>>} s */
|
|
80
|
+
const overCap = (s) => s.index.lines > INDEX_LINES || s.index.bytes > INDEX_BYTES;
|
|
81
|
+
|
|
82
|
+
/**
|
|
83
|
+
* One doctor line. Only an index past the cap fails: that is memory Claude silently never reads.
|
|
84
|
+
* @param {ReturnType<typeof scanMemory>} s
|
|
85
|
+
* @returns {{ok:boolean, line:string}|null}
|
|
86
|
+
*/
|
|
87
|
+
export function memoryCheck(s) {
|
|
88
|
+
if (!s) return null;
|
|
89
|
+
const size = `index ${s.index.lines}/${INDEX_LINES} lines, ${Math.round(s.index.bytes / 1000)}/25 KB`;
|
|
90
|
+
if (overCap(s))
|
|
91
|
+
return {
|
|
92
|
+
ok: false,
|
|
93
|
+
line: `Memory ${size}: Claude Code loads only the first ${INDEX_LINES} lines or 25 KB of MEMORY.md, so the rest is never read. Fix: /limitcast:memory-audit`,
|
|
94
|
+
};
|
|
95
|
+
const parts = [
|
|
96
|
+
s.index.lines >= INDEX_LINES * 0.8 || s.index.bytes >= INDEX_BYTES * 0.8 ? 'index close to the cap' : '',
|
|
97
|
+
s.orphans.length ? `${s.orphans.length} not linked from the index` : '',
|
|
98
|
+
s.broken.length ? `${s.broken.length} broken link${s.broken.length === 1 ? '' : 's'}` : '',
|
|
99
|
+
s.big.length ? `${s.big.length} file${s.big.length === 1 ? '' : 's'} over ${BIG_LINES} lines` : '',
|
|
100
|
+
].filter(Boolean);
|
|
101
|
+
const next = s.big.length ? '/limitcast:memory-audit, then /limitcast:memory-split' : '/limitcast:memory-audit';
|
|
102
|
+
return { ok: true, line: `Memory: ${s.files} files, ${size}${parts.length ? `; ${parts.join(', ')}. Run ${next}` : ', no problems'}` };
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/** The sweep `/limitcast:memory-audit` and `/limitcast:memory-split` start from.
|
|
106
|
+
* @param {ReturnType<typeof scanMemory>} s
|
|
107
|
+
* @param {string} [dir] shown when there is no index */
|
|
108
|
+
export function memoryReport(s, dir = '') {
|
|
109
|
+
if (!s) return `No auto-memory index (MEMORY.md) in ${dir.replace(homedir(), '~')}`;
|
|
110
|
+
const out = [
|
|
111
|
+
`Memory: ${s.dir.replace(homedir(), '~')}`,
|
|
112
|
+
`Index: MEMORY.md ${s.index.lines} / ${INDEX_LINES} lines, ${(s.index.bytes / 1000).toFixed(1)} / 25 KB${overCap(s) ? ' (OVER: what is past the cap is never loaded)' : ''}`,
|
|
113
|
+
`Topic files: ${s.files}`,
|
|
114
|
+
];
|
|
115
|
+
if (s.orphans.length) out.push(`Not linked from the index (${s.orphans.length}): ${s.orphans.join(', ')}`);
|
|
116
|
+
if (s.broken.length) out.push(`Broken links (${s.broken.length}): ${s.broken.map((b) => `${b.from} -> ${b.target}`).join(', ')}`);
|
|
117
|
+
if (s.big.length)
|
|
118
|
+
out.push(
|
|
119
|
+
`Over ${BIG_LINES} lines or 24 KB (${s.big.length}): ${s.big.map((b) => `${b.name} (${b.lines} lines, ${Math.round(b.bytes / 1000)} KB)`).join(', ')}`,
|
|
120
|
+
);
|
|
121
|
+
return out.join('\n');
|
|
122
|
+
}
|
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
|
-
|
|
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
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
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(
|
|
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(`
|
|
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(
|
|
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
|
|