Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
4 changes: 2 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -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",
Expand Down
82 changes: 79 additions & 3 deletions src/commands/memory.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -274,23 +282,73 @@ async function memMerge(): Promise<boolean> {

async function memStats(): Promise<boolean> {
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;
}

Expand All @@ -313,7 +371,19 @@ async function memSuggest(): Promise<boolean> {

async function memSearch(): Promise<boolean> {
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(
Expand All @@ -327,6 +397,12 @@ async function memSearch(): Promise<boolean> {
: (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));
Expand Down
81 changes: 81 additions & 0 deletions src/memory/db.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@ import {
insertMessage,
searchMessages,
getStats,
recordQuery,
dailyActivity,
toFtsMatchQuery,
} from "./db.js";

Expand Down Expand Up @@ -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();
});
});
Loading
Loading