diff --git a/CHANGELOG.md b/CHANGELOG.md index 21b7c4fd..7aaad9b0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,14 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/). ## [Unreleased] +## [1.23.0] - 2026-06-24 + +### Added +- **`kit memory stats` becomes a real instrument — recall count + token economy.** Beyond sessions/messages/tool-uses, `kit memory stats` now reports: **tokens** (input/output totals from the indexed transcripts — already captured per message; `--tokens` adds tokens/message, tokens/session, a by-model breakdown, and a **cache-hit ratio**), **recalls** (how often the store is actually searched — net-new `query_log` records each `kit memory search` with its hit count; surfaces total/last-7d/distinct/top-terms), a **logical-vs-sidechain session split** + transcript-files-indexed (exposes the "N files → M logical sessions" collapse), and `--heatmap` (a per-day activity sparkline over the last 90 days). All local-first, zero-LLM, sourced from the same SQLite DB + transcripts kit already owns. Pure `summarizeTokens`/`sparkline` fixture-tested; schema migrated to v4 (cache-token columns on `messages`, new `query_log`). Cache-hit ratio is `n/a` until cache data accumulates (forward-only; older rows predate the columns). + +### Fixed +- **`kit memory search` no longer leaks a space-form flag value into the query.** `--limit 3` / `--project /p` (space form) previously kept the value token (`3`) as a search term, polluting both the FTS query and (now) the recall log; the value is now consumed. The `--flag=value` form was unaffected. + ## [1.22.0] - 2026-06-23 ### Added diff --git a/package-lock.json b/package-lock.json index c630a1dc..9068a1de 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "sandstream-kit", - "version": "1.22.0", + "version": "1.23.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "sandstream-kit", - "version": "1.22.0", + "version": "1.23.0", "license": "MIT", "workspaces": [ "packages/*" diff --git a/package.json b/package.json index 36897743..dc76ac1b 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "sandstream-kit", - "version": "1.22.0", + "version": "1.23.0", "description": "developer kit. zero LLM, local-first, multi-vault. one command from git clone to working dev environment.", "license": "MIT", "funding": "https://buymeacoffee.com/sandstream", diff --git a/src/commands/memory.ts b/src/commands/memory.ts index afaea4bb..efb01660 100644 --- a/src/commands/memory.ts +++ b/src/commands/memory.ts @@ -4,7 +4,15 @@ import { c } from "../utils/colors.js"; import { hasFlag, flagValue } from "../utils/flags.js"; import { existsSync } from "node:fs"; import { basename } from "node:path"; -import { openMemoryDb, getStats, getMemoryDbPath, searchMessages } from "../memory/db.js"; +import { + openMemoryDb, + getStats, + getMemoryDbPath, + searchMessages, + recordQuery, + dailyActivity, +} from "../memory/db.js"; +import { sparkline, fmtTokens } from "../memory/stats.js"; import { indexAllHarnesses } from "../memory/parser.js"; import { mergeDb } from "../memory/merge.js"; import { buildSuggestPrompt } from "../memory/suggest.js"; @@ -274,23 +282,73 @@ async function memMerge(): Promise { async function memStats(): Promise { const jsonMode = hasFlag(process.argv, "--json"); + const tokensMode = hasFlag(process.argv, "--tokens"); + const heatmapMode = hasFlag(process.argv, "--heatmap"); const db = openMemoryDb(); const s = getStats(db); + const activity = heatmapMode ? dailyActivity(db, 90) : []; db.close(); if (jsonMode) { - console.log(JSON.stringify(s)); + console.log(JSON.stringify(heatmapMode ? { ...s, activity } : s)); return true; } + + const pct = (r: number | null): string => (r === null ? "n/a" : `${(r * 100).toFixed(0)}%`); + console.log(`${c.bold}kit memory${c.reset} ${c.dim}${s.dbPath}${c.reset}`); console.log(` sessions ${s.sessions}`); if (s.byHarness.length > 1) { const breakdown = s.byHarness.map((h) => `${h.harness} ${h.sessions}`).join(", "); console.log(` ${c.dim}${breakdown}${c.reset}`); } + console.log( + ` ${c.dim}${s.sessionsBreakdown.logical} logical, ${s.sessionsBreakdown.sidechain} sidechain · ${s.sessionsBreakdown.filesIndexed} transcript files indexed${c.reset}`, + ); console.log(` messages ${s.messages}`); console.log(` tool-uses ${s.toolUses}`); + console.log( + ` tokens ${fmtTokens(s.tokens.totalTokens)} ${c.dim}(${fmtTokens(s.tokens.inputTokens)} in / ${fmtTokens(s.tokens.outputTokens)} out · cache-hit ${pct(s.tokens.cacheHitRatio)})${c.reset}`, + ); + console.log( + ` recalls ${s.recalls.total} ${c.dim}(${s.recalls.last7d} last 7d · ${s.recalls.distinctQueries} distinct queries)${c.reset}`, + ); console.log(` pending ${s.pendingOpen} ${c.dim}(open action items)${c.reset}`); console.log(` size ${Math.round(s.sizeBytes / 1024)} KB`); + console.log( + ` ${c.dim}account-wide /stats may exceed this — sessions on other machines aren't in this DB${c.reset}`, + ); + + if (tokensMode) { + console.log(`\n${c.bold}token economy${c.reset}`); + console.log( + ` ${fmtTokens(s.tokens.perMessage)}/message · ${fmtTokens(s.tokens.perSession)}/session`, + ); + console.log( + ` cache: ${fmtTokens(s.tokens.cacheReadTokens)} read / ${fmtTokens(s.tokens.cacheCreationTokens)} created${c.reset}`, + ); + if (s.tokens.byModel.length) { + console.log(` ${c.dim}by model:${c.reset}`); + for (const m of s.tokens.byModel) { + console.log( + ` ${m.model} ${c.dim}${m.messages} msgs · ${fmtTokens(m.inputTokens)} in / ${fmtTokens(m.outputTokens)} out${c.reset}`, + ); + } + } + if (s.recalls.topTerms.length) { + console.log(` ${c.dim}top recalls:${c.reset}`); + for (const term of s.recalls.topTerms) { + console.log(` ${term.count}× ${c.dim}${term.query}${c.reset}`); + } + } + } + + if (heatmapMode) { + console.log(`\n${c.bold}activity${c.reset} ${c.dim}(last 90 days, messages/day)${c.reset}`); + console.log(` ${sparkline(activity.map((a) => a.count))}`); + if (activity.length) { + console.log(` ${c.dim}${activity[0].day} → ${activity[activity.length - 1].day}${c.reset}`); + } + } return true; } @@ -313,7 +371,19 @@ async function memSuggest(): Promise { async function memSearch(): Promise { const jsonMode = hasFlag(process.argv, "--json"); - const terms = process.argv.slice(4).filter((a) => !a.startsWith("--")); + // Extract positional query terms, skipping flags AND the value of space-form + // value-flags (`--limit 3` / `--project /p`) so "3" doesn't leak into the query. + const VALUE_FLAGS = new Set(["--limit", "--project"]); + const rawArgs = process.argv.slice(4); + const terms: string[] = []; + for (let i = 0; i < rawArgs.length; i++) { + const a = rawArgs[i]; + if (a.startsWith("--")) { + if (VALUE_FLAGS.has(a)) i++; // consume the following value token + continue; + } + terms.push(a); + } const query = terms.join(" ").trim(); if (!query) { console.error( @@ -327,6 +397,12 @@ async function memSearch(): Promise { : (flagValue(process.argv, "--project") ?? getCurrentProjectRoot()); const db = openMemoryDb(); const hits = searchMessages(db, query, { limit, projectPath }); + // Record the recall (query_log) — best-effort; never let logging break search. + try { + recordQuery(db, { query, hitCount: hits.length, projectPath }); + } catch { + // logging is non-critical + } db.close(); if (jsonMode) { console.log(JSON.stringify(hits)); diff --git a/src/memory/db.test.ts b/src/memory/db.test.ts index 4f00e7df..add71987 100644 --- a/src/memory/db.test.ts +++ b/src/memory/db.test.ts @@ -7,6 +7,8 @@ import { insertMessage, searchMessages, getStats, + recordQuery, + dailyActivity, toFtsMatchQuery, } from "./db.js"; @@ -164,4 +166,83 @@ describe("memory db", () => { assert.deepEqual(scoped.map((h) => h.uuid).sort(), ["a", "c"]); db.close(); }); + + it("getStats aggregates tokens (incl cache-hit) from message rows", () => { + const db = fresh(); + upsertSession(db, { sessionId: "s1", harness: "claude-code" }); + insertMessage(db, { + uuid: "a", + sessionId: "s1", + type: "assistant", + model: "claude-opus-4-8", + content: "hi", + inputTokens: 100, + outputTokens: 50, + cacheReadTokens: 300, + cacheCreationTokens: 100, + }); + const s = getStats(db); + assert.equal(s.tokens.totalTokens, 150); + assert.equal(s.tokens.cacheReadTokens, 300); + assert.equal(s.tokens.cacheHitRatio, 0.6); // 300/(100+300+100) + assert.equal(s.tokens.perMessage, 150); // 150 tokens / 1 message + assert.equal(s.tokens.byModel[0].model, "claude-opus-4-8"); + db.close(); + }); + + it("recordQuery feeds getStats recall counts + top terms", () => { + const db = fresh(); + recordQuery(db, { query: "stripe webhook", hitCount: 3, projectPath: "/repo" }); + recordQuery(db, { query: "stripe webhook", hitCount: 1 }); + recordQuery(db, { query: "rls policy", hitCount: 0 }); + const s = getStats(db); + assert.equal(s.recalls.total, 3); + assert.equal(s.recalls.last7d, 3); // all just inserted + assert.equal(s.recalls.distinctQueries, 2); + assert.equal(s.recalls.topTerms[0].query, "stripe webhook"); + assert.equal(s.recalls.topTerms[0].count, 2); + db.close(); + }); + + it("getStats splits logical vs sidechain sessions", () => { + const db = fresh(); + upsertSession(db, { sessionId: "main", harness: "claude-code", isAgentSidechain: false }); + upsertSession(db, { sessionId: "sub", harness: "claude-code", isAgentSidechain: true }); + const s = getStats(db); + assert.equal(s.sessions, 2); + assert.equal(s.sessionsBreakdown.logical, 1); + assert.equal(s.sessionsBreakdown.sidechain, 1); + db.close(); + }); + + it("dailyActivity groups messages by day", () => { + const db = fresh(); + upsertSession(db, { sessionId: "s1", harness: "claude-code" }); + insertMessage(db, { + uuid: "a", + sessionId: "s1", + type: "user", + content: "x", + timestamp: "2026-06-20T10:00:00.000Z", + }); + insertMessage(db, { + uuid: "b", + sessionId: "s1", + type: "user", + content: "y", + timestamp: "2026-06-20T11:00:00.000Z", + }); + // far-past row is outside the default 90-day window + insertMessage(db, { + uuid: "old", + sessionId: "s1", + type: "user", + content: "z", + timestamp: "2000-01-01T00:00:00.000Z", + }); + const days = dailyActivity(db, 100_000); // wide window to capture both buckets + const jun20 = days.find((d) => d.day === "2026-06-20"); + assert.equal(jun20?.count, 2); + db.close(); + }); }); diff --git a/src/memory/db.ts b/src/memory/db.ts index 448eb2a2..e9689d60 100644 --- a/src/memory/db.ts +++ b/src/memory/db.ts @@ -17,8 +17,9 @@ import { homedir } from "node:os"; import { join } from "node:path"; import { existsSync, mkdirSync, chmodSync, statSync } from "node:fs"; import type { MemoryStats, MessageInput, SearchHit, SessionInput, ToolUseInput } from "./types.js"; +import { summarizeTokens } from "./stats.js"; -export const SCHEMA_VERSION = 3; +export const SCHEMA_VERSION = 4; export function getMemoryDir(): string { return process.env.KIT_MEMORY_DIR ?? join(homedir(), ".kit"); @@ -56,6 +57,8 @@ CREATE TABLE IF NOT EXISTS messages ( model TEXT, input_tokens INTEGER, output_tokens INTEGER, + cache_read_input_tokens INTEGER, + cache_creation_input_tokens INTEGER, timestamp TEXT, cwd TEXT, git_branch TEXT, @@ -102,11 +105,21 @@ CREATE TABLE IF NOT EXISTS file_index ( indexed_at TEXT DEFAULT CURRENT_TIMESTAMP ); +CREATE TABLE IF NOT EXISTS query_log ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + query TEXT NOT NULL, + hit_count INTEGER NOT NULL DEFAULT 0, + project_path TEXT, + harness TEXT, + executed_at TEXT DEFAULT CURRENT_TIMESTAMP +); + CREATE INDEX IF NOT EXISTS idx_messages_session ON messages(session_id); CREATE INDEX IF NOT EXISTS idx_messages_type ON messages(type); CREATE INDEX IF NOT EXISTS idx_messages_timestamp ON messages(timestamp); CREATE INDEX IF NOT EXISTS idx_tool_uses_tool ON tool_uses(tool_name); CREATE INDEX IF NOT EXISTS idx_pending_status ON pending_actions(status); +CREATE INDEX IF NOT EXISTS idx_query_log_executed ON query_log(executed_at); CREATE VIRTUAL TABLE IF NOT EXISTS messages_fts USING fts5( content, @@ -143,6 +156,11 @@ function migrate(db: DatabaseSync): void { // shell verify_cmd). Legacy verify_cmd rows have a NULL verify_check and are // never auto-executed. ensureColumn(db, "pending_actions", "verify_check", "TEXT"); + // v4: prompt-cache token columns on messages (cache-hit economy). Older rows + // stay NULL — cache stats populate going forward (input/output were always + // captured); query_log is created by SCHEMA_SQL above. + ensureColumn(db, "messages", "cache_read_input_tokens", "INTEGER"); + ensureColumn(db, "messages", "cache_creation_input_tokens", "INTEGER"); const row = db.prepare("SELECT version FROM schema_meta LIMIT 1").get() as | { version: number } | undefined; @@ -226,8 +244,8 @@ export function insertMessage(db: DatabaseSync, m: MessageInput): boolean { const res = db .prepare( `INSERT OR IGNORE INTO messages - (uuid, session_id, parent_uuid, type, role, content, model, input_tokens, output_tokens, timestamp, cwd, git_branch, version) - VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, + (uuid, session_id, parent_uuid, type, role, content, model, input_tokens, output_tokens, cache_read_input_tokens, cache_creation_input_tokens, timestamp, cwd, git_branch, version) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, ) .run( m.uuid, @@ -239,6 +257,8 @@ export function insertMessage(db: DatabaseSync, m: MessageInput): boolean { m.model ?? null, m.inputTokens ?? null, m.outputTokens ?? null, + m.cacheReadTokens ?? null, + m.cacheCreationTokens ?? null, m.timestamp ?? null, m.cwd ?? null, m.gitBranch ?? null, @@ -319,6 +339,25 @@ export function searchMessages( .all(...params) as unknown as SearchHit[]; } +export interface QueryLogInput { + query: string; + hitCount: number; + projectPath?: string; + harness?: string; +} + +/** + * Record one recall (a `kit memory search`) into query_log — the basis for the + * "how often is the store actually used" stat. Append-only, best-effort: a + * logging failure must never break the search itself (callers wrap in try/catch). + */ +export function recordQuery(db: DatabaseSync, q: QueryLogInput): void { + db.prepare( + `INSERT INTO query_log (query, hit_count, project_path, harness, executed_at) + VALUES (?, ?, ?, ?, datetime('now'))`, + ).run(q.query, q.hitCount, q.projectPath ?? null, q.harness ?? null); +} + /** * Most-recent messages by wall-clock time (newest first) — the basis for session * recovery (re-injecting "where you left off" after a compaction/resume). Unlike @@ -367,13 +406,92 @@ export function getStats(db: DatabaseSync): MemoryStats { .all() as { harness: string; n: number }[] ).map((r) => ({ harness: r.harness, sessions: Number(r.n) })); + const sessions = count("SELECT COUNT(*) AS n FROM sessions"); + const messages = count("SELECT COUNT(*) AS n FROM messages"); + + // Token economy — SUM the raw columns, then derive ratios via the pure helper. + const t = db + .prepare( + `SELECT COALESCE(SUM(input_tokens), 0) AS i, + COALESCE(SUM(output_tokens), 0) AS o, + COALESCE(SUM(cache_read_input_tokens), 0) AS cr, + COALESCE(SUM(cache_creation_input_tokens), 0) AS cc + FROM messages`, + ) + .get() as { i: number; o: number; cr: number; cc: number }; + const summary = summarizeTokens({ + inputTokens: Number(t.i), + outputTokens: Number(t.o), + cacheReadTokens: Number(t.cr), + cacheCreationTokens: Number(t.cc), + }); + const byModel = ( + db + .prepare( + `SELECT COALESCE(model, '(unknown)') AS model, COUNT(*) AS n, + COALESCE(SUM(input_tokens), 0) AS i, COALESCE(SUM(output_tokens), 0) AS o + FROM messages WHERE input_tokens IS NOT NULL OR output_tokens IS NOT NULL + GROUP BY model ORDER BY (i + o) DESC LIMIT 5`, + ) + .all() as { model: string; n: number; i: number; o: number }[] + ).map((r) => ({ + model: r.model, + messages: Number(r.n), + inputTokens: Number(r.i), + outputTokens: Number(r.o), + })); + + // Recall usage from query_log. + const recallTotal = count("SELECT COUNT(*) AS n FROM query_log"); + const recall7d = count( + "SELECT COUNT(*) AS n FROM query_log WHERE executed_at >= datetime('now', '-7 days')", + ); + const distinctQueries = count("SELECT COUNT(DISTINCT query) AS n FROM query_log"); + const topTerms = ( + db + .prepare( + `SELECT query, COUNT(*) AS n FROM query_log + GROUP BY query ORDER BY n DESC, query ASC LIMIT 5`, + ) + .all() as { query: string; n: number }[] + ).map((r) => ({ query: r.query, count: Number(r.n) })); + return { - sessions: count("SELECT COUNT(*) AS n FROM sessions"), - messages: count("SELECT COUNT(*) AS n FROM messages"), + sessions, + messages, toolUses: count("SELECT COUNT(*) AS n FROM tool_uses"), pendingOpen: count("SELECT COUNT(*) AS n FROM pending_actions WHERE status = 'open'"), dbPath, sizeBytes, byHarness, + tokens: { + ...summary, + perSession: sessions > 0 ? Math.round(summary.totalTokens / sessions) : 0, + perMessage: messages > 0 ? Math.round(summary.totalTokens / messages) : 0, + byModel, + }, + recalls: { + total: recallTotal, + last7d: recall7d, + distinctQueries, + topTerms, + }, + sessionsBreakdown: { + logical: count("SELECT COUNT(*) AS n FROM sessions WHERE is_agent_sidechain = 0"), + sidechain: count("SELECT COUNT(*) AS n FROM sessions WHERE is_agent_sidechain = 1"), + filesIndexed: count("SELECT COUNT(*) AS n FROM file_index"), + }, }; } + +/** Per-day message counts (oldest→newest) over the last `days` days — sparkline feed. */ +export function dailyActivity(db: DatabaseSync, days = 90): { day: string; count: number }[] { + return db + .prepare( + `SELECT DATE(timestamp) AS day, COUNT(*) AS count + FROM messages + WHERE timestamp IS NOT NULL AND DATE(timestamp) >= DATE('now', ?) + GROUP BY day ORDER BY day ASC`, + ) + .all(`-${days} days`) as { day: string; count: number }[]; +} diff --git a/src/memory/parser.ts b/src/memory/parser.ts index 9919a939..7f2571d3 100644 --- a/src/memory/parser.ts +++ b/src/memory/parser.ts @@ -94,7 +94,12 @@ interface TranscriptRecord { role?: string; content?: Content; model?: string; - usage?: { input_tokens?: number; output_tokens?: number }; + usage?: { + input_tokens?: number; + output_tokens?: number; + cache_read_input_tokens?: number; + cache_creation_input_tokens?: number; + }; }; } @@ -151,6 +156,8 @@ function indexFile( model: msg?.model, inputTokens: msg?.usage?.input_tokens, outputTokens: msg?.usage?.output_tokens, + cacheReadTokens: msg?.usage?.cache_read_input_tokens, + cacheCreationTokens: msg?.usage?.cache_creation_input_tokens, timestamp: ts, cwd: rec.cwd, gitBranch: rec.gitBranch, diff --git a/src/memory/stats.test.ts b/src/memory/stats.test.ts new file mode 100644 index 00000000..67202706 --- /dev/null +++ b/src/memory/stats.test.ts @@ -0,0 +1,77 @@ +import { describe, it } from "node:test"; +import assert from "node:assert/strict"; +import { summarizeTokens, sparkline, fmtTokens } from "./stats.js"; + +describe("summarizeTokens", () => { + it("sums totalTokens (input+output) and computes cache-hit ratio", () => { + const s = summarizeTokens({ + inputTokens: 100, + outputTokens: 50, + cacheReadTokens: 300, + cacheCreationTokens: 100, + }); + assert.equal(s.totalTokens, 150); + // cacheRead / (input + cacheRead + cacheCreation) = 300 / 500 = 0.6 + assert.equal(s.cacheHitRatio, 0.6); + }); + + it("returns null cache-hit ratio when there is no token data (avoids misleading 0%)", () => { + const s = summarizeTokens({ + inputTokens: 0, + outputTokens: 0, + cacheReadTokens: 0, + cacheCreationTokens: 0, + }); + assert.equal(s.cacheHitRatio, null); + assert.equal(s.totalTokens, 0); + }); + + it("ratio is null when input exists but NO cache tokens were recorded (forward-only history)", () => { + // Historical rows have input_tokens but NULL cache cols → don't report a + // misleading 0%; n/a until cache data accumulates. + const s = summarizeTokens({ + inputTokens: 200, + outputTokens: 80, + cacheReadTokens: 0, + cacheCreationTokens: 0, + }); + assert.equal(s.cacheHitRatio, null); + }); + + it("ratio reflects a true 0% only once some cache activity is present", () => { + // cache_creation happened (cache was written) but nothing was read back. + const s = summarizeTokens({ + inputTokens: 100, + outputTokens: 0, + cacheReadTokens: 0, + cacheCreationTokens: 100, + }); + assert.equal(s.cacheHitRatio, 0); // 0 / (100+0+100) + }); +}); + +describe("sparkline", () => { + it("returns empty for no data", () => { + assert.equal(sparkline([]), ""); + }); + + it("maps the busiest day to the densest glyph and zero-days to blanks", () => { + const out = sparkline([0, 1, 10]); + assert.equal(out.length, 3); + assert.equal(out[0], " "); // zero day → blank + assert.equal(out[2], "█"); // max day → densest + assert.notEqual(out[1], " "); // a non-zero day is never blank + }); + + it("all-zero input renders all blanks (no divide-by-zero)", () => { + assert.equal(sparkline([0, 0, 0]), " "); + }); +}); + +describe("fmtTokens", () => { + it("formats millions, thousands, and raw", () => { + assert.equal(fmtTokens(87_600_000), "87.6m"); + assert.equal(fmtTokens(12_345), "12.3k"); + assert.equal(fmtTokens(629), "629"); + }); +}); diff --git a/src/memory/stats.ts b/src/memory/stats.ts new file mode 100644 index 00000000..c3ce283b --- /dev/null +++ b/src/memory/stats.ts @@ -0,0 +1,59 @@ +/** + * kit memory — pure stat derivations (token economy + activity sparkline). + * + * These are split out from db.ts so they're fixture-testable without a SQLite + * handle: db.ts SUMs the raw columns, these functions turn the sums into the + * ratios + glyphs the CLI prints. Zero I/O, zero deps. + */ +import type { TokenTotals, TokenSummary } from "./types.js"; + +/** + * Derive the token economy from summed totals. `totalTokens` is input+output + * (content generated/consumed); `cacheHitRatio` is the fraction of *input* that + * was served from the prompt cache. + * + * The ratio is null when NO cache tokens were recorded — even if input_tokens is + * non-zero. Cache columns are forward-only (older rows have NULL cache tokens), so + * a populated input + zero cache means "not captured", not a true 0% hit rate. + * Reporting n/a there avoids misrepresenting heavily-cached history as uncached. + */ +export function summarizeTokens(t: TokenTotals): TokenSummary { + const cacheData = t.cacheReadTokens + t.cacheCreationTokens; + const cacheBase = t.inputTokens + t.cacheReadTokens + t.cacheCreationTokens; + return { + inputTokens: t.inputTokens, + outputTokens: t.outputTokens, + cacheReadTokens: t.cacheReadTokens, + cacheCreationTokens: t.cacheCreationTokens, + totalTokens: t.inputTokens + t.outputTokens, + cacheHitRatio: cacheData > 0 ? t.cacheReadTokens / cacheBase : null, + }; +} + +const RAMP = " ░▒▓█"; + +/** + * One glyph per day (GitHub-contribution ramp), scaled to the busiest day. + * Empty input → "". A day with 0 activity is a space; the rest bucket linearly + * across ░▒▓█ relative to the max. Pure + deterministic. + */ +export function sparkline(counts: number[]): string { + if (counts.length === 0) return ""; + const max = Math.max(...counts); + if (max <= 0) return RAMP[0].repeat(counts.length); + return counts + .map((n) => { + if (n <= 0) return RAMP[0]; + // bucket 1..4 (skip the blank glyph for any non-zero day) + const idx = Math.min(RAMP.length - 1, Math.ceil((n / max) * (RAMP.length - 1))); + return RAMP[Math.max(1, idx)]; + }) + .join(""); +} + +/** Human-readable token count: 87_600_000 → "87.6m", 12_345 → "12.3k". */ +export function fmtTokens(n: number): string { + if (n >= 1_000_000) return `${(n / 1_000_000).toFixed(1)}m`; + if (n >= 1_000) return `${(n / 1_000).toFixed(1)}k`; + return String(n); +} diff --git a/src/memory/types.ts b/src/memory/types.ts index 34b64971..89357bdf 100644 --- a/src/memory/types.ts +++ b/src/memory/types.ts @@ -24,6 +24,10 @@ export interface MessageInput { model?: string; inputTokens?: number; outputTokens?: number; + /** Input tokens served from the prompt cache (cheap reads). */ + cacheReadTokens?: number; + /** Input tokens written to the prompt cache (one-time cost). */ + cacheCreationTokens?: number; timestamp?: string; cwd?: string; gitBranch?: string; @@ -58,4 +62,37 @@ export interface MemoryStats { * This is the portability proof: it shows the store spans agents, so the * externalized state is not locked to one tool. */ byHarness: { harness: string; sessions: number }[]; + /** Token economy distilled from the indexed transcripts (see summarizeTokens). */ + tokens: TokenSummary & { + perSession: number; + perMessage: number; + /** Top models by message volume, with their token totals. */ + byModel: { model: string; messages: number; inputTokens: number; outputTokens: number }[]; + }; + /** Recall usage — how often the store is actually searched (query_log). */ + recalls: { + total: number; + last7d: number; + distinctQueries: number; + topTerms: { query: string; count: number }[]; + }; + /** Logical vs sidechain session split + raw transcript files indexed. + * Exposes the "N files → M logical sessions" collapse. */ + sessionsBreakdown: { logical: number; sidechain: number; filesIndexed: number }; +} + +/** Token totals summed across messages — the raw inputs to summarizeTokens. */ +export interface TokenTotals { + inputTokens: number; + outputTokens: number; + cacheReadTokens: number; + cacheCreationTokens: number; +} + +/** Derived token economy: totals + ratios. cacheHitRatio is null when no cache data. */ +export interface TokenSummary extends TokenTotals { + /** input + output (the content tokens generated/consumed). */ + totalTokens: number; + /** cacheRead / (input + cacheRead + cacheCreation): fraction of input served from cache. */ + cacheHitRatio: number | null; }