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
9 changes: 9 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion contracts/kit.opencli.json
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down
3 changes: 2 additions & 1 deletion src/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -779,7 +779,8 @@ const SUBCOMMAND_HELP: Record<string, string> = {
"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",
Expand Down
7 changes: 5 additions & 2 deletions src/commands/memory.ts
Original file line number Diff line number Diff line change
Expand Up @@ -831,7 +831,7 @@ async function memSearch(): Promise<boolean> {
const query = terms.join(" ").trim();
if (!query) {
console.error(
`${c.red}usage: kit memory search <query> [--global] [--project=<path>] [--limit=N]${c.reset}`,
`${c.red}usage: kit memory search <query> [--global] [--project=<path>] [--limit=N] [--fresh]${c.reset}`,
);
return false;
}
Expand All @@ -843,8 +843,11 @@ async function memSearch(): Promise<boolean> {
// 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 });
Expand Down
84 changes: 84 additions & 0 deletions src/memory/db.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import {
toFtsMatchQuery,
quarantineInjectedMessages,
countQuarantined,
fuseByRrf,
} from "./db.js";

describe("memory db", () => {
Expand Down Expand Up @@ -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();
});
});
48 changes: 44 additions & 4 deletions src/memory/db.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<T>(lists: T[][], keyOf: (x: T) => string | number, k = 60): T[] {
const score = new Map<string | number, number>();
const item = new Map<string | number, T>();
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);
}

/**
Expand Down Expand Up @@ -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];
Expand All @@ -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,
Expand All @@ -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<SearchHit>([pool, byRecency], (h) => h.id).slice(0, limit);
}

export interface QueryLogInput {
Expand Down
Loading