Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

perf: roll up old daily usage buckets into monthly to bound usage.json growth (#2485)

Adam Eivyee326ed7d8f9
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 85b239ce7b..e2be8799cd 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -83,3 +83,5 @@
- **A daily self-diagnostics job now surfaces CoS self-healing failures into a single GitHub monitoring issue (#2464).** The Layered Intelligence loop can only improve if failures are actually observed, but a category quietly stuck failing (e.g. `self-improve:claim-issue`'s claim-work at a ~30% failure rate, or `layered-intelligence` failing its first run) had no automated pulse — the numbers lived only in the Learning tab. A new deterministic `type: 'script'` autonomous job (`job-self-diagnostics`, `scriptHandler: 'self-diagnostics'`, daily at 05:00, disabled by default) reads the task-learning per-category metrics (`data/cos/learning.json` `byTaskType`), and for every category with recorded failures records a structured single-line log entry (slug, failed/total, success rate, `lastCompleted`, avg/max duration) and aggregates them — ordered by impact (most failures first, then lowest success rate) — into ONE persistent GitHub summary issue. It reuses an existing open issue marked `monitoring` (matched by an embedded dedup slug marker) rather than filing a fresh duplicate each cycle, refreshes its body in place, and toggles a `needs attention` label on while failures exist / off once the categories recover. The issue read distinguishes a failed `gh` call (skip, don't file) from an empty list (`ok:true`), so a transient CLI blip can't defeat dedup. No LLM calls — a pure metrics-read + `gh` write, cold-bootstrap-safe and a sanctioned scheduled automation. The new default job self-installs on existing installs via the additive `mergeWithDefaults` boot merge (no migration needed).
- **The Elements Song page gains a Flash Cards study mode so you can learn name↔symbol pairings before being tested (#2480).** The `/post/memory/elements` surface previously only *tested* element mappings (the Element Flash recall quiz) or let you *browse* the periodic table — a user who didn't already know the pairings had nowhere to learn them, unlike Morse (copy vs head-copy) and MemoryPractice (learn vs recall) which both have an explicit study→test split. A new **Flash Cards** mode draws the weakest-mastered elements first, shows one face (name, or symbol + atomic number) and flips to reveal the full pairing, then lets you self-rate *Got It* / *Study Again*. Study reps advance element mastery through the same `submitMemoryPractice` path the recall quiz uses (`mode: 'element-study'`), so studying counts toward the same per-element mastery the periodic-table heatmap shows. The elements page is also now reachable from ⌘K / voice nav (a new `nav.post.memory.elements` manifest entry) — it had no entry before. `element-study` is a standalone practice mode (like `learn`), not a POST-session drill type, so it's intentionally not offered in the balanced-session drill picker (the server has no session generator for it); no migration needed (additive enum value + label).
+
+- **`data/usage.json` no longer grows without bound — old per-day activity is rolled up into monthly buckets at load time (#2485).** Usage is rewritten in full on every AI run (`recordSession`/`recordMessages`), and `dailyActivity` accumulated one key per day forever, so the hot-path serialize+write grew linearly and would keep bloating as richer per-provider/per-model day buckets land. `loadUsage()` now runs a one-shot, idempotent rollup that moves day buckets older than 400 days (a full year-plus of per-day granularity, beyond any useful streak/report window) into a new `monthlyActivity['YYYY-MM']` map, deep-summing their numeric fields so long-range totals stay accurate at monthly granularity — and shape-tolerant, so any nested per-provider/per-model token splits are preserved when collapsed. Recent days are left untouched (streaks, last-7-days, and top-level totals are unchanged), and `monthlyActivity` is backfilled for existing installs on first load with no migration script needed (pure additive, tolerant load-time transform). The `buildUsageReport` cost report (#2484) now folds the monthly buckets back in alongside the daily ones, so an all-time or long-range Est. API Cost report stays accurate across the rollup boundary (a rolled-up month is whole-month-granular and included whenever it overlaps the requested range). New exported `rollupOldDailyActivity` helper is unit-tested for the retention boundary, same-month summing, deep nested-shape summing, idempotency, and total-preservation across the boundary, plus report tests for monthly folding and range overlap.
diff --git a/server/services/usage.js b/server/services/usage.js
index 99756db389..217ac21c5d 100644
--- a/server/services/usage.js
+++ b/server/services/usage.js
@@ -5,6 +5,13 @@ import { resolveModelRates, isFreeProvider, estimateCostUsd, PRICING_AS_OF } fro
const DATA_DIR = PATHS.data;
const USAGE_FILE = join(DATA_DIR, 'usage.json');
+// Day buckets older than this are rolled up into monthly buckets at load time so
+// dailyActivity (and therefore the whole-file rewrite on every AI run) stops growing
+// linearly forever. 400 days keeps a full year-plus of per-day granularity — beyond
+// any useful streak/report window — while collapsing everything older to per-month.
+const ROLLUP_RETENTION_DAYS = 400;
+const DAY_KEY_RE = /^\d{4}-\d{2}-\d{2}$/;
+
let usageData = null;
/**
@@ -22,11 +29,64 @@ function getEmptyUsage() {
byProvider: {},
byModel: {},
dailyActivity: {},
+ monthlyActivity: {},
hourlyActivity: Array(24).fill(0),
lastUpdated: null
};
}
+/**
+ * Deep-sum a source bucket into a target bucket, in place. Numbers add; nested
+ * objects recurse. Shape-tolerant on purpose: a day bucket may be the flat
+ * `{ sessions, messages, tokens }` shape, or carry nested per-provider/per-model
+ * token splits — either way its per-provider/per-model detail is preserved when
+ * rolled up to monthly granularity.
+ */
+function deepSumInto(target, source) {
+ for (const [key, value] of Object.entries(source)) {
+ if (typeof value === 'number') {
+ target[key] = (typeof target[key] === 'number' ? target[key] : 0) + value;
+ } else if (value && typeof value === 'object' && !Array.isArray(value)) {
+ if (!target[key] || typeof target[key] !== 'object' || Array.isArray(target[key])) {
+ target[key] = {};
+ }
+ deepSumInto(target[key], value);
+ }
+ // Non-numeric scalars (strings like provider `name`) are intentionally dropped:
+ // a monthly rollup aggregates counts, not labels.
+ }
+ return target;
+}
+
+/**
+ * Pure, idempotent load-time transform: move day buckets older than `retentionDays`
+ * out of `dailyActivity` and into `monthlyActivity['YYYY-MM']`, deep-summing their
+ * (possibly nested) numeric fields so long-range totals stay accurate at monthly
+ * granularity. Mutates the passed maps in place and returns whether anything moved.
+ * Only well-formed YYYY-MM-DD keys are considered, so an already-rolled monthly key
+ * is never re-processed (guaranteeing idempotency).
+ */
+export function rollupOldDailyActivity(dailyActivity, monthlyActivity, { retentionDays = ROLLUP_RETENTION_DAYS, now = new Date() } = {}) {
+ if (!dailyActivity || !monthlyActivity) return false;
+
+ const cutoff = new Date(now);
+ cutoff.setDate(cutoff.getDate() - retentionDays);
+ const cutoffKey = cutoff.toISOString().split('T')[0];
+
+ let changed = false;
+ for (const dayKey of Object.keys(dailyActivity)) {
+ if (!DAY_KEY_RE.test(dayKey)) continue;
+ if (dayKey >= cutoffKey) continue; // lexical compare is date-correct for YYYY-MM-DD
+
+ const monthKey = dayKey.slice(0, 7); // 'YYYY-MM'
+ if (!monthlyActivity[monthKey]) monthlyActivity[monthKey] = {};
+ deepSumInto(monthlyActivity[monthKey], dailyActivity[dayKey]);
+ delete dailyActivity[dayKey];
+ changed = true;
+ }
+ return changed;
+}
+
/**
* Load usage data from disk
*/
@@ -39,6 +99,20 @@ export async function loadUsage() {
await saveUsage();
}
+ // Backfill maps for installs whose usage.json predates the rollup, then collapse
+ // old day buckets so the hot-path file stops growing per-day.
+ if (!usageData.dailyActivity || typeof usageData.dailyActivity !== 'object') {
+ usageData.dailyActivity = {};
+ }
+ if (!usageData.monthlyActivity || typeof usageData.monthlyActivity !== 'object') {
+ usageData.monthlyActivity = {};
+ }
+ const rolledUp = rollupOldDailyActivity(usageData.dailyActivity, usageData.monthlyActivity);
+ if (rolledUp) {
+ console.log(`📊 Rolled up old daily usage into ${Object.keys(usageData.monthlyActivity).length} monthly buckets`);
+ await saveUsage();
+ }
+
console.log(`📊 Loaded usage: ${usageData.totalSessions} sessions, ${usageData.totalMessages} messages`);
return usageData;
}
@@ -280,19 +354,22 @@ const LEGACY_BLENDED_RATES = { inputPer1M: 3.0, outputPer1M: 15.0 };
* `services/providers.getAllProviders()`), used for free-classification and
* display names — records whose provider config no longer exists fall back to
* an id-based heuristic.
+ *
+ * `monthlyActivity` (optional) is the rollup of day buckets older than the daily
+ * retention window (see `rollupOldDailyActivity`). Its buckets carry the same
+ * nested `byProvider`/`byModel` shape at month granularity, so folding them in
+ * keeps long-range totals accurate across the rollup boundary. A month bucket
+ * is whole-month-granular: it is included whenever its month overlaps
+ * `[from, to]` (rolled-up months are far older than any day-precise range).
*/
-export function buildUsageReport(dailyActivity, { from = null, to = null, providers = [] } = {}) {
+export function buildUsageReport(dailyActivity, { from = null, to = null, providers = [], monthlyActivity = null } = {}) {
const configById = new Map((providers || []).map((p) => [p.id, p]));
const agg = new Map(); // providerId -> { name, sessions, messages, tokensIn, tokensOut, byModel: Map }
let breakdownSince = null;
- for (const [date, day] of Object.entries(dailyActivity || {})) {
- if (!day?.byProvider) continue;
- if (!breakdownSince || date < breakdownSince) breakdownSince = date;
- if (from && date < from) continue;
- if (to && date > to) continue;
-
- for (const [pid, pDay] of Object.entries(day.byProvider)) {
+ // Fold one bucket's per-provider/per-model splits into the running aggregate.
+ const foldBucket = (bucket) => {
+ for (const [pid, pDay] of Object.entries(bucket.byProvider)) {
if (!agg.has(pid)) {
agg.set(pid, { name: pDay.name || pid, sessions: 0, messages: 0, tokensIn: 0, tokensOut: 0, byModel: new Map() });
}
@@ -312,6 +389,28 @@ export function buildUsageReport(dailyActivity, { from = null, to = null, provid
m.tokensOut += mDay.tokensOut || 0;
}
}
+ };
+
+ // Rolled-up monthly buckets first, so `breakdownSince` reflects the earliest
+ // month once old days have been collapsed. A `YYYY-MM` key overlaps the range
+ // whenever its month is within the from/to months (compared at month prefix).
+ const fromMonth = from ? from.slice(0, 7) : null;
+ const toMonth = to ? to.slice(0, 7) : null;
+ for (const [month, bucket] of Object.entries(monthlyActivity || {})) {
+ if (!bucket?.byProvider) continue;
+ const monthStart = `${month}-01`;
+ if (!breakdownSince || monthStart < breakdownSince) breakdownSince = monthStart;
+ if (fromMonth && month < fromMonth) continue;
+ if (toMonth && month > toMonth) continue;
+ foldBucket(bucket);
+ }
+
+ for (const [date, day] of Object.entries(dailyActivity || {})) {
+ if (!day?.byProvider) continue;
+ if (!breakdownSince || date < breakdownSince) breakdownSince = date;
+ if (from && date < from) continue;
+ if (to && date > to) continue;
+ foldBucket(day);
}
const totals = { sessions: 0, messages: 0, tokensIn: 0, tokensOut: 0, estimatedCost: 0 };
@@ -412,7 +511,7 @@ export function getUsageSummary({ from = null, to = null, providers = [] } = {})
estimatedCost: 0,
topProviders: [],
topModels: [],
- report: buildUsageReport({}, { from, to, providers })
+ report: buildUsageReport({}, { from, to, providers, monthlyActivity: {} })
};
}
@@ -430,7 +529,7 @@ export function getUsageSummary({ from = null, to = null, providers = [] } = {})
const currentStreak = calculateStreak(usageData.dailyActivity);
const longestStreak = findLongestStreak(usageData.dailyActivity);
- const report = buildUsageReport(usageData.dailyActivity, { from, to, providers });
+ const report = buildUsageReport(usageData.dailyActivity, { from, to, providers, monthlyActivity: usageData.monthlyActivity });
return {
totalSessions: usageData.totalSessions,
diff --git a/server/services/usage.test.js b/server/services/usage.test.js
index f57e460027..5b518baf3a 100644
--- a/server/services/usage.test.js
+++ b/server/services/usage.test.js
@@ -20,7 +20,7 @@ tryReadFile: vi.fn().mockResolvedValue(null),
}));
import { readJSONFile } from '../lib/fileUtils.js';
-import { loadUsage, getUsageSummary, getUsage, recordSession, recordMessages, buildUsageReport } from './usage.js';
+import { loadUsage, getUsageSummary, getUsage, recordSession, recordMessages, buildUsageReport, rollupOldDailyActivity } from './usage.js';
// Helper: produce a date string N days ago (relative to today)
function daysAgo(n) {
@@ -363,5 +363,205 @@ describe('usage.js — streak calculations', () => {
expect(report.totals).toMatchObject({ sessions: 0, estimatedCost: 0 });
expect(report.breakdownSince).toBeNull();
});
+
+ it('folds rolled-up monthly buckets into an all-time report', () => {
+ // Old cost lives in a monthly bucket (same nested shape as a day bucket);
+ // recent cost lives in daily. An unbounded report must sum both.
+ const monthlyActivity = {
+ '2024-01': nestedDay('codex', 'Codex', 'gpt-5.3-codex', { tokensOut: 1000 })
+ };
+ const daily = {
+ [daysAgo(0)]: nestedDay('codex', 'Codex', 'gpt-5.3-codex', { tokensOut: 500 })
+ };
+ const report = buildUsageReport(daily, { monthlyActivity });
+ expect(report.providers).toHaveLength(1);
+ expect(report.providers[0].tokensOut).toBe(1500); // 1000 monthly + 500 daily
+ // breakdown now reaches back to the earliest rolled-up month
+ expect(report.breakdownSince).toBe('2024-01-01');
+ });
+
+ it('includes a monthly bucket only when its month overlaps the from/to range', () => {
+ const monthlyActivity = {
+ '2024-01': nestedDay('codex', 'Codex', 'gpt-5.3-codex', { tokensOut: 100 }),
+ '2024-06': nestedDay('codex', 'Codex', 'gpt-5.3-codex', { tokensOut: 200 })
+ };
+ const report = buildUsageReport({}, { from: '2024-05-01', to: '2024-07-31', monthlyActivity });
+ // Only 2024-06 overlaps the window; 2024-01 is excluded.
+ expect(report.providers[0].tokensOut).toBe(200);
+ });
+
+ it('preserves grand totals whether old data sits in daily or monthly buckets', () => {
+ // Same underlying activity, split across the rollup boundary two ways —
+ // the all-time report totals must be identical.
+ const allDaily = buildUsageReport({
+ '2024-01-05': nestedDay('codex', 'Codex', 'gpt-5.3-codex', { tokensOut: 300 }),
+ '2024-01-06': nestedDay('codex', 'Codex', 'gpt-5.3-codex', { tokensOut: 400 })
+ }, {});
+ const rolledUp = buildUsageReport({}, {
+ monthlyActivity: { '2024-01': nestedDay('codex', 'Codex', 'gpt-5.3-codex', { sessions: 2, messages: 2, tokensOut: 700 }) }
+ });
+ expect(rolledUp.totals.tokensOut).toBe(allDaily.totals.tokensOut);
+ expect(rolledUp.totals.estimatedCost).toBeCloseTo(allDaily.totals.estimatedCost);
+ });
+ });
+});
+
+describe('usage.js — rollupOldDailyActivity (bounded growth)', () => {
+ const NOW = new Date('2026-07-12T12:00:00.000Z');
+
+ // A day key exactly `n` days before NOW.
+ function dayKey(n) {
+ const d = new Date(NOW);
+ d.setDate(d.getDate() - n);
+ return d.toISOString().split('T')[0];
+ }
+
+ it('moves day buckets older than retention into monthly buckets', () => {
+ const oldKey = dayKey(500); // > 400 days old
+ const daily = { [oldKey]: { sessions: 2, messages: 5, tokens: 100 } };
+ const monthly = {};
+
+ const changed = rollupOldDailyActivity(daily, monthly, { now: NOW });
+
+ expect(changed).toBe(true);
+ expect(daily[oldKey]).toBeUndefined();
+ const monthKey = oldKey.slice(0, 7);
+ expect(monthly[monthKey]).toEqual({ sessions: 2, messages: 5, tokens: 100 });
+ });
+
+ it('leaves recent day buckets (within retention) untouched', () => {
+ const recent = dayKey(30);
+ const daily = { [recent]: { sessions: 1, messages: 1, tokens: 10 } };
+ const monthly = {};
+
+ const changed = rollupOldDailyActivity(daily, monthly, { now: NOW });
+
+ expect(changed).toBe(false);
+ expect(daily[recent]).toEqual({ sessions: 1, messages: 1, tokens: 10 });
+ expect(monthly).toEqual({});
+ });
+
+ it('sums multiple old days in the same month into one monthly bucket', () => {
+ // Two days in the same old month.
+ const daily = {
+ '2024-01-05': { sessions: 1, messages: 2, tokens: 30 },
+ '2024-01-20': { sessions: 3, messages: 4, tokens: 70 }
+ };
+ const monthly = {};
+
+ rollupOldDailyActivity(daily, monthly, { now: NOW });
+
+ expect(monthly['2024-01']).toEqual({ sessions: 4, messages: 6, tokens: 100 });
+ expect(Object.keys(daily)).toHaveLength(0);
+ });
+
+ it('deep-sums nested per-provider/per-model splits (shape tolerance)', () => {
+ // Forward-compatible with the #2484 nested day-bucket shape.
+ const daily = {
+ '2024-01-05': {
+ sessions: 1,
+ tokens: 100,
+ byProvider: { claude: { tokens: 60, byModel: { opus: { tokens: 60 } } } }
+ },
+ '2024-01-06': {
+ sessions: 2,
+ tokens: 40,
+ byProvider: { claude: { tokens: 40, byModel: { opus: { tokens: 40 } } } }
+ }
+ };
+ const monthly = {};
+
+ rollupOldDailyActivity(daily, monthly, { now: NOW });
+
+ expect(monthly['2024-01']).toEqual({
+ sessions: 3,
+ tokens: 140,
+ byProvider: { claude: { tokens: 100, byModel: { opus: { tokens: 100 } } } }
+ });
+ });
+
+ it('drops non-numeric labels while summing counts', () => {
+ const daily = {
+ '2024-01-05': { sessions: 1, tokens: 10, name: 'Claude Code CLI' }
+ };
+ const monthly = {};
+
+ rollupOldDailyActivity(daily, monthly, { now: NOW });
+
+ expect(monthly['2024-01']).toEqual({ sessions: 1, tokens: 10 });
+ });
+
+ it('is idempotent — a second pass is a no-op and never re-processes monthly keys', () => {
+ const oldKey = dayKey(500);
+ const daily = { [oldKey]: { sessions: 2, tokens: 100 } };
+ const monthly = {};
+
+ rollupOldDailyActivity(daily, monthly, { now: NOW });
+ const afterFirst = JSON.parse(JSON.stringify(monthly));
+
+ const changedAgain = rollupOldDailyActivity(daily, monthly, { now: NOW });
+
+ expect(changedAgain).toBe(false);
+ expect(monthly).toEqual(afterFirst); // no double-counting
+ });
+
+ it('preserves grand totals across the rollup boundary', () => {
+ const daily = {
+ '2024-01-05': { sessions: 5, messages: 10, tokens: 500 }, // old → monthly
+ [dayKey(10)]: { sessions: 2, messages: 4, tokens: 200 } // recent → daily
+ };
+ const monthly = {};
+
+ rollupOldDailyActivity(daily, monthly, { now: NOW });
+
+ const sumField = (field) =>
+ Object.values(daily).reduce((a, v) => a + (v[field] || 0), 0) +
+ Object.values(monthly).reduce((a, v) => a + (v[field] || 0), 0);
+
+ expect(sumField('sessions')).toBe(7);
+ expect(sumField('messages')).toBe(14);
+ expect(sumField('tokens')).toBe(700);
+ });
+});
+
+describe('usage.js — loadUsage rollup integration', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ it('backfills monthlyActivity for pre-rollup files and rolls up old days', async () => {
+ const old = new Date();
+ old.setDate(old.getDate() - 500);
+ const oldKey = old.toISOString().split('T')[0];
+ const recent = new Date();
+ recent.setDate(recent.getDate() - 5);
+ const recentKey = recent.toISOString().split('T')[0];
+
+ // Legacy file with no monthlyActivity key at all.
+ const legacy = {
+ totalSessions: 7,
+ totalMessages: 0,
+ totalToolCalls: 0,
+ totalTokens: { input: 0, output: 0 },
+ byProvider: {},
+ byModel: {},
+ dailyActivity: {
+ [oldKey]: { sessions: 5, messages: 0, tokens: 500 },
+ [recentKey]: { sessions: 2, messages: 0, tokens: 200 }
+ },
+ hourlyActivity: Array(24).fill(0),
+ lastUpdated: null
+ };
+ readJSONFile.mockResolvedValueOnce(legacy);
+
+ await loadUsage();
+ const data = getUsage();
+
+ expect(data.monthlyActivity).toBeDefined();
+ expect(data.dailyActivity[oldKey]).toBeUndefined(); // rolled up
+ expect(data.dailyActivity[recentKey]).toBeDefined(); // retained
+ expect(data.monthlyActivity[oldKey.slice(0, 7)].tokens).toBe(500);
+ // Top-level totals are independent of bucket rollup — unchanged.
+ expect(data.totalSessions).toBe(7);
});
});