From c8dffccc7ae3210a4fe9f854250b8a25b8d4b87b Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 19 Jul 2026 08:26:38 +0000 Subject: [PATCH] =?UTF-8?q?feat(memory):=20kit=20memory=20search=20--fresh?= =?UTF-8?q?=20=E2=80=94=20recency-aware=20RRF=20ranking=20(B5)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Borrows the Cerebras knowledge-base ranking insight, kept on-charter (deterministic, zero-LLM; kit has one lexical retriever + recency, no embeddings/reranker). - fuseByRrf(lists, keyOf, k=60): pure Reciprocal Rank Fusion — merges ranked lists by RANK, not score, so incommensurable signals combine without normalization. Deterministic tiebreak by key. Reusable primitive for future multi-signal fusion (e.g. provenance). - searchMessages gains opts.recencyBoost (default off → relevance-first order UNCHANGED). When on, it fetches a larger candidate pool and RRF-fuses bm25-relevance with recency, so a fresh still-relevant hit can outrank a marginally-more-relevant stale one; relevance still dominates. - kit memory search --fresh wires it; help/opencli contract updated. Tests: fuseByRrf (consensus > single #1, single-list identity, dedup, deterministic tiebreak); searchMessages --fresh promotes a fresh-but-weaker hit above a stale mid one while the strongest relevance match still leads. Full suite green (3013 pass / 0 fail). Co-Authored-By: Claude Opus 4.8 --- CHANGELOG.md | 9 ++++ contracts/kit.opencli.json | 2 +- src/cli.ts | 3 +- src/commands/memory.ts | 7 +++- src/memory/db.test.ts | 84 ++++++++++++++++++++++++++++++++++++++ src/memory/db.ts | 48 ++++++++++++++++++++-- 6 files changed, 145 insertions(+), 8 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 7fcd5574..69507e0f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,15 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/). ### Added +- **`kit memory search --fresh` — recency-aware recall (deterministic, zero-LLM).** By default + recall is bm25 relevance-first (unchanged). `--fresh` fetches a larger candidate pool and + **RRF-fuses** two incommensurable signals — bm25 relevance and recency — _by rank_ (no score + normalization), so a fresh, still-relevant hit can outrank a marginally-more-relevant stale + one ("when relevance is otherwise equal, the newer answer wins"). Relevance still dominates; + recency breaks the lower ranks. Exposes a reusable `fuseByRrf` primitive for future + multi-signal fusion. Borrowed from the Cerebras knowledge-base ranking stack, kept on-charter + (kit has one lexical retriever + recency; no embeddings, no reranker model). + - **`kit broker enforce-readiness` — graduate observe→enforce on evidence, not nerve.** The exec-broker runtime ladder is off → observe → enforce, but the human step between the last two had no evidence: an operator in observe (which watches but never denies) had no way to diff --git a/contracts/kit.opencli.json b/contracts/kit.opencli.json index 9fd01e7c..8d4ee10c 100644 --- a/contracts/kit.opencli.json +++ b/contracts/kit.opencli.json @@ -521,7 +521,7 @@ }, "search": { "kind": "command", - "summary": "Full-text search memory (current project; --global for all)", + "summary": "Full-text search memory (current project; --global for all; --fresh = recency-aware ranking)", "x-kit-args-modeled": false, "x-kit-mcp": false, "x-kit-stability": "stable" diff --git a/src/cli.ts b/src/cli.ts index e6c77762..2b5d06eb 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -779,7 +779,8 @@ const SUBCOMMAND_HELP: Record = { "broker enforce-readiness": "Read the recorded observe window (.kit-audit.jsonl) and report whether it's safe to flip exec-broker to enforce: ready | would-block (+ exactly what breaks) | untested (--gate fails CI on any not-ready verdict)", "memory index": "Index ~/.claude transcripts into the SQLite memory store", - "memory search": "Full-text search memory (current project; --global for all)", + "memory search": + "Full-text search memory (current project; --global for all; --fresh = recency-aware ranking)", "memory stats": "Show what the local memory store contains", "memory suggest": "Emit a BYO-LLM review prompt (recent activity + open items) — pipe to your own model", diff --git a/src/commands/memory.ts b/src/commands/memory.ts index 1c955833..288eadff 100644 --- a/src/commands/memory.ts +++ b/src/commands/memory.ts @@ -831,7 +831,7 @@ async function memSearch(): Promise { const query = terms.join(" ").trim(); if (!query) { console.error( - `${c.red}usage: kit memory search [--global] [--project=] [--limit=N]${c.reset}`, + `${c.red}usage: kit memory search [--global] [--project=] [--limit=N] [--fresh]${c.reset}`, ); return false; } @@ -843,8 +843,11 @@ async function memSearch(): Promise { // default so a poisoned line is never re-injected; --include-quarantined shows // them (for inspection) — still badged as flagged in the render below. const includeQuarantined = hasFlag(process.argv, "--include-quarantined"); + // --fresh: recency-aware ranking (RRF-fuse bm25 relevance + recency). Off by default so the + // relevance-first ordering is unchanged unless asked for. + const recencyBoost = hasFlag(process.argv, "--fresh"); const db = openMemoryDb(); - const hits = searchMessages(db, query, { limit, projectPath, includeQuarantined }); + const hits = searchMessages(db, query, { limit, projectPath, includeQuarantined, recencyBoost }); // Record the recall (query_log) — best-effort; never let logging break search. try { recordQuery(db, { query, hitCount: hits.length, projectPath }); diff --git a/src/memory/db.test.ts b/src/memory/db.test.ts index 60b1d54f..29bbfa6d 100644 --- a/src/memory/db.test.ts +++ b/src/memory/db.test.ts @@ -13,6 +13,7 @@ import { toFtsMatchQuery, quarantineInjectedMessages, countQuarantined, + fuseByRrf, } from "./db.js"; describe("memory db", () => { @@ -404,3 +405,86 @@ describe("memory quarantine (R3 — recall excludes injected rows)", () => { db.close(); }); }); + +describe("fuseByRrf", () => { + const key = (x: { id: string }) => x.id; + + it("rewards consensus across lists over a single #1", () => { + // b is #1 in list A but absent from B; a is #2 in both. Consensus (a) should win. + const A = [{ id: "b" }, { id: "a" }, { id: "c" }]; + const B = [{ id: "d" }, { id: "a" }, { id: "c" }]; + const fused = fuseByRrf([A, B], key).map((x) => x.id); + assert.equal(fused[0], "a"); // appears high in BOTH lists → beats b (#1 in one only) + }); + + it("is a stable identity for a single list (order preserved)", () => { + const A = [{ id: "x" }, { id: "y" }, { id: "z" }]; + assert.deepEqual( + fuseByRrf([A], key).map((x) => x.id), + ["x", "y", "z"], + ); + }); + + it("dedups items appearing in multiple lists", () => { + const A = [{ id: "a" }, { id: "b" }]; + const B = [{ id: "b" }, { id: "a" }]; + assert.equal(fuseByRrf([A, B], key).length, 2); + }); + + it("breaks ties deterministically by key", () => { + // a and b are perfectly symmetric across the two lists → tie → key-ascending. + const A = [{ id: "a" }, { id: "b" }]; + const B = [{ id: "b" }, { id: "a" }]; + assert.deepEqual( + fuseByRrf([A, B], key).map((x) => x.id), + ["a", "b"], + ); + }); +}); + +describe("searchMessages --fresh (recency-aware ranking)", () => { + const fresh = () => openMemoryDb(":memory:"); + + it("default is relevance-only; --fresh lifts a fresh but less-relevant hit above a stale mid one", () => { + const db = fresh(); + upsertSession(db, { sessionId: "s1", harness: "claude-code", project: "/repo" }); + // All match "deploy"; bm25 length-normalization ranks the shortest match highest, so relevance + // order is strong > mid > weak. `weak` is the FRESHEST (and least relevant). + insertMessage(db, { + uuid: "strong", + sessionId: "s1", + type: "user", + content: "deploy", + timestamp: "2022-01-01T00:00:00.000Z", + }); + insertMessage(db, { + uuid: "mid", + sessionId: "s1", + type: "user", + content: "deploy alpha beta", + timestamp: "2021-01-01T00:00:00.000Z", + }); + insertMessage(db, { + uuid: "weak", + sessionId: "s1", + type: "user", + content: "deploy alpha beta gamma delta epsilon", + timestamp: "2026-01-01T00:00:00.000Z", + }); + + // Default: pure relevance — freshest-but-weakest ("weak") sits last. + const plain = searchMessages(db, "deploy").map((h) => h.uuid); + assert.equal(plain[0], "strong"); + assert.ok(plain.indexOf("mid") < plain.indexOf("weak"), `relevance order: ${plain}`); + + // --fresh: RRF fuses recency, promoting the fresh "weak" above the stale "mid"; the strongest + // relevance match still leads (relevance dominates, recency breaks the lower ranks). + const boosted = searchMessages(db, "deploy", { recencyBoost: true }).map((h) => h.uuid); + assert.equal(boosted[0], "strong"); + assert.ok( + boosted.indexOf("weak") < boosted.indexOf("mid"), + `recency-boosted order: ${boosted}`, + ); + db.close(); + }); +}); diff --git a/src/memory/db.ts b/src/memory/db.ts index 361d5b1f..ae90bcde 100644 --- a/src/memory/db.ts +++ b/src/memory/db.ts @@ -507,6 +507,35 @@ export interface SearchOptions { /** Include quarantined (high-confidence injection) rows. Default false: recall * excludes them so a poisoned line is never re-injected. Set for inspection. */ includeQuarantined?: boolean; + /** Opt-in recency-aware ranking (`kit memory search --fresh`): RRF-fuse bm25 relevance with + * recency so a fresh, still-relevant hit outranks a marginally-more-relevant stale one. Off by + * default — the relevance-first ordering is unchanged unless a caller asks for it. */ + recencyBoost?: boolean; +} + +/** + * Reciprocal Rank Fusion — merge several ranked lists of the SAME items into one, by RANK not by + * score. This lets incommensurable signals (e.g. bm25 relevance vs recency) combine WITHOUT any + * score normalization: each list contributes `1/(k + rank)` (rank 1-based) to an item's fused + * score, and `k` (default 60, the standard smoothing constant) makes agreement across lists count + * for more than a single list's #1. Deterministic — ties break by key ascending. Pure, zero-LLM. + */ +export function fuseByRrf(lists: T[][], keyOf: (x: T) => string | number, k = 60): T[] { + const score = new Map(); + const item = new Map(); + for (const list of lists) { + for (let i = 0; i < list.length; i++) { + const key = keyOf(list[i]); + score.set(key, (score.get(key) ?? 0) + 1 / (k + i + 1)); + if (!item.has(key)) item.set(key, list[i]); + } + } + return [...item.keys()] + .sort((a, b) => { + const d = (score.get(b) ?? 0) - (score.get(a) ?? 0); + return d !== 0 ? d : a < b ? -1 : a > b ? 1 : 0; // deterministic tiebreak by key + }) + .map((key) => item.get(key) as T); } /** @@ -539,6 +568,9 @@ export function searchMessages( const terms = query.trim().split(/\s+/).filter(Boolean); if (terms.length === 0) return []; const limit = opts.limit ?? 20; + // Recency-boost needs a candidate POOL larger than `limit` to re-rank; the default path fetches + // exactly `limit` (behavior unchanged). + const poolLimit = opts.recencyBoost ? Math.max(limit * 4, 40) : limit; const run = (match: string): SearchHit[] => { const params: (string | number)[] = [match]; @@ -548,7 +580,7 @@ export function searchMessages( where += " AND (m.cwd = ? OR m.cwd LIKE ?)"; params.push(opts.projectPath, `${opts.projectPath}/%`); } - params.push(limit); + params.push(poolLimit); return db .prepare( `SELECT m.id AS id, m.uuid AS uuid, m.session_id AS sessionId, m.role AS role, @@ -565,13 +597,21 @@ export function searchMessages( // Precision first: an all-terms (implicit-AND) match. FTS5's `rank` is bm25, // so results already come back relevance-ordered. const strict = run(toFtsMatchQuery(query, "AND")); - if (strict.length > 0 || terms.length < 2) return strict; - // Graceful recall: a strict AND over a multi-term query returned nothing (no // single message holds every term). Fall back to OR so partial matches still // surface, bm25-ranked — the message covering the most terms ranks first. // This is the "rank by relevance, not all-or-nothing" behavior (#164). - return run(toFtsMatchQuery(query, "OR")); + const pool = strict.length > 0 || terms.length < 2 ? strict : run(toFtsMatchQuery(query, "OR")); + + if (!opts.recencyBoost) return pool.slice(0, limit); + + // Recency-aware: RRF-fuse the bm25-relevance order with a recency order (two incommensurable + // signals blended by RANK — no score normalization), so a fresh, still-relevant hit can + // outrank a marginally-more-relevant stale one. Relevance still dominates; recency breaks + // near-ties (the "when relevance is otherwise equal, newer wins" rule). Then take top `limit`. + const recencyOf = (h: SearchHit): number => (h.timestamp ? Date.parse(h.timestamp) || 0 : 0); + const byRecency = [...pool].sort((a, b) => recencyOf(b) - recencyOf(a)); + return fuseByRrf([pool, byRecency], (h) => h.id).slice(0, limit); } export interface QueryLogInput {