limitcast 0.13.1 → 0.15.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/README.md +6 -3
- package/bin/limitcast.mjs +68 -11
- package/package.json +1 -1
- package/src/apply.mjs +33 -5
- package/src/codex.mjs +9 -5
- package/src/grok.mjs +9 -5
- package/src/guard.mjs +36 -1
- package/src/hints.mjs +24 -0
- package/src/memory.mjs +122 -0
- package/src/notify.mjs +15 -2
- package/src/results.mjs +8 -1
- package/src/subagents.mjs +21 -0
- package/src/trim.mjs +19 -11
package/README.md
CHANGED
|
@@ -45,7 +45,7 @@ limitcast install --guard # also the subagent guard (free: preview only)
|
|
|
45
45
|
limitcast doctor
|
|
46
46
|
```
|
|
47
47
|
|
|
48
|
-
In Claude Code you can also add the plugin, for `/limitcast:status`, `/limitcast:results` and `/limitcast:
|
|
48
|
+
In Claude Code you can also add the plugin, for `/limitcast:status`, `/limitcast:results`, `/limitcast:trim`, `/limitcast:memory-audit` and `/limitcast:memory-split`: `/plugin marketplace add SamStull9007/limitcast`, then `/plugin install limitcast@limitcast`. The status-line recorder still comes from `limitcast install`.
|
|
49
49
|
|
|
50
50
|
`install` backs up `~/.claude/settings.json` and wraps your existing status line: it looks exactly the same, and the limitcast line (for example `limitcast: 5h 14% · 7d 18% · today 9% left`) goes on the line under it. `--guard` adds the subagent guard (without Pro it only records what it would block). Restart Claude Code to load it. `limitcast uninstall` puts everything back.
|
|
51
51
|
|
|
@@ -57,19 +57,21 @@ In Claude Code you can also add the plugin, for `/limitcast:status`, `/limitcast
|
|
|
57
57
|
|
|
58
58
|
| Command | |
|
|
59
59
|
|---|---|
|
|
60
|
-
| `limitcast status [--json]` | Used, burn rate, runout time and reset for each window, and today's share of each weekly one. **Pro** also lists your other Claude accounts |
|
|
60
|
+
| `limitcast status [--json]` | Used, burn rate, runout time and reset for each window, and today's share of each weekly one. When a window is on pace to run out, one line names the one that binds first and where else there is room ("You'll hit Claude 7d first (Thu 14:00). Grok 5h still has $38."). **Pro** also lists your other Claude accounts |
|
|
61
61
|
| `limitcast trim --codex [--apply / --undo]` | Codex: AGENTS.md size and MCP servers in `~/.codex/config.toml` you haven't used. **Pro** names them and turns them off (`enabled = false`; `--undo` restores the file exactly) |
|
|
62
62
|
| `limitcast trim --grok [--apply / --undo]` | Grok: system prompt and tool-definition size, and MCP servers in `~/.grok/config.toml` you haven't used. **Pro** names them and turns them off (`enabled = false`; `--undo` restores the file exactly) |
|
|
63
63
|
| `limitcast notify on/off/test` | **Pro.** A desktop notification when a Claude window turns NEAR, AT_RISK or HIT, and when it resets after a HIT. On macOS they come from a tiny limitcast notifier app, listed as "limitcast" in System Settings → Notifications |
|
|
64
64
|
| `limitcast notify ntfy <topic or https URL>` / `notify webhook <https URL>` | **Pro.** Also send every notification to your phone through [ntfy](https://ntfy.sh) (install the app, subscribe to the topic) or to a Slack or Discord incoming webhook. `off` removes it. Sent in the background, so no hook waits on the network |
|
|
65
65
|
| `limitcast budget subagents <percent>` / `off` | **Pro.** Once subagents have used that share of the current 5-hour window, the guard holds new ones until it resets. Priced from your own readings (needs about a day of use first) |
|
|
66
|
+
| `limitcast budget today on` / `off` | **Pro.** The `today N% left` pace of a weekly window becomes an action. With `notify on` you get one notification a day at 80% of today's share. With `budget today on` the guard also holds new subagents once today's share is used up, until local midnight. Off by default; a window already at 100% is left to the tool; `LIMITCAST_ALLOW=1` overrides. Free installs record what it would have held (`results`) |
|
|
66
67
|
| `limitcast subagent-model <type> <sonnet\|opus\|haiku\|claude-id\|grok-id>` / `off` | **Pro.** Run new subagents of that type (for example `Explore` or `explore`) on that model, unless the spawn names a model itself. Grok ids also write `[subagents.models]` in `~/.grok/config.toml` (restart Grok). Without arguments it lists what is pinned and the types you ran in the last 30 days. Needs `install --guard`; `results` counts the subagents it moved |
|
|
67
68
|
| `limitcast plan [--days N]`, `limitcast plan set <pro\|max5\|max20>` / `off` | **Pro.** Does your Claude plan fit how much you use? From a long-lived record of the peak of every 5-hour and weekly window (kept 120 days; it starts when you install this version) it says whether you reached your limits often enough to look at the next plan, or used so little that a smaller one would have fit, with the monthly price difference, and shows what your Claude Code tokens would cost at API list prices. Tell it your plan first with `plan set`. Plan prices (Pro $20, Max 5x $100, Max 20x $200) and the 5x / 20x multipliers are from claude.com/pricing (2026-10-26; the Max 20x price was not on that page: change any price in `prices.json`, `{"plans": {"max20": 200}}`). It assumes weekly limits scale like the 5-hour limit, and it cannot see extra-usage spend |
|
|
68
69
|
| `limitcast budget grok <usd>` / `off` / `7d <usd>` | **Pro.** Dollar cap for Grok's aligned 5-hour window (optional 7-day cap). Turns Grok spend into a % so `status` can forecast runout and the guard can block `spawn_subagent` |
|
|
69
70
|
| `limitcast after-reset [--src claude/codex] [--window 5h/7d] [--detach] -- <cmd>` | **Pro.** Wait for the window to reset, then run the command |
|
|
70
71
|
| `limitcast results --html [--out FILE]` | **Pro.** Results, current windows and the burn report on one page, opened in your browser |
|
|
71
72
|
| `limitcast install [--guard] [--alerts]` / `uninstall` | Wire into Claude Code / restore your settings |
|
|
72
|
-
| `limitcast doctor [--fix]` | Check the setup, data freshness, license, and that Claude Code, Codex and Grok logs are still in a format limitcast reads. Also runs daily in the background and flags problems in the status line. `--fix` re-installs with the current Node (after a Node upgrade) |
|
|
73
|
+
| `limitcast doctor [--fix]` | Check the setup, data freshness, license, this project's auto-memory index (see `memory`), and that Claude Code, Codex and Grok logs are still in a format limitcast reads. Also runs daily in the background and flags problems in the status line (the memory line only shows when you run `doctor` yourself). `--fix` re-installs with the current Node (after a Node upgrade) |
|
|
74
|
+
| `limitcast memory [dir]` | Check this project's auto-memory folder (`~/.claude/projects/<project>/memory`): how much of `MEMORY.md` fits in what Claude Code loads each session (the first 200 lines or 25 KB; anything past that is never read), broken links, topic files nothing links to, and files over 150 lines. Read-only. In Claude Code, `/limitcast:memory-audit` takes it from there (stale, contradictory and unlinked notes) and `/limitcast:memory-split` splits an oversized file into a short hub plus topic files |
|
|
73
75
|
| `limitcast trial` | Pro free for 7 days on this computer, no card, once |
|
|
74
76
|
| `limitcast report [--days N] [--out FILE]` | **Pro.** Tokens by tool, day, project, model and session; subagent share; and the API-equivalent cost: what the tokens would cost at the API's list prices (Claude and Grok models; a subscription is not billed this way). Prices are in the code as of 2026-10-26; add or change a model in `~/.local/state/limitcast/prices.json` (`{"models": {"claude-opus-4-1": {"input": 15, "output": 75}}}`, dollars per million tokens) |
|
|
75
77
|
| `limitcast report --why [--days N]` | **Pro.** Where your new tokens went: subagents, session starts, cache rebuilds after idle, tool results by tool, model output, and the largest single steps (Claude Code only) |
|
|
@@ -77,6 +79,7 @@ In Claude Code you can also add the plugin, for `/limitcast:status`, `/limitcast
|
|
|
77
79
|
| `limitcast trim [--days N] [--share]` | Measured starting context of your latest session and how much you haven't used in N days (default 7). **Pro** names each item. `--share`: totals only, no names, safe to post |
|
|
78
80
|
| `limitcast saved` | **Pro.** How much the part of your starting context you control has dropped since limitcast first measured it, times your sessions since |
|
|
79
81
|
| `limitcast trim --apply` / `--undo` | **Pro.** Hide the unused skills from the model and turn off the unused MCP servers for that project, through Claude Code's own settings. Backed up; `--undo` reverses exactly what it changed |
|
|
82
|
+
| `limitcast trim keep <name>[,<name>]` | Servers or skills no `trim --apply` (Claude, Codex or Grok) ever turns off or hides, e.g. `trim keep ego-browser`. `--remove <name>` drops one; no name lists them. Free to set; `trim` shows what it would keep |
|
|
80
83
|
| `limitcast results [--days N] [--share]` | Proof it works: each limit window that reached 100% and how far ahead limitcast warned, and what the guard blocked (free: what it would have blocked) and whether that window then ran out. **Pro** adds starting-context savings. `--share`: totals only |
|
|
81
84
|
| `install --alerts` | **Pro.** A SessionStart hook that tells you (never the model) when your starting context grew ~1k+ tokens, and what grew, plus a one-line weekly summary of what limitcast did |
|
|
82
85
|
| `limitcast activate <key>` | Unlock Pro: registers this computer with Polar (3 computers per key). Polar re-checks it weekly in the background; it keeps working up to 30 days offline |
|
package/bin/limitcast.mjs
CHANGED
|
@@ -7,11 +7,14 @@ import { fileURLToPath } from 'node:url';
|
|
|
7
7
|
import {
|
|
8
8
|
applyTrim,
|
|
9
9
|
claudeJsonPath,
|
|
10
|
+
getKeep,
|
|
10
11
|
installedPlugins,
|
|
12
|
+
isKept,
|
|
11
13
|
localSkillFolders,
|
|
12
14
|
planTrim,
|
|
13
15
|
projectMcpServers,
|
|
14
16
|
reapplyTrim,
|
|
17
|
+
setKeep,
|
|
15
18
|
stillLoading,
|
|
16
19
|
transcriptCwd,
|
|
17
20
|
undoTrim,
|
|
@@ -38,10 +41,11 @@ import {
|
|
|
38
41
|
undoGrokTrim,
|
|
39
42
|
} from '../src/grok.mjs';
|
|
40
43
|
import { runGuard } from '../src/guard.mjs';
|
|
41
|
-
import { accountForecasts, compactHint, headroom, lastCall, lastCallTokens } from '../src/hints.mjs';
|
|
44
|
+
import { accountForecasts, bindingLine, compactHint, headroom, lastCall, lastCallTokens } from '../src/hints.mjs';
|
|
42
45
|
import { htmlPage } from '../src/html.mjs';
|
|
43
46
|
import { doctor, install, installedFeatures, readSettings, settingsPath, uninstall } from '../src/install.mjs';
|
|
44
47
|
import { activate, currentLicense, isPro, startTrial, trialStatus, UPGRADE_URL } from '../src/license.mjs';
|
|
48
|
+
import { memoryCheck, memoryDir, memoryReport, scanMemory } from '../src/memory.mjs';
|
|
45
49
|
import { buildNotifierApp, loadChannels, notifierApp, notifyChanges, notifyEnabled, send, setChannel, setNotify } from '../src/notify.mjs';
|
|
46
50
|
import { driftMessage, loadOverhead, recordOverhead, savedPerSession, savedSummary, snapshot } from '../src/overhead.mjs';
|
|
47
51
|
import { advise, getPlan, loadPeaks, PLANS, planPrices, planStats, recordPeaks, setPlan } from '../src/plan.mjs';
|
|
@@ -56,11 +60,13 @@ import {
|
|
|
56
60
|
budgetSpent,
|
|
57
61
|
getBudget,
|
|
58
62
|
getSubagentModels,
|
|
63
|
+
getTodayHold,
|
|
59
64
|
loadSubagents,
|
|
60
65
|
logSubagent,
|
|
61
66
|
receiptMessage,
|
|
62
67
|
setBudget,
|
|
63
68
|
setSubagentModel,
|
|
69
|
+
setTodayHold,
|
|
64
70
|
subagentUsage,
|
|
65
71
|
validModel,
|
|
66
72
|
windowStart,
|
|
@@ -84,6 +90,7 @@ const HELP = `limitcast ${VERSION}: stretch your Claude Code, Codex and Grok pla
|
|
|
84
90
|
limitcast trim [--share] tokens every session loads before you type, and how much you never use
|
|
85
91
|
limitcast trim --codex the same for Codex: AGENTS.md size and MCP servers you haven't used
|
|
86
92
|
limitcast trim --grok the same for Grok: system prompt size and MCP servers you haven't used
|
|
93
|
+
limitcast memory [dir] check this project's auto-memory: load cap, broken links, unlinked and oversized files
|
|
87
94
|
limitcast results [--days N] limits you reached, how far ahead limitcast warned, what the guard blocked
|
|
88
95
|
[--share] totals only, safe to post
|
|
89
96
|
limitcast license show the license and re-check it with Polar
|
|
@@ -94,6 +101,7 @@ const HELP = `limitcast ${VERSION}: stretch your Claude Code, Codex and Grok pla
|
|
|
94
101
|
limitcast trim --apply / --undo hide those skills and turn off those MCP servers (backed up, reversible)
|
|
95
102
|
limitcast trim --codex --apply / --undo turn off unused Codex MCP servers (enabled = false; reversible)
|
|
96
103
|
limitcast trim --grok --apply / --undo turn off unused Grok MCP servers (enabled = false; reversible)
|
|
104
|
+
limitcast trim keep <name>[,<name>…] never hide or turn off these (any --apply); --remove <name> drops one, no name lists them
|
|
97
105
|
limitcast saved tokens saved since limitcast first measured you
|
|
98
106
|
limitcast install --guard block new subagents when a window is on pace to run out, and run
|
|
99
107
|
them on Sonnet while a window is tight (NEAR or AT_RISK); show what
|
|
@@ -106,6 +114,8 @@ const HELP = `limitcast ${VERSION}: stretch your Claude Code, Codex and Grok pla
|
|
|
106
114
|
limitcast plan set <pro|max5|max20>|off tell limitcast which Claude plan you are on
|
|
107
115
|
limitcast budget grok <usd>|off Grok 5-hour dollar cap (Grok stores spend, not a % used; the guard
|
|
108
116
|
needs this cap to block spawn_subagent). Optional: budget grok 7d <usd>
|
|
117
|
+
limitcast budget today on|off hold new subagents once today's share of a weekly window is used up, until
|
|
118
|
+
midnight (off: you only get a notification at 80% of the share; notify on)
|
|
109
119
|
limitcast install --alerts tell you when your starting context grows, plus a weekly summary, and
|
|
110
120
|
when one tool result is very large (about 20k tokens), with what to ask for instead
|
|
111
121
|
limitcast notify on|off|test desktop notification when a window turns NEAR, AT_RISK or HIT, or resets,
|
|
@@ -148,6 +158,8 @@ if (cmd === 'status') {
|
|
|
148
158
|
if (args.includes('--json')) console.log(JSON.stringify(rows, null, 2));
|
|
149
159
|
else {
|
|
150
160
|
console.log(rows.length ? table(rows) : 'No data yet. Run `limitcast install`, then send a message in Claude Code, Codex or Grok.');
|
|
161
|
+
const binds = bindingLine(rows, getGrokBudget(), clock);
|
|
162
|
+
if (binds) console.log(`\n${binds}`);
|
|
151
163
|
// Pro: the other Claude accounts limitcast has current readings for (the table shows the latest one).
|
|
152
164
|
if (isPro())
|
|
153
165
|
for (const a of accountForecasts(load(now - KEEP_MS), now).slice(1))
|
|
@@ -416,9 +428,25 @@ if (cmd === 'status') {
|
|
|
416
428
|
console.log('The budget is enforced by the guard: limitcast install --guard (then restart Grok).');
|
|
417
429
|
process.exit(0);
|
|
418
430
|
}
|
|
431
|
+
if (args[0] === 'today') {
|
|
432
|
+
if (args[1] !== undefined && args[1] !== 'on' && args[1] !== 'off') {
|
|
433
|
+
console.log('Usage: limitcast budget today on|off');
|
|
434
|
+
process.exit(1);
|
|
435
|
+
}
|
|
436
|
+
if (args[1]) setTodayHold(args[1] === 'on');
|
|
437
|
+
console.log(
|
|
438
|
+
getTodayHold()
|
|
439
|
+
? "Daily hold is on: the guard holds new subagents once today's share of a weekly window is used up, until midnight. Turn it off: limitcast budget today off"
|
|
440
|
+
: "Daily hold is off: you get a notification at 80% of today's share (limitcast notify on), nothing is held. Hold new subagents past it: limitcast budget today on",
|
|
441
|
+
);
|
|
442
|
+
if (getTodayHold() && !installedFeatures().guard) console.log('The hold is enforced by the guard: limitcast install --guard');
|
|
443
|
+
process.exit(0);
|
|
444
|
+
}
|
|
419
445
|
const value = args[1];
|
|
420
446
|
if (args[0] !== 'subagents' || (value !== undefined && value !== 'off' && !(Number(value) > 0 && Number(value) <= 100))) {
|
|
421
|
-
console.log(
|
|
447
|
+
console.log(
|
|
448
|
+
'Usage: limitcast budget subagents <percent of the 5-hour window, 1-100>|off\n limitcast budget grok <usd>|off\n limitcast budget today on|off',
|
|
449
|
+
);
|
|
422
450
|
process.exit(1);
|
|
423
451
|
}
|
|
424
452
|
if (value !== undefined) setBudget(value === 'off' ? null : Number(value));
|
|
@@ -490,8 +518,14 @@ if (cmd === 'status') {
|
|
|
490
518
|
}
|
|
491
519
|
const checks = await healthChecks();
|
|
492
520
|
saveHealth(checks);
|
|
521
|
+
// Memory is per project: shown here, but kept out of the saved health that the daily background check overwrites.
|
|
522
|
+
const mem = memoryCheck(scanMemory(memoryDir()));
|
|
523
|
+
if (mem) checks.push(mem);
|
|
493
524
|
for (const c of checks) console.log(`${c.ok ? '✓' : '✗'} ${c.line}`);
|
|
494
525
|
process.exit(checks.every((c) => c.ok) ? 0 : 1);
|
|
526
|
+
} else if (cmd === 'memory') {
|
|
527
|
+
const dir = args.find((a) => !a.startsWith('-')) ?? memoryDir();
|
|
528
|
+
console.log(memoryReport(scanMemory(dir), dir));
|
|
495
529
|
} else if (cmd === 'report' || cmd === 'trim') {
|
|
496
530
|
const pro = isPro();
|
|
497
531
|
if (!pro && cmd === 'report') {
|
|
@@ -501,6 +535,20 @@ if (cmd === 'status') {
|
|
|
501
535
|
process.exit(2);
|
|
502
536
|
}
|
|
503
537
|
const since = now - days() * 86400_000;
|
|
538
|
+
if (cmd === 'trim' && args[0] === 'keep') {
|
|
539
|
+
// The keep-list: servers and skills `trim --apply` never touches (Claude, Codex and Grok). Free to manage; apply is Pro.
|
|
540
|
+
const drop = args[1] === '--remove';
|
|
541
|
+
const names = args
|
|
542
|
+
.slice(drop ? 2 : 1)
|
|
543
|
+
.join(',')
|
|
544
|
+
.split(',')
|
|
545
|
+
.map((n) => n.trim())
|
|
546
|
+
.filter(Boolean);
|
|
547
|
+
if (names.length) setKeep(drop ? getKeep().filter((k) => !isKept(names, k)) : [...getKeep(), ...names]);
|
|
548
|
+
const keep = getKeep();
|
|
549
|
+
console.log(keep.length ? `Kept by \`trim --apply\`: ${keep.join(', ')}` : 'Nothing on the keep-list. Example: limitcast trim keep ego-browser');
|
|
550
|
+
process.exit(0);
|
|
551
|
+
}
|
|
504
552
|
if (cmd === 'trim' && args.includes('--codex')) {
|
|
505
553
|
// Codex: AGENTS.md and the MCP servers in ~/.codex/config.toml. Free counts them; Pro names them and turns them off.
|
|
506
554
|
if ((args.includes('--apply') || args.includes('--undo')) && !pro) {
|
|
@@ -519,13 +567,13 @@ if (cmd === 'status') {
|
|
|
519
567
|
process.exit(0);
|
|
520
568
|
}
|
|
521
569
|
const servers = codexServers(readFileSync(codexConfigPath(), 'utf8'));
|
|
522
|
-
const r = codexTrimReport({ servers, used: await codexUsedServers(since), startup: await codexStartup(), days: days(), pro });
|
|
570
|
+
const r = codexTrimReport({ servers, used: await codexUsedServers(since), startup: await codexStartup(), days: days(), pro, keep: getKeep() });
|
|
523
571
|
if (args.includes('--apply')) {
|
|
524
572
|
const changed = applyCodexTrim(r.unused);
|
|
525
573
|
console.log(
|
|
526
|
-
changed.length
|
|
574
|
+
(changed.length
|
|
527
575
|
? `✓ Turned off ${changed.length} Codex MCP servers (enabled = false in ${codexConfigPath()}): ${changed.map((s) => s.name).join(', ')}\nTakes effect in your next Codex session. Undo: limitcast trim --codex --undo`
|
|
528
|
-
: 'Nothing to turn off: every server that is on was used.',
|
|
576
|
+
: 'Nothing to turn off: every server that is on was used or is on your keep-list.') + keptNote(r.kept),
|
|
529
577
|
);
|
|
530
578
|
} else console.log(forTerminal(r.text));
|
|
531
579
|
process.exit(0);
|
|
@@ -552,13 +600,14 @@ if (cmd === 'status') {
|
|
|
552
600
|
startup: grokStartup(),
|
|
553
601
|
days: days(),
|
|
554
602
|
pro,
|
|
603
|
+
keep: getKeep(),
|
|
555
604
|
});
|
|
556
605
|
if (args.includes('--apply')) {
|
|
557
606
|
const changed = applyGrokTrim(r.unused);
|
|
558
607
|
console.log(
|
|
559
|
-
changed.length
|
|
608
|
+
(changed.length
|
|
560
609
|
? `✓ Turned off ${changed.length} Grok MCP servers (enabled = false in ${grokConfigPath()}): ${changed.map((s) => s.name).join(', ')}\nTakes effect in your next Grok session. Undo: limitcast trim --grok --undo`
|
|
561
|
-
: 'Nothing to turn off: every server that is on was used.',
|
|
610
|
+
: 'Nothing to turn off: every server that is on was used or is on your keep-list.') + keptNote(r.kept),
|
|
562
611
|
);
|
|
563
612
|
} else console.log(forTerminal(r.text));
|
|
564
613
|
process.exit(0);
|
|
@@ -592,15 +641,16 @@ if (cmd === 'status') {
|
|
|
592
641
|
console.log(args.includes('--undo') ? undoMessage(undoTrim()) : applyMessage(latest, used));
|
|
593
642
|
process.exit(0);
|
|
594
643
|
}
|
|
595
|
-
|
|
596
|
-
|
|
644
|
+
const keep = getKeep();
|
|
645
|
+
if (latest && (args.includes('--share') || !pro)) text = shareSummary(baseline(usage), latest, used, days(), keep);
|
|
646
|
+
else text = latest ? startupReport(baseline(usage), latest, used, days(), keep) : trimReport(baseline(usage), contributors(), used, days());
|
|
597
647
|
if (!pro)
|
|
598
648
|
text += `\n\nPro names each item and what it costs, so you can cut it: ${UPGRADE_URL}\nTry it free for 7 days: limitcast trial. Already bought it? limitcast activate <license-key>`;
|
|
599
649
|
else if (latest && !args.includes('--share')) {
|
|
600
650
|
const still = stillLoading(latest);
|
|
601
651
|
text += still.length
|
|
602
652
|
? `\n\nStill loading after \`trim --apply\`: ${still.join(', ')}. A Claude Code session that was running may have rewritten ~/.claude.json; quit Claude Code and run \`limitcast trim --apply\` again.`
|
|
603
|
-
: measuredSavings(latest.pieces, used).tokens > 0
|
|
653
|
+
: measuredSavings(latest.pieces, used, keep).tokens > 0
|
|
604
654
|
? '\n\nApply these cuts: `limitcast trim --apply` (backed up; `limitcast trim --undo` reverses it).'
|
|
605
655
|
: '';
|
|
606
656
|
}
|
|
@@ -910,7 +960,7 @@ function freeWeeklyHint(t) {
|
|
|
910
960
|
}
|
|
911
961
|
if (t < from) return null;
|
|
912
962
|
const preview = loadBlocks(t - WEEK).filter((b) => b.shadow);
|
|
913
|
-
const stopped = preview.filter((b) => !b.kind || b.kind === 'budget').length;
|
|
963
|
+
const stopped = preview.filter((b) => !b.kind || b.kind === 'budget' || b.kind === 'today').length;
|
|
914
964
|
const moved = preview.filter((b) => b.kind === 'switch').length;
|
|
915
965
|
const cold = preview.filter((b) => b.kind === 'cold').length;
|
|
916
966
|
if (!stopped && !moved && !cold) return null;
|
|
@@ -992,6 +1042,7 @@ function applyMessage(latest, used) {
|
|
|
992
1042
|
plugins: installedPlugins(),
|
|
993
1043
|
projectMcpJson: projectMcpServers(cwd),
|
|
994
1044
|
localSkills: localSkillFolders(cwd),
|
|
1045
|
+
keep: getKeep(),
|
|
995
1046
|
});
|
|
996
1047
|
const e = applyTrim(plan, { cwd, now });
|
|
997
1048
|
const lines = [];
|
|
@@ -1000,6 +1051,7 @@ function applyMessage(latest, used) {
|
|
|
1000
1051
|
if (e.mcp.length) lines.push(`✓ Turned off ${e.mcp.length} MCP servers for ${cwd}: ${e.mcp.join(', ')}`);
|
|
1001
1052
|
if (plan.pluginSkills.length) lines.push(`- Plugin skills can only be turned off with their plugin (\`/plugin\`): ${plan.pluginSkills.join(', ')}`);
|
|
1002
1053
|
if (plan.manualMcp.length) lines.push(`- Turn these off in \`/mcp\` (limitcast couldn't confirm their exact names): ${plan.manualMcp.join(', ')}`);
|
|
1054
|
+
if (plan.kept.length) lines.push(`- Kept, as on your keep-list: ${[...new Set(plan.kept)].join(', ')}`);
|
|
1003
1055
|
if (!e.skills.length && !e.mcp.length) lines.unshift('Nothing to change automatically.');
|
|
1004
1056
|
else
|
|
1005
1057
|
lines.push(
|
|
@@ -1008,6 +1060,11 @@ function applyMessage(latest, used) {
|
|
|
1008
1060
|
return lines.join('\n');
|
|
1009
1061
|
}
|
|
1010
1062
|
|
|
1063
|
+
/** The keep-list servers a Codex or Grok `trim --apply` left on. @param {string[]} kept */
|
|
1064
|
+
function keptNote(kept) {
|
|
1065
|
+
return kept.length ? `\nKept, as on your keep-list: ${kept.join(', ')}` : '';
|
|
1066
|
+
}
|
|
1067
|
+
|
|
1011
1068
|
/** @param {ReturnType<typeof undoTrim>} e */
|
|
1012
1069
|
function undoMessage(e) {
|
|
1013
1070
|
if (!e) return 'Nothing to undo.';
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "limitcast",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.15.0",
|
|
4
4
|
"description": "Stretch your Claude Code plan: measure what every session loads before you type, cut what you never use, and stop runaway subagents before they burn your window.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"bin": {
|
package/src/apply.mjs
CHANGED
|
@@ -30,6 +30,32 @@ const ledgerPath = () => join(stateDir(), 'trim-applied.json');
|
|
|
30
30
|
|
|
31
31
|
/** MCP tool names keep the server name but normalize punctuation. @param {string} s */
|
|
32
32
|
const norm = (s) => s.toLowerCase().replace(/[^a-z0-9]/g, '_');
|
|
33
|
+
const configFile = () => join(stateDir(), 'config.json');
|
|
34
|
+
|
|
35
|
+
/** Names `trim --apply` never turns off or hides, from `limitcast trim keep`. @returns {string[]} */
|
|
36
|
+
export function getKeep() {
|
|
37
|
+
try {
|
|
38
|
+
const k = JSON.parse(readFileSync(configFile(), 'utf8')).trimKeep;
|
|
39
|
+
return Array.isArray(k) ? k.filter((n) => typeof n === 'string') : [];
|
|
40
|
+
} catch {
|
|
41
|
+
return [];
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** @param {string[]} names */
|
|
46
|
+
export function setKeep(names) {
|
|
47
|
+
let cfg = {};
|
|
48
|
+
try {
|
|
49
|
+
cfg = JSON.parse(readFileSync(configFile(), 'utf8'));
|
|
50
|
+
} catch {
|
|
51
|
+
/* new */
|
|
52
|
+
}
|
|
53
|
+
mkdirSync(stateDir(), { recursive: true });
|
|
54
|
+
writeFileSync(configFile(), JSON.stringify({ ...cfg, trimKeep: [...new Set(names)] }));
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** Same server or skill under another spelling ("ego-browser" / "ego_browser") counts. @param {string[]} keep @param {string} name */
|
|
58
|
+
export const isKept = (keep, name) => keep.some((k) => norm(k) === norm(name));
|
|
33
59
|
|
|
34
60
|
/**
|
|
35
61
|
* Installed plugins and the MCP servers they register ("plugin:<plugin>:<server>").
|
|
@@ -63,15 +89,15 @@ export function installedPlugins(dir = configDir()) {
|
|
|
63
89
|
|
|
64
90
|
/**
|
|
65
91
|
* What `--apply` would change, from the unused items `trim` measured.
|
|
66
|
-
* @param {{skills:string[], mcp:string[], cwd:string, settings:any, claudeJson:any, plugins:{names:Set<string>, servers:string[]}, projectMcpJson:string[], localSkills:Set<string
|
|
67
|
-
* localSkills: folder names of personal and project skills
|
|
92
|
+
* @param {{skills:string[], mcp:string[], cwd:string, settings:any, claudeJson:any, plugins:{names:Set<string>, servers:string[]}, projectMcpJson:string[], localSkills:Set<string>, keep?:string[]}} r
|
|
93
|
+
* localSkills: folder names of personal and project skills; keep: the `trim keep` list, never hidden or disabled
|
|
68
94
|
*/
|
|
69
|
-
export function planTrim({ skills, mcp, cwd, settings, claudeJson, plugins, projectMcpJson, localSkills }) {
|
|
95
|
+
export function planTrim({ skills, mcp, cwd, settings, claudeJson, plugins, projectMcpJson, localSkills, keep = [] }) {
|
|
70
96
|
// "x:y" is a plugin skill (namespaced by its plugin) unless x is one of your own skill folders with nested skills.
|
|
71
97
|
// Plugins can load from places installed_plugins.json doesn't list, so the namespace alone decides.
|
|
72
98
|
const isPluginSkill = (/** @type {string} */ n) => n.includes(':') && !localSkills.has(n.split(':')[0]);
|
|
73
99
|
const overrides = settings.skillOverrides ?? {};
|
|
74
|
-
const hide = skills.filter((n) => !isPluginSkill(n) && (overrides[n] === undefined || overrides[n] === 'on'));
|
|
100
|
+
const hide = skills.filter((n) => !isPluginSkill(n) && (overrides[n] === undefined || overrides[n] === 'on') && !isKept(keep, n));
|
|
75
101
|
const pluginSkills = skills.filter(isPluginSkill);
|
|
76
102
|
|
|
77
103
|
// Exact server names Claude Code uses: configured servers, plugin servers, and names already toggled in /mcp anywhere.
|
|
@@ -90,12 +116,14 @@ export function planTrim({ skills, mcp, cwd, settings, claudeJson, plugins, proj
|
|
|
90
116
|
/** @type {string[]} */
|
|
91
117
|
const manualMcp = [];
|
|
92
118
|
for (const m of mcp) {
|
|
119
|
+
if (isKept(keep, m)) continue;
|
|
93
120
|
// .mcp.json servers are approved per project in settings, not toggled in disabledMcpServers.
|
|
94
121
|
const name = projectServers.has(norm(m)) ? null : (byNorm.get(norm(m)) ?? (m.startsWith('claude.ai ') ? m : null));
|
|
95
122
|
if (!name) manualMcp.push(m);
|
|
96
123
|
else if (!already.has(name)) disable.push(name);
|
|
97
124
|
}
|
|
98
|
-
|
|
125
|
+
const kept = [...skills, ...mcp].filter((n) => isKept(keep, n));
|
|
126
|
+
return { hide, pluginSkills, disable, manualMcp, kept };
|
|
99
127
|
}
|
|
100
128
|
|
|
101
129
|
/** @param {string} path */
|
package/src/codex.mjs
CHANGED
|
@@ -118,11 +118,14 @@ export async function codexStartup(root = join(codexHome(), 'sessions')) {
|
|
|
118
118
|
}
|
|
119
119
|
|
|
120
120
|
/**
|
|
121
|
-
* @param {{servers:{name:string, enabled:boolean|undefined}[], used:Set<string>, startup:{agentsMd:number, base:number}|null, days:number, pro:boolean}} r
|
|
121
|
+
* @param {{servers:{name:string, enabled:boolean|undefined}[], used:Set<string>, startup:{agentsMd:number, base:number}|null, days:number, pro:boolean, keep?:string[]}} r
|
|
122
|
+
* keep: the `trim keep` list; unused servers on it are reported as kept and left out of `unused`
|
|
122
123
|
*/
|
|
123
|
-
export function codexTrimReport({ servers, used, startup, days, pro }) {
|
|
124
|
+
export function codexTrimReport({ servers, used, startup, days, pro, keep = [] }) {
|
|
124
125
|
const on = servers.filter((s) => s.enabled !== false);
|
|
125
|
-
const
|
|
126
|
+
const idle = on.filter((s) => !used.has(norm(s.name)));
|
|
127
|
+
const kept = idle.filter((s) => keep.some((k) => norm(k) === norm(s.name)));
|
|
128
|
+
const unused = idle.filter((s) => !kept.includes(s));
|
|
126
129
|
const tok = (/** @type {number} */ c) => `${(c / 4000).toFixed(1)}k`;
|
|
127
130
|
const out = ['# limitcast trim --codex', ''];
|
|
128
131
|
if (startup)
|
|
@@ -131,15 +134,16 @@ export function codexTrimReport({ servers, used, startup, days, pro }) {
|
|
|
131
134
|
'',
|
|
132
135
|
);
|
|
133
136
|
out.push(`## MCP servers: ${on.length} on, ${unused.length} not used in ${days} days`);
|
|
134
|
-
if (!unused.length) out.push('Every server that is on was used.');
|
|
137
|
+
if (!unused.length) out.push(kept.length ? 'Nothing else to turn off.' : 'Every server that is on was used.');
|
|
135
138
|
else if (pro)
|
|
136
139
|
out.push(...unused.map((s) => `- ${s.name}`), '', 'Turn them off: `limitcast trim --codex --apply` (backed up; `--undo` reverses it).');
|
|
137
140
|
else out.push(`Pro names them and turns them off for you: https://limitcast.dev/#pricing`);
|
|
141
|
+
if (kept.length) out.push('', `Would keep (your keep-list): ${kept.map((s) => s.name).join(', ')}.`);
|
|
138
142
|
out.push(
|
|
139
143
|
'',
|
|
140
144
|
'Each server that is on starts with every Codex session and adds its tool list to the context. AGENTS.md: every 1k tokens you move into files read on demand saves 1k per turn.',
|
|
141
145
|
);
|
|
142
|
-
return { text: out.join('\n'), unused: unused.map((s) => s.name) };
|
|
146
|
+
return { text: out.join('\n'), unused: unused.map((s) => s.name), kept: kept.map((s) => s.name) };
|
|
143
147
|
}
|
|
144
148
|
|
|
145
149
|
/** @param {string} path @param {string} text */
|
package/src/grok.mjs
CHANGED
|
@@ -73,11 +73,14 @@ export function grokStartup(root = grokRoot()) {
|
|
|
73
73
|
}
|
|
74
74
|
|
|
75
75
|
/**
|
|
76
|
-
* @param {{servers:{name:string, enabled:boolean|undefined}[], used:Set<string>, startup:{prompt:number, tools:number}|null, days:number, pro:boolean}} r
|
|
76
|
+
* @param {{servers:{name:string, enabled:boolean|undefined}[], used:Set<string>, startup:{prompt:number, tools:number}|null, days:number, pro:boolean, keep?:string[]}} r
|
|
77
|
+
* keep: the `trim keep` list; unused servers on it are reported as kept and left out of `unused`
|
|
77
78
|
*/
|
|
78
|
-
export function grokTrimReport({ servers, used, startup, days, pro }) {
|
|
79
|
+
export function grokTrimReport({ servers, used, startup, days, pro, keep = [] }) {
|
|
79
80
|
const on = servers.filter((s) => s.enabled !== false);
|
|
80
|
-
const
|
|
81
|
+
const idle = on.filter((s) => !used.has(norm(s.name)));
|
|
82
|
+
const kept = idle.filter((s) => keep.some((k) => norm(k) === norm(s.name)));
|
|
83
|
+
const unused = idle.filter((s) => !kept.includes(s));
|
|
81
84
|
const tok = (/** @type {number} */ c) => `${(c / 4000).toFixed(1)}k`;
|
|
82
85
|
const out = ['# limitcast trim --grok', ''];
|
|
83
86
|
if (startup)
|
|
@@ -86,15 +89,16 @@ export function grokTrimReport({ servers, used, startup, days, pro }) {
|
|
|
86
89
|
'',
|
|
87
90
|
);
|
|
88
91
|
out.push(`## MCP servers: ${on.length} on, ${unused.length} not used in ${days} days`);
|
|
89
|
-
if (!unused.length) out.push('Every server that is on was used.');
|
|
92
|
+
if (!unused.length) out.push(kept.length ? 'Nothing else to turn off.' : 'Every server that is on was used.');
|
|
90
93
|
else if (pro)
|
|
91
94
|
out.push(...unused.map((s) => `- ${s.name}`), '', 'Turn them off: `limitcast trim --grok --apply` (backed up; `--undo` reverses it).');
|
|
92
95
|
else out.push(`Pro names them and turns them off for you: https://limitcast.dev/#pricing`);
|
|
96
|
+
if (kept.length) out.push('', `Would keep (your keep-list): ${kept.map((s) => s.name).join(', ')}.`);
|
|
93
97
|
out.push(
|
|
94
98
|
'',
|
|
95
99
|
'Each server that is on starts with every Grok session and adds its tool list to the context. Moving unused servers off is `enabled = false` in ~/.grok/config.toml.',
|
|
96
100
|
);
|
|
97
|
-
return { text: out.join('\n'), unused: unused.map((s) => s.name) };
|
|
101
|
+
return { text: out.join('\n'), unused: unused.map((s) => s.name), kept: kept.map((s) => s.name) };
|
|
98
102
|
}
|
|
99
103
|
|
|
100
104
|
/**
|
package/src/guard.mjs
CHANGED
|
@@ -4,7 +4,7 @@ import { grokSamples } from './grok.mjs';
|
|
|
4
4
|
import { logBlock } from './results.mjs';
|
|
5
5
|
import { readCodex } from './sources.mjs';
|
|
6
6
|
import { KEEP_MS, load } from './store.mjs';
|
|
7
|
-
import { budgetMessage, budgetSpent, getBudget, loadSubagents, pinnedModel, spawnNotice, windowStart } from './subagents.mjs';
|
|
7
|
+
import { budgetMessage, budgetSpent, getBudget, getTodayHold, loadSubagents, pinnedModel, spawnNotice, windowStart } from './subagents.mjs';
|
|
8
8
|
|
|
9
9
|
const NAMES = { claude: 'Claude', codex: 'Codex', grok: 'Grok' };
|
|
10
10
|
|
|
@@ -95,6 +95,27 @@ export async function runGuard(hook, now, minutes, { preview = false } = {}) {
|
|
|
95
95
|
}
|
|
96
96
|
}
|
|
97
97
|
if (reason) return preview ? null : reason;
|
|
98
|
+
// Today's share of a weekly window is used up: hold new subagents until local midnight, when the share starts over.
|
|
99
|
+
// Opt-in for Pro (`limitcast budget today on`; the default is a notification at 80%); a free preview records it either way.
|
|
100
|
+
// A window already at 100% is left to the tool. shortcut: Codex readings here span only 2 hours, so its share reads low.
|
|
101
|
+
const day = todayOver(src, forecasts);
|
|
102
|
+
if (day && (preview || getTodayHold())) {
|
|
103
|
+
try {
|
|
104
|
+
logBlock({
|
|
105
|
+
t: now,
|
|
106
|
+
kind: 'today',
|
|
107
|
+
src: day.src,
|
|
108
|
+
win: day.win,
|
|
109
|
+
pct: Math.round(day.today.used),
|
|
110
|
+
wall: now,
|
|
111
|
+
reset: new Date(now).setHours(24, 0, 0, 0),
|
|
112
|
+
...(preview ? { shadow: true } : {}),
|
|
113
|
+
});
|
|
114
|
+
} catch {
|
|
115
|
+
/* a failed log must not change the decision */
|
|
116
|
+
}
|
|
117
|
+
if (!preview) return todayMessage(day);
|
|
118
|
+
}
|
|
98
119
|
// Pro: hold new Claude subagents once those of this account have used their budget of the current 5-hour window.
|
|
99
120
|
const budget = src === 'claude' ? getBudget() : null;
|
|
100
121
|
if (budget) {
|
|
@@ -182,6 +203,20 @@ export async function runGuard(hook, now, minutes, { preview = false } = {}) {
|
|
|
182
203
|
};
|
|
183
204
|
}
|
|
184
205
|
|
|
206
|
+
/**
|
|
207
|
+
* The spawning tool's weekly window when today's even share of it is used up (and the window itself is not at 100%).
|
|
208
|
+
* @param {'claude'|'codex'|'grok'|null} src
|
|
209
|
+
* @param {ReturnType<typeof import('./forecast.mjs').forecastAll>} forecasts
|
|
210
|
+
*/
|
|
211
|
+
function todayOver(src, forecasts) {
|
|
212
|
+
return forecasts.find((f) => f.src === src && f.today && f.today.left < 0 && f.verdict !== 'HIT' && f.verdict !== 'RESET');
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
/** @param {NonNullable<ReturnType<typeof todayOver>>} f */
|
|
216
|
+
const todayMessage = (f) =>
|
|
217
|
+
`limitcast: today's share of your ${NAMES[/** @type {'claude'} */ (f.src)]} ${f.win} limit is used up (${Math.round(f.today?.used ?? 0)}% of ${Math.round(f.today?.budget ?? 0)}%). ` +
|
|
218
|
+
'New subagents are held until midnight. Turn this off: `limitcast budget today off`, or set LIMITCAST_ALLOW=1 to spawn anyway.';
|
|
219
|
+
|
|
185
220
|
const SWITCH_TO = 'sonnet';
|
|
186
221
|
|
|
187
222
|
/**
|
package/src/hints.mjs
CHANGED
|
@@ -42,6 +42,30 @@ export function headroom(samples, sid, now) {
|
|
|
42
42
|
return `⇄ other account ${parts.join(' · ')}`;
|
|
43
43
|
}
|
|
44
44
|
|
|
45
|
+
const NAMES = { claude: 'Claude', codex: 'Codex', grok: 'Grok' };
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* One sentence naming the window that runs out first at the current pace, and where else there is room:
|
|
49
|
+
* "You'll hit Claude 7d first (Thu 14:00). Grok 5h still has $38." Null when no window is on pace to run out.
|
|
50
|
+
* @param {ReturnType<typeof forecastAll>} rows
|
|
51
|
+
* @param {{'5h'?:number, '7d'?:number}|null} grokCap the Grok dollar caps; a Grok row holds a % of its cap
|
|
52
|
+
* @param {(ms:number)=>string} clock
|
|
53
|
+
*/
|
|
54
|
+
export function bindingLine(rows, grokCap, clock) {
|
|
55
|
+
const first = rows.filter((f) => f.verdict === 'AT_RISK' && f.wall !== null).sort((a, b) => (a.wall ?? 0) - (b.wall ?? 0))[0];
|
|
56
|
+
if (!first) return null;
|
|
57
|
+
const name = (/** @type {{src:string, win:string}} */ f) => `${NAMES[/** @type {'claude'} */ (f.src)] ?? f.src} ${f.win}`;
|
|
58
|
+
// Room: the least-used window of another tool that is not itself in trouble.
|
|
59
|
+
const room = rows.filter((f) => f.src !== first.src && f.verdict === 'OK').sort((a, b) => a.pct - b.pct)[0];
|
|
60
|
+
const cap = room?.src === 'grok' ? grokCap?.[/** @type {'5h'} */ (room.win)] : undefined;
|
|
61
|
+
const left = !room
|
|
62
|
+
? ''
|
|
63
|
+
: cap
|
|
64
|
+
? ` ${name(room)} still has $${Math.round((cap * (100 - room.pct)) / 100)}.`
|
|
65
|
+
: ` ${name(room)} has ${Math.round(100 - room.pct)}% left.`;
|
|
66
|
+
return `You'll hit ${name(first)} first (${clock(first.wall ?? first.reset)}).${left}`;
|
|
67
|
+
}
|
|
68
|
+
|
|
45
69
|
const COMPACT_AT = 150_000; // tokens re-sent per model call worth a /compact
|
|
46
70
|
|
|
47
71
|
/**
|
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
|
@@ -25,11 +25,14 @@ export function setNotify(on) {
|
|
|
25
25
|
/**
|
|
26
26
|
* Messages for windows that got worse since the last notification, or reset after reaching their limit.
|
|
27
27
|
* Within one window the state only ratchets up, so a pace that wobbles around a threshold notifies once.
|
|
28
|
-
*
|
|
28
|
+
* A weekly window's daily share also notifies once a day, at 80% of today's share used (key "<src>|<win>|today",
|
|
29
|
+
* reset = that day's midnight).
|
|
30
|
+
* @param {{src:string, win:string, pct:number, reset:number, wall:number|null, verdict:string, today?:{budget:number, used:number, left:number}|null}[]} rows
|
|
29
31
|
* @param {Record<string, {reset:number, verdict:string}>} prev
|
|
30
32
|
* @param {(ms:number)=>string} clock
|
|
33
|
+
* @param {number} [now] epoch ms
|
|
31
34
|
*/
|
|
32
|
-
export function transitions(rows, prev, clock) {
|
|
35
|
+
export function transitions(rows, prev, clock, now = Date.now()) {
|
|
33
36
|
const messages = [];
|
|
34
37
|
const next = { ...prev };
|
|
35
38
|
for (const f of rows) {
|
|
@@ -50,6 +53,16 @@ export function transitions(rows, prev, clock) {
|
|
|
50
53
|
messages.push(`${name} limit is on pace to run out at ${clock(f.wall)}, before it resets at ${clock(f.reset)}.`);
|
|
51
54
|
if (f.verdict === 'HIT') messages.push(`${name} limit reached. Resets ${clock(f.reset)}.`);
|
|
52
55
|
}
|
|
56
|
+
const midnight = new Date(now).setHours(0, 0, 0, 0);
|
|
57
|
+
for (const f of rows) {
|
|
58
|
+
const t = f.today;
|
|
59
|
+
const key = `${f.src}|${f.win}|today`;
|
|
60
|
+
if (!t || t.budget <= 0 || t.used < 0.8 * t.budget || f.verdict === 'HIT' || next[key]?.reset === midnight) continue;
|
|
61
|
+
next[key] = { reset: midnight, verdict: 'NEAR' };
|
|
62
|
+
messages.push(
|
|
63
|
+
`${NAMES[/** @type {'claude'} */ (f.src)] ?? f.src} ${f.win}: ${Math.round((t.used / t.budget) * 100)}% of today's share used, ${Math.max(0, Math.round(t.left))}% left today.`,
|
|
64
|
+
);
|
|
65
|
+
}
|
|
53
66
|
return { messages, next };
|
|
54
67
|
}
|
|
55
68
|
|
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); no kind: a forecast block */
|
|
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 */
|
|
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' };
|
|
@@ -131,6 +131,7 @@ export function resultsStats({ now, days, samples, blocks, pro }) {
|
|
|
131
131
|
const defaults = mine.filter((b) => b.kind === 'default').length;
|
|
132
132
|
const colds = mine.filter((b) => b.kind === 'cold');
|
|
133
133
|
const budgets = mine.filter((b) => b.kind === 'budget').length;
|
|
134
|
+
const todays = mine.filter((b) => b.kind === 'today').length;
|
|
134
135
|
return {
|
|
135
136
|
readings,
|
|
136
137
|
hits,
|
|
@@ -142,6 +143,7 @@ export function resultsStats({ now, days, samples, blocks, pro }) {
|
|
|
142
143
|
colds: colds.length,
|
|
143
144
|
coldPct: colds.reduce((a, b) => a + b.pct, 0),
|
|
144
145
|
budgets,
|
|
146
|
+
todays,
|
|
145
147
|
};
|
|
146
148
|
}
|
|
147
149
|
|
|
@@ -177,6 +179,7 @@ export function weeklyLine(st, savedPerSession, notResent = 0) {
|
|
|
177
179
|
if (st.switches) parts.push(`moved ${st.switches} to Sonnet`);
|
|
178
180
|
if (st.defaults) parts.push(`ran ${st.defaults} on their set model`);
|
|
179
181
|
if (st.budgets) parts.push(`held ${st.budgets} over budget`);
|
|
182
|
+
if (st.todays) parts.push(`held ${st.todays} once today's share was used`);
|
|
180
183
|
if (st.colds) parts.push(`caught ${st.colds} cold-cache message${st.colds === 1 ? '' : 's'}`);
|
|
181
184
|
if (savedPerSession && savedPerSession > 0) parts.push(`starting context ${fmtK(savedPerSession)} tokens smaller`);
|
|
182
185
|
if (notResent > 0) parts.push(`${fmtK(notResent)} tokens not re-sent`);
|
|
@@ -276,6 +279,10 @@ export function resultsReport({ now, days, samples, blocks, pro, saved, value =
|
|
|
276
279
|
`${pro ? 'Ran' : 'Pro would have run'} ${st.defaults} subagent${st.defaults === 1 ? '' : 's'} on the model you set for their type (limitcast subagent-model).`,
|
|
277
280
|
);
|
|
278
281
|
if (st.budgets) out.push(`Held ${st.budgets} subagent${st.budgets === 1 ? '' : 's'} once subagents had used their budget of the 5-hour window.`);
|
|
282
|
+
if (st.todays)
|
|
283
|
+
out.push(
|
|
284
|
+
`${pro ? 'Held' : 'Pro could have held'} ${st.todays} subagent${st.todays === 1 ? '' : 's'} once today's share of a weekly window was used up (limitcast budget today on).`,
|
|
285
|
+
);
|
|
279
286
|
|
|
280
287
|
const recent = subagents.filter((e) => e.t >= now - days * 86400_000);
|
|
281
288
|
if (recent.length || st.colds) {
|
package/src/subagents.mjs
CHANGED
|
@@ -131,6 +131,27 @@ export function setBudget(pct) {
|
|
|
131
131
|
writeFileSync(configFile(), JSON.stringify({ ...cfg, subagentBudget: pct }));
|
|
132
132
|
}
|
|
133
133
|
|
|
134
|
+
/** Whether the guard holds new subagents once today's share of a weekly window is used up (`limitcast budget today on`). */
|
|
135
|
+
export function getTodayHold() {
|
|
136
|
+
try {
|
|
137
|
+
return JSON.parse(readFileSync(configFile(), 'utf8')).todayHold === true;
|
|
138
|
+
} catch {
|
|
139
|
+
return false;
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
/** @param {boolean} on */
|
|
144
|
+
export function setTodayHold(on) {
|
|
145
|
+
let cfg = {};
|
|
146
|
+
try {
|
|
147
|
+
cfg = JSON.parse(readFileSync(configFile(), 'utf8'));
|
|
148
|
+
} catch {
|
|
149
|
+
/* new */
|
|
150
|
+
}
|
|
151
|
+
mkdirSync(stateDir(), { recursive: true });
|
|
152
|
+
writeFileSync(configFile(), JSON.stringify({ ...cfg, todayHold: on }));
|
|
153
|
+
}
|
|
154
|
+
|
|
134
155
|
/** A model a subagent type can be pinned to: sonnet, opus, haiku, a claude-... id, or a grok-... id. */
|
|
135
156
|
export const validModel = (/** @type {unknown} */ m) => typeof m === 'string' && /^(sonnet|opus|haiku|claude-[a-z0-9.-]+|grok-[a-z0-9.-]+)$/i.test(m);
|
|
136
157
|
|
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(
|
|
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 ?? {};
|
|
@@ -196,8 +197,9 @@ const tok = (/** @type {number} */ chars) => Math.round(chars / 4);
|
|
|
196
197
|
* From a measured startup breakdown: MCP servers and listed skills unused in the period, with their exact size.
|
|
197
198
|
* @param {import('./startup.mjs').Piece[]} pieces
|
|
198
199
|
* @param {Activity} used
|
|
200
|
+
* @param {string[]} [keep] the `trim keep` list: unused, but never counted as a cut; named in `kept`
|
|
199
201
|
*/
|
|
200
|
-
export function measuredSavings(pieces, used) {
|
|
202
|
+
export function measuredSavings(pieces, used, keep = []) {
|
|
201
203
|
const usedMcp = new Set([...used.mcp].map(norm));
|
|
202
204
|
// Instructions and tool names spell a server differently ("claude.ai Postman" / "claude_ai_Postman"): merge by normalized name.
|
|
203
205
|
/** @type {Map<string, {name:string, chars:number}>} */
|
|
@@ -212,9 +214,12 @@ export function measuredSavings(pieces, used) {
|
|
|
212
214
|
}
|
|
213
215
|
}
|
|
214
216
|
const skills = pieces.filter((p) => p.group === 'Skill listing' && !skillUsed(p.name, used.skills)).sort((a, b) => b.chars - a.chars);
|
|
215
|
-
const
|
|
216
|
-
const
|
|
217
|
-
|
|
217
|
+
const kept = [...mcp.values(), ...skills].filter((x) => keep.some((k) => norm(k) === norm(x.name))).map((x) => x.name);
|
|
218
|
+
const isKept = (/** @type {{name:string}} */ x) => kept.includes(x.name);
|
|
219
|
+
const unusedMcp = [...mcp.values()].filter((m) => !isKept(m)).sort((a, b) => b.chars - a.chars);
|
|
220
|
+
const unusedSkills = skills.filter((s) => !isKept(s));
|
|
221
|
+
const chars = unusedMcp.reduce((a, m) => a + m.chars, 0) + unusedSkills.reduce((a, s) => a + s.chars, 0);
|
|
222
|
+
return { unusedMcp, unusedSkills, tokens: tok(chars), kept };
|
|
218
223
|
}
|
|
219
224
|
|
|
220
225
|
/**
|
|
@@ -223,9 +228,10 @@ export function measuredSavings(pieces, used) {
|
|
|
223
228
|
* @param {{pieces:import('./startup.mjs').Piece[], at:number}} b
|
|
224
229
|
* @param {Activity} used
|
|
225
230
|
* @param {number} days
|
|
231
|
+
* @param {string[]} [keep] the `trim keep` list
|
|
226
232
|
*/
|
|
227
|
-
export function startupReport(base, b, used, days) {
|
|
228
|
-
const s = measuredSavings(b.pieces, used);
|
|
233
|
+
export function startupReport(base, b, used, days, keep = []) {
|
|
234
|
+
const s = measuredSavings(b.pieces, used, keep);
|
|
229
235
|
const median = base?.median ?? 0;
|
|
230
236
|
const lines = ['# limitcast trim', ''];
|
|
231
237
|
if (base) {
|
|
@@ -257,7 +263,8 @@ export function startupReport(base, b, used, days) {
|
|
|
257
263
|
' Set each to `"user-invocable-only"` under `skillOverrides` in `~/.claude/settings.json`: `/name` still works.',
|
|
258
264
|
);
|
|
259
265
|
}
|
|
260
|
-
if (
|
|
266
|
+
if (s.kept.length) lines.push(`- **Would keep ${s.kept.length} on your keep-list** (\`trim --apply\` never touches them): ${s.kept.join(', ')}.`);
|
|
267
|
+
else if (!s.unusedMcp.length && !s.unusedSkills.length) lines.push('- Nothing unused. Everything that loads was used in the period.');
|
|
261
268
|
|
|
262
269
|
/** @type {Map<string, number>} */
|
|
263
270
|
const groups = new Map();
|
|
@@ -293,16 +300,17 @@ export function startupReport(base, b, used, days) {
|
|
|
293
300
|
* @param {{pieces:import('./startup.mjs').Piece[]}} b
|
|
294
301
|
* @param {Activity} used
|
|
295
302
|
* @param {number} days
|
|
303
|
+
* @param {string[]} [keep] the `trim keep` list; only its count is shown
|
|
296
304
|
*/
|
|
297
|
-
export function shareSummary(base, b, used, days) {
|
|
298
|
-
const s = measuredSavings(b.pieces, used);
|
|
305
|
+
export function shareSummary(base, b, used, days, keep = []) {
|
|
306
|
+
const s = measuredSavings(b.pieces, used, keep);
|
|
299
307
|
/** @type {Map<string, number>} */
|
|
300
308
|
const groups = new Map();
|
|
301
309
|
for (const p of b.pieces) groups.set(p.group, (groups.get(p.group) ?? 0) + p.chars);
|
|
302
310
|
const median = base?.median ?? 0;
|
|
303
311
|
const lines = [
|
|
304
312
|
`My Claude Code sessions start at ${fmt(median)} tokens before I type.`,
|
|
305
|
-
`limitcast found ~${fmt(s.tokens)} per session${median ? ` (${Math.round((s.tokens / median) * 100)}%)` : ''} I haven't used in ${days} days: ${s.unusedMcp.length} MCP servers, ${s.unusedSkills.length} skills.`,
|
|
313
|
+
`limitcast found ~${fmt(s.tokens)} per session${median ? ` (${Math.round((s.tokens / median) * 100)}%)` : ''} I haven't used in ${days} days: ${s.unusedMcp.length} MCP servers, ${s.unusedSkills.length} skills${s.kept.length ? ` (${s.kept.length} more kept on my keep-list)` : ''}.`,
|
|
306
314
|
'Where it comes from:',
|
|
307
315
|
...[...groups].sort((x, y) => y[1] - x[1]).map(([g, c]) => ` ${g}: ${fmt(tok(c))}`),
|
|
308
316
|
];
|