diff --git a/README.md b/README.md index 2a9e39e..ce0e8ef 100644 --- a/README.md +++ b/README.md @@ -460,6 +460,18 @@ sections above. `.meta.json`), next to a `(main session)` row; *Launches* counts `Agent` tool calls by requested `subagent_type`. The *Agents* column in period reports is the number of launches. +- **Usage limits** – the error message Claude Code writes when a plan's usage + limit stops a request (`isApiErrorMessage`, `error: "rate_limit"`, + `apiError: "usage_limit_reached"`), deduplicated by uuid. The limit type + (5-hour, weekly, weekly Opus / Sonnet, extra usage) and reset time come from + its `rate_limit_info`, or from the message text in versions that don't log + them; older versions' `Claude AI usage limit reached|` and team or + enterprise spend limits count too. Short capacity 429s that Claude Code + retries on its own (`apiErrorIsTransient`) are not usage limits. When a limit + was hit, the summary and period reports add a *Usage limits* table (hits, + sessions, last hit, median time to reset) and a summary line; JSON output + always has `usageLimits`. For Copilot: `session.error` events of type + `quota` (premium requests used up) and `rate_limit`. Cursor logs no errors. - **Cost** – estimated per request at Claude API list prices, parsed from Anthropic's [pricing page](https://platform.claude.com/docs/en/about-claude/pricing) and cached for 24h in `%LOCALAPPDATA%\ccreports` / `~/.cache/ccreports`; diff --git a/bin/ccreports.mjs b/bin/ccreports.mjs index 9f4e052..18cae69 100644 --- a/bin/ccreports.mjs +++ b/bin/ccreports.mjs @@ -16,6 +16,7 @@ import { INTENTS } from '../src/intent.mjs'; import { buildRecommendations } from '../src/recommendations.mjs'; import { openFile, FORMAT_EXTENSIONS } from '../src/open.mjs'; import { loadPlugins, loadCopilotPlugins, pluginRows, pluginsJSON } from '../src/plugins.mjs'; +import { limitStats, limitParts, limitsJSON } from '../src/limits.mjs'; import { VERSION } from '../src/version.mjs'; const HELP = `ccreports - Claude Code (and GitHub Copilot, Cursor) tool, skill, slash-command and token usage @@ -278,6 +279,11 @@ if (report === 'recommendations' || opts.recommendations) { }; } +// Usage-limit hits, in the summary and the period reports. +const usageLimits = ['adoption', 'recommendations'].includes(report) + ? null + : limitStats(data, { since, until, project: opts.project, timeZone: opts.timezone }); + let output; if (format === 'json') { const meta = { report, source, since, until, pricingSource, ccreportsVersion: VERSION }; @@ -311,6 +317,7 @@ if (format === 'json') { } else { json = { ...meta, rows: result.buckets.map(toJSON), totals: toJSON(result.totals), plugins: pluginsJSON(plugins) }; } + if (usageLimits) json.usageLimits = limitsJSON(usageLimits); if (adoptionJson && report !== 'adoption') json.adoption = adoptionJson; if (advice && report !== 'recommendations') json.recommendations = advice.items; output = JSON.stringify(json, null, 2) + '\n'; @@ -320,7 +327,8 @@ if (format === 'json') { const own = { adoption, intents: intentDoc, recommendations: advice }[report]; let doc = own ?? (report === 'summary' ? buildSummary(result, docOpts) : buildPeriodReport(report, result, docOpts)); // Appended parts: their summary lines on top, their sections after the report's own. - for (const part of [adoption, advice]) { + const limitDoc = usageLimits && limitParts(usageLimits, { timeZone: opts.timezone }); + for (const part of [limitDoc, adoption, advice]) { if (!part || part === doc) continue; doc = { ...doc, summary: [...(doc.summary ?? []), ...part.summary], sections: [...doc.sections, ...part.sections] }; } diff --git a/skills/report/SKILL.md b/skills/report/SKILL.md index f7bd16e..0f2b228 100644 --- a/skills/report/SKILL.md +++ b/skills/report/SKILL.md @@ -25,6 +25,7 @@ the request: | The user wants | Command | |---|---| | an overview, totals, top tools / skills / commands / hooks / models | `summary` (default) | +| how often they hit a usage limit (5-hour, weekly, Copilot quota) | `summary`, or `daily` / `weekly` for when; `-j` for each hit | | which plugins are installed (version, enabled) and whether they're used | any report (its *Installed plugins* table), e.g. `summary` | | a trend over time | `daily`, `weekly` or `monthly` | | per conversation or per repository | `session` or `project` | @@ -107,6 +108,9 @@ of every table. Keep these caveats in mind and mention them when relevant: - Tokens per tool / skill (shown with `~`) are reconstructed from context growth and include re-reads of the result in later requests; subagent tokens are exact. - Context size counts the main conversation only. +- Usage limits (the *Usage limits* table, `usageLimits` in JSON) count the times + a plan's 5-hour, weekly or spend limit, or Copilot's premium request quota or + rate limit, stopped a session. The table only appears when one was hit. - The adoption phases are per session, from the user's own logs; PRs are those Claude Code created. - Session intent (bug fix, new development, refactoring, ...) comes from rules diff --git a/src/copilot.mjs b/src/copilot.mjs index 72ce3e2..da234d9 100644 --- a/src/copilot.mjs +++ b/src/copilot.mjs @@ -24,6 +24,7 @@ import { FileAttribution, createCalibration, charsPerToken, resolveTokens } from import { shellCommands } from './shell.mjs'; import { errorLine, normalizeSkillName, patchFiles } from './loader.mjs'; import { promptText, workMessages } from './intent.mjs'; +import { copilotLimit } from './limits.mjs'; const NANO_AIU_PER_USD = 1e11; const SHELLS = { powershell: 'PowerShell', bash: 'Bash' }; @@ -112,6 +113,7 @@ export async function loadCopilotRecords({ dirs = defaultCopilotDirs(), includeS const skills = new Map(); const commands = new Map(); const hooks = new Map(); + const limits = new Map(); // event id -> usage-limit hit const titles = new Map(); const sessions = new Map(); const psNames = new Map(); @@ -188,6 +190,13 @@ export async function loadCopilotRecords({ dirs = defaultCopilotDirs(), includeS if (d.agentId) agentTypes.set(d.agentId, data.agentType || data.agentName || 'general-purpose'); break; + case 'session.error': { + // Premium request quota used up (402) or rate limited (429): the request is not answered. + const hit = copilotLimit(data); + if (hit) limits.set(d.id ?? `${id}:${d.timestamp}`, { ...base(), ...hit }); + break; + } + case 'session.compaction_complete': if (data.success === false) break; attributionOf(d.agentId).compact(); @@ -431,6 +440,7 @@ export async function loadCopilotRecords({ dirs = defaultCopilotDirs(), includeS skills: [...skills.values()], commands: [...commands.values()], hooks: [...hooks.values()], + limits: [...limits.values()], titles, }; } @@ -447,11 +457,12 @@ export function mergeData(...parts) { skills: [...first.skills], commands: [...first.commands], hooks: [...first.hooks], + limits: [...(first.limits ?? [])], events: [...(first.events ?? [])], }; for (const p of rest) { out.files += p.files; - for (const k of ['usage', 'tools', 'skills', 'commands', 'hooks', 'events']) out[k].push(...(p[k] ?? [])); + for (const k of ['usage', 'tools', 'skills', 'commands', 'hooks', 'events', 'limits']) out[k].push(...(p[k] ?? [])); for (const [k, v] of p.sessions) out.sessions.set(k, v); for (const [k, v] of p.titles) out.titles.set(k, v); } diff --git a/src/cursor.mjs b/src/cursor.mjs index 82ef6f8..66d94e0 100644 --- a/src/cursor.mjs +++ b/src/cursor.mjs @@ -343,6 +343,7 @@ export async function loadCursorRecords({ dirs = defaultCursorDirs(), userDirs = skills, commands, hooks: [], + limits: [], // Cursor logs no errors events, titles, }; diff --git a/src/limits.mjs b/src/limits.mjs new file mode 100644 index 0000000..1451a8b --- /dev/null +++ b/src/limits.mjs @@ -0,0 +1,129 @@ +// Usage limits: the times a session was stopped because the plan's usage limit +// was reached (Claude Code's 5-hour or weekly limits, a spend limit; Copilot's +// premium request quota or its rate limit). Short capacity hiccups the client +// retries on its own are not usage limits and are left out. + +import { recordFilter, dateFormatter } from './aggregate.mjs'; + +export const LIMIT_KINDS = { + five_hour: '5-hour limit', + seven_day: 'Weekly limit', + seven_day_opus: 'Weekly Opus limit', + seven_day_sonnet: 'Weekly Sonnet limit', + seven_day_overage_included: 'Weekly limit (with extra usage)', + overage: 'Extra usage limit', + spend: 'Spend limit', + quota: 'Premium request quota', + rate_limit: 'Rate limit', + unknown: 'Usage limit', +}; + +const USAGE_TEXT = /usage limit|limit reached|hit your [\w -]*limit|limit (will )?resets?|resets? (at|in) /i; +const LEGACY = /^Claude AI usage limit reached\|(\d{9,})/; // older Claude Code: "…|" + +function kindFromText(text) { + if (/opus/i.test(text) && /week|7-day/i.test(text)) return 'seven_day_opus'; + if (/sonnet/i.test(text) && /week|7-day/i.test(text)) return 'seven_day_sonnet'; + if (/week|7-day/i.test(text)) return 'seven_day'; + if (/5-hour|five-hour|session limit/i.test(text)) return 'five_hour'; + return 'unknown'; +} + +const isoFromEpoch = (seconds) => { + const n = Number(seconds); + if (!Number.isFinite(n) || n <= 0) return null; + return new Date(n < 1e12 ? n * 1000 : n).toISOString(); +}; + +/** + * A Claude Code transcript line that reports a usage limit: { kind, resetsAt } + * or null. `text` is the message's text. + */ +export function claudeLimit(d, text) { + const legacy = LEGACY.exec(text); + if (legacy) return { kind: 'five_hour', resetsAt: isoFromEpoch(legacy[1]) }; + if (!d?.isApiErrorMessage) return null; + if (d.error === 'billing_error' && /spend limit|monthly (spend|usage) limit/i.test(text)) return { kind: 'spend', resetsAt: null }; + const info = d.apiErrorParams?.rate_limit_info; + const usage = d.apiError === 'usage_limit_reached' || (d.error === 'rate_limit' && !d.apiErrorIsTransient && USAGE_TEXT.test(text)); + if (!usage) return null; + const kind = info?.rateLimitType in LIMIT_KINDS ? info.rateLimitType : /spend limit/i.test(text) ? 'spend' : kindFromText(text); + return { kind, resetsAt: isoFromEpoch(info?.resetsAt) }; +} + +/** A Copilot session.error event's data that reports a usage limit: { kind, resetsAt } or null. */ +export function copilotLimit(data) { + if (data?.errorType === 'quota' || data?.statusCode === 402) return { kind: 'quota', resetsAt: null }; + if (data?.errorType === 'rate_limit') return { kind: 'rate_limit', resetsAt: null }; + return null; +} + +const median = (values) => { + if (!values.length) return null; + const v = [...values].sort((a, b) => a - b); + const mid = Math.floor(v.length / 2); + return v.length % 2 ? v[mid] : (v[mid - 1] + v[mid]) / 2; +}; + +/** Usage-limit hits in the selected range, per kind. */ +export function limitStats(data, { since, until, project, timeZone } = {}) { + const inRange = recordFilter({ since, until, project, timeZone }); + const hits = (data.limits ?? []).filter((h) => inRange(h)).sort((a, b) => (a.timestamp < b.timestamp ? -1 : 1)); + const kinds = new Map(); + for (const h of hits) { + const k = kinds.get(h.kind) ?? { kind: h.kind, title: LIMIT_KINDS[h.kind] ?? LIMIT_KINDS.unknown, hits: 0, sessions: new Set(), lastHit: null, waits: [] }; + k.hits += 1; + k.sessions.add(h.sessionId); + k.lastHit = h.timestamp; + if (h.resetsAt && h.resetsAt > h.timestamp) k.waits.push(Date.parse(h.resetsAt) - Date.parse(h.timestamp)); + kinds.set(h.kind, k); + } + const byKind = [...kinds.values()] + .sort((a, b) => b.hits - a.hits) + .map(({ waits, sessions, ...k }) => ({ ...k, sessions: sessions.size, medianWaitMs: median(waits) })); + return { hits, byKind, sessions: new Set(hits.map((h) => h.sessionId)).size }; +} + +/** "2h 15m", "3d 4h", "40m". */ +export function duration(ms) { + if (ms == null) return ''; + const m = Math.round(ms / 60000); + if (m < 60) return `${m}m`; + const h = Math.floor(m / 60); + if (h < 48) return m % 60 ? `${h}h ${m % 60}m` : `${h}h`; + return `${Math.floor(h / 24)}d ${h % 24}h`; +} + +const right = (title) => ({ title, align: 'right' }); +const left = (title) => ({ title, align: 'left' }); + +/** Report sections and summary line; nothing when no limit was hit. */ +export function limitParts(stats, { timeZone } = {}) { + if (!stats.hits.length) return { summary: [], sections: [] }; + const day = dateFormatter(timeZone); + const last = stats.hits.at(-1); + const times = stats.hits.length === 1 ? 'once' : `${stats.hits.length} times`; + return { + summary: [ + `A usage limit stopped ${stats.sessions} session${stats.sessions === 1 ? '' : 's'} ${times}; the last was a ${LIMIT_KINDS[last.kind]?.toLowerCase() ?? 'usage limit'} on ${day(last.timestamp)}.`, + ], + sections: [ + { + title: 'Usage limits', + note: 'times a session was stopped until the limit reset', + columns: [left('Limit'), right('Hits'), right('Sessions'), left('Last hit'), right('Median time to reset')], + rows: stats.byKind.map((k) => ({ cells: [k.title, k.hits, k.sessions, day(k.lastHit), duration(k.medianWaitMs)] })), + }, + ], + }; +} + +/** For --json. */ +export function limitsJSON(stats) { + return { + hits: stats.hits.length, + sessions: stats.sessions, + byKind: stats.byKind, + events: stats.hits.map(({ timestamp, sessionId, project, agent, source, kind, resetsAt }) => ({ timestamp, sessionId, project, agent, source, kind, resetsAt })), + }; +} diff --git a/src/loader.mjs b/src/loader.mjs index 6ae1c45..c55b731 100644 --- a/src/loader.mjs +++ b/src/loader.mjs @@ -13,6 +13,7 @@ import path from 'node:path'; import { FileAttribution, createCalibration, charsPerToken, resolveTokens } from './attribution.mjs'; import { SHELL_TOOLS, shellCommands } from './shell.mjs'; import { promptText, workMessages } from './intent.mjs'; +import { claudeLimit } from './limits.mjs'; const SKILL_CONTENT_PREFIX = 'Base directory for this skill'; const COMMAND_RE = /([^<]+)<\/command-name>/; @@ -111,6 +112,7 @@ export async function loadRecords({ dirs = defaultProjectDirs(), includeSubagent const skills = new Map(); // tool_use id | user-message uuid -> record const commands = new Map(); // user-message uuid -> record const hooks = new Map(); // attachment uuid -> record + const limits = new Map(); // error-message uuid -> usage-limit hit const titles = new Map(); // sessionId -> ai title // sessionId -> { entrypoint, prompts: Set, prs: Set, compactions: Set, modes: Set, // branches: Set, firstPrompt, workMessages: Map } (adoption / recommendations) @@ -244,6 +246,11 @@ export async function loadRecords({ dirs = defaultProjectDirs(), includeSubagent } if (d.type === 'assistant') { + // A usage limit stopped the request: Claude Code writes its own error message. + if (d.isApiErrorMessage || d.message?.model === '') { + const hit = claudeLimit(d, textOf(d.message?.content)); + if (hit) limits.set(d.uuid ?? `${file}:${base.timestamp}`, { ...base, source: 'claude', ...hit }); + } const m = d.message ?? {}; const u = m.usage; const key = m.id ? `${m.id}:${d.requestId ?? ''}` : d.uuid; @@ -350,7 +357,7 @@ export async function loadRecords({ dirs = defaultProjectDirs(), includeSubagent attributed.push(...attribution.finish()); } - for (const map of [usage, tools, skills, commands, hooks]) { + for (const map of [usage, tools, skills, commands, hooks, limits]) { for (const rec of map.values()) rec.project = sessionStart.get(rec.sessionId)?.cwd ?? rec.project; } @@ -380,6 +387,7 @@ export async function loadRecords({ dirs = defaultProjectDirs(), includeSubagent skills: [...skills.values()], commands: [...commands.values()], hooks: [...hooks.values()], + limits: [...limits.values()], titles, }; } diff --git a/test/limits.test.mjs b/test/limits.test.mjs new file mode 100644 index 0000000..1032caa --- /dev/null +++ b/test/limits.test.mjs @@ -0,0 +1,155 @@ +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { mkdtemp, mkdir, writeFile, rm } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import path from 'node:path'; +import { loadRecords } from '../src/loader.mjs'; +import { loadCopilotRecords } from '../src/copilot.mjs'; +import { claudeLimit, copilotLimit, limitStats, limitParts, limitsJSON, duration } from '../src/limits.mjs'; +import { toMarkdown } from '../src/formats.mjs'; + +// Claude Code's own error message for a request a usage limit stopped (as written by 2.1.x). +const limitMessage = (ts, uuid, extra = {}, text = "You've hit your limit · resets 3pm (Europe/Amsterdam)") => ({ + type: 'assistant', + sessionId: 's1', + cwd: '/work/app', + timestamp: ts, + uuid, + isApiErrorMessage: true, + error: 'rate_limit', + message: { id: uuid, model: '', role: 'assistant', content: [{ type: 'text', text }] }, + ...extra, +}); + +test('claudeLimit: usage limits, not other errors or transient 429s', () => { + const text = (d) => d.message.content[0].text; + const resetsAt = Date.parse('2026-10-01T15:00:00Z') / 1000; + const structured = limitMessage('2026-10-01T12:00:00Z', 'a', { + apiError: 'usage_limit_reached', + apiErrorParams: { rate_limit_info: { status: 'rejected', resetsAt, rateLimitType: 'seven_day_opus' } }, + }); + assert.deepEqual(claudeLimit(structured, text(structured)), { kind: 'seven_day_opus', resetsAt: '2026-10-01T15:00:00.000Z' }); + + // Only the text: the kind comes from it. + const weekly = limitMessage('2026-10-01T12:00:00Z', 'b', {}, 'Weekly limit reached · resets Oct 9, 10am'); + assert.deepEqual(claudeLimit(weekly, text(weekly)), { kind: 'seven_day', resetsAt: null }); + const plain = limitMessage('2026-10-01T12:00:00Z', 'c'); + assert.equal(claudeLimit(plain, text(plain)).kind, 'unknown'); + + // Older Claude Code: "Claude AI usage limit reached|". + assert.deepEqual(claudeLimit({ message: { model: '' } }, `Claude AI usage limit reached|${resetsAt}`), { + kind: 'five_hour', + resetsAt: '2026-10-01T15:00:00.000Z', + }); + + // Spend limits on team / enterprise plans. + const spend = limitMessage('2026-10-01T12:00:00Z', 'd', { error: 'billing_error' }, "You've hit your monthly spend limit."); + assert.equal(claudeLimit(spend, text(spend)).kind, 'spend'); + + // Not usage limits: a capacity hiccup retried by the client, login and server errors. + const transient = limitMessage('2026-10-01T12:00:00Z', 'e', { apiErrorIsTransient: true }, 'API Error: Request rejected (429) · this may be a temporary capacity issue.'); + assert.equal(claudeLimit(transient, text(transient)), null); + const login = limitMessage('2026-10-01T12:00:00Z', 'f', { error: 'authentication_failed' }, 'Login expired · Please run /login'); + assert.equal(claudeLimit(login, text(login)), null); + const server = limitMessage('2026-10-01T12:00:00Z', 'g', { error: 'server_error' }, 'API Error: Connection lost mid-response.'); + assert.equal(claudeLimit(server, text(server)), null); + // Ordinary assistant text that mentions limits. + assert.equal(claudeLimit({ message: { model: 'claude-opus-5-5' } }, 'The usage limit resets at 3pm.'), null); +}); + +test('copilotLimit: premium request quota and rate limit', () => { + assert.deepEqual(copilotLimit({ errorType: 'quota', statusCode: 402, message: 'Quota exceeded.' }), { kind: 'quota', resetsAt: null }); + assert.deepEqual(copilotLimit({ errorType: 'rate_limit', statusCode: 429 }), { kind: 'rate_limit', resetsAt: null }); + assert.equal(copilotLimit({ errorType: 'query', statusCode: 400, message: '"llama3.2" does not support thinking' }), null); +}); + +test('Claude Code loader records usage-limit hits once, resumed copies included', async () => { + const root = await mkdtemp(path.join(tmpdir(), 'ccreports-')); + try { + const proj = path.join(root, '-work-app'); + await mkdir(proj, { recursive: true }); + const resetsAt = Date.parse('2026-10-01T15:00:00Z') / 1000; + const hit = limitMessage('2026-10-01T12:00:00Z', 'l1', { + apiError: 'usage_limit_reached', + apiErrorParams: { rate_limit_info: { status: 'rejected', resetsAt, rateLimitType: 'five_hour' } }, + }); + const lines = [ + { type: 'user', sessionId: 's1', cwd: '/work/app', timestamp: '2026-10-01T11:59:00Z', uuid: 'u1', message: { role: 'user', content: 'go on' } }, + hit, + limitMessage('2026-10-01T12:01:00Z', 'l2', { error: 'server_error' }, 'API Error: Connection lost mid-response.'), + ]; + await writeFile(path.join(proj, 's1.jsonl'), lines.map((l) => JSON.stringify(l)).join('\n') + '\n'); + await writeFile(path.join(proj, 's1-resumed.jsonl'), JSON.stringify(hit) + '\n'); + const data = await loadRecords({ dirs: [root] }); + assert.equal(data.limits.length, 1); + assert.deepEqual( + { ...data.limits[0] }, + { timestamp: '2026-10-01T12:00:00Z', sessionId: 's1', project: '/work/app', agent: null, source: 'claude', kind: 'five_hour', resetsAt: '2026-10-01T15:00:00.000Z' }, + ); + assert.equal(data.usage.length, 0); // the synthetic message is not usage + } finally { + await rm(root, { recursive: true, force: true }); + } +}); + +test('Copilot loader records quota and rate-limit errors', async () => { + const root = await mkdtemp(path.join(tmpdir(), 'ccreports-copilot-')); + try { + const ev = (type, timestamp, data) => ({ type, data, id: `${type}-${timestamp}`, timestamp }); + const events = [ + ev('session.start', '2026-10-01T10:00:00Z', { sessionId: 'c1', context: { cwd: '/work/app' } }), + ev('user.message', '2026-10-01T10:00:01Z', { content: 'add a button' }), + ev('session.error', '2026-10-01T10:00:02Z', { errorType: 'quota', message: 'Quota exceeded.', statusCode: 402 }), + ev('session.error', '2026-10-01T10:05:00Z', { errorType: 'rate_limit', message: 'Sorry, you have exceeded your rate limit.', statusCode: 429 }), + ev('session.error', '2026-10-01T10:06:00Z', { errorType: 'query', message: 'model not found', statusCode: 400 }), + ]; + await mkdir(path.join(root, 'c1'), { recursive: true }); + await writeFile(path.join(root, 'c1', 'events.jsonl'), events.map((e) => JSON.stringify(e)).join('\n') + '\n'); + const data = await loadCopilotRecords({ dirs: [root] }); + assert.deepEqual(data.limits.map((l) => [l.kind, l.sessionId, l.project, l.source]), [ + ['quota', 'c1', '/work/app', 'copilot'], + ['rate_limit', 'c1', '/work/app', 'copilot'], + ]); + } finally { + await rm(root, { recursive: true, force: true }); + } +}); + +test('limitStats and limitParts: hits per limit, sessions, time to reset; nothing without hits', () => { + const hit = (timestamp, sessionId, kind, resetsAt = null) => ({ timestamp, sessionId, project: '/p', agent: null, source: 'claude', kind, resetsAt }); + const data = { + limits: [ + hit('2026-10-01T12:00:00Z', 's1', 'five_hour', '2026-10-01T15:00:00Z'), + hit('2026-10-02T09:00:00Z', 's2', 'five_hour', '2026-10-02T10:00:00Z'), + hit('2026-10-02T09:30:00Z', 's2', 'five_hour', '2026-10-02T10:00:00Z'), + hit('2026-10-05T18:00:00Z', 's3', 'seven_day'), + hit('2026-09-01T12:00:00Z', 's0', 'seven_day'), // before --since + ], + }; + const stats = limitStats(data, { since: '2026-10-01', timeZone: 'UTC' }); + assert.equal(stats.hits.length, 4); + assert.equal(stats.sessions, 3); + assert.deepEqual(stats.byKind, [ + { kind: 'five_hour', title: '5-hour limit', hits: 3, lastHit: '2026-10-02T09:30:00Z', sessions: 2, medianWaitMs: 60 * 60_000 }, + { kind: 'seven_day', title: 'Weekly limit', hits: 1, lastHit: '2026-10-05T18:00:00Z', sessions: 1, medianWaitMs: null }, + ]); + + const parts = limitParts(stats, { timeZone: 'UTC' }); + assert.deepEqual(parts.summary, ['A usage limit stopped 3 sessions 4 times; the last was a weekly limit on 2026-10-05.']); + assert.deepEqual(parts.sections[0].rows.map((r) => r.cells), [ + ['5-hour limit', 3, 2, '2026-10-02', '1h'], + ['Weekly limit', 1, 1, '2026-10-05', ''], + ]); + assert.match(toMarkdown({ title: 'x', ...parts }), /## Usage limits/); + assert.equal(limitsJSON(stats).events.length, 4); + + const none = limitParts(limitStats({ limits: [] }, {}), {}); + assert.deepEqual(none, { summary: [], sections: [] }); +}); + +test('duration formats minutes, hours and days', () => { + assert.equal(duration(40 * 60_000), '40m'); + assert.equal(duration(135 * 60_000), '2h 15m'); + assert.equal(duration(76 * 3_600_000), '3d 4h'); + assert.equal(duration(null), ''); +});