Skip to content

Persistent Context Across Sessions for Every Agent – Captures everything your agent does during sessions, compresses it with AI, and injects relevant context back into future sessions. Works with Claude Code, OpenClaw, Codex, Gemini, Hermes, Copilot, OpenCode + More

fix(search): drop the recency window from the Chroma leg of a typed search (#6759)

Junying Shao5f7c82586a37
diff --git a/docs/public/configuration.mdx b/docs/public/configuration.mdx
index 7e5283f40..131adc105 100644
--- a/docs/public/configuration.mdx
+++ b/docs/public/configuration.mdx
@@ -96,7 +96,7 @@ lock directory, and restart to finish applying the saved selection.
| `CLAUDE_MEM_SEMANTIC_INJECT_OBSERVATION_TYPES` | _(empty)_ | Comma-separated active-mode observation type IDs to include in per-prompt semantic context. Empty keeps the current unfiltered selection. Filtering happens before the result limit, for both `index` and `narrative` output. |
| `CLAUDE_MEM_SEMANTIC_INJECT_OBSERVATION_CONCEPTS` | _(empty)_ | Comma-separated active-mode concept IDs to include in per-prompt semantic context. Empty keeps the current unfiltered selection. Unknown type/concept IDs are ignored; if a configured list contains no valid IDs, it falls back to the active mode's complete list. |
| `CLAUDE_MEM_SEMANTIC_INJECT_FORMAT` | `narrative` | `narrative` adds each match's title and full narrative. `index` adds one line per match with its id, title and subtitle and points Claude to `get_observations` for the details. `narrative` is the default because it works without Claude making a tool call: in `index` mode a match it does not expand only contributes its title and subtitle. An `index` line costs a fraction of a narrative, so `index` can carry more matches for the same tokens; pair it with a higher limit. |
-| `CLAUDE_MEM_SEARCH_RECENCY_DAYS` | `90` | Date-less semantic search (`search`, `search_observations`, the timeline) only ranks semantic (Chroma) matches created in the last N days; older semantic matches are left out of the answer. In relevance order, `search` and `search_observations` also rank exact keyword (FTS5) matches of any age; per-prompt injection (`CLAUDE_MEM_SEMANTIC_INJECT`) applies the window to keyword matches too. `0` turns the window off so every indexed match stays eligible; a larger N widens it. A request that passes `dateStart`/`dateEnd` always uses that range instead of the window. Restart the worker after changing it. |
+| `CLAUDE_MEM_SEARCH_RECENCY_DAYS` | `90` | Per-prompt injection (`CLAUDE_MEM_SEMANTIC_INJECT`) only ranks semantic (Chroma) and keyword (FTS5) matches created in the last N days; older matches stay out of the prompt. Date-ordered `search` and `search_observations`, and the timeline, apply the window to semantic matches. In relevance order, the default, `search` and `search_observations` rank semantic and keyword matches of any age, as the server's hybrid search does. `0` turns the window off so every indexed match stays eligible; a larger N widens it. A request that passes `dateStart`/`dateEnd` always uses that range instead of the window. Restart the worker after changing it. |
| `CLAUDE_MEM_SEARCH_MAX_DISTANCE` | _(empty)_ | Optional maximum Chroma distance for semantic search results. Rows farther away are removed before keyword/semantic rank fusion and per-prompt injection. Exact keyword (FTS5) matches remain eligible. Empty disables the cutoff; `0` is a valid cutoff. Choose a non-negative finite value using known matching and unrelated queries from your own collection: distances depend on its embedding model and distance metric, so a value from another collection may not transfer. Applies to worker search, `search_observations`, and query-based timeline anchors. Restart the worker after changing it. |
| `CLAUDE_MEM_FILE_READ_GATE_ENABLED` | `true` | Block whole-file Reads of code files of 32 KB and up that have observation history and send Claude to `smart_outline` / `smart_unfold` / `get_observations` instead (Claude Code only). Targeted Reads with `offset`/`limit` still work. `false` lets every Read through and still adds the file's timeline as context. See [File Read Gate](/file-read-gate). |
| `CLAUDE_MEM_LINE_ANCHORS_ENABLED` | `false` | Opt-in; only `true` turns it on. When the worker stores an observation, it then records in the observation's metadata the path, line number and exact text of up to 3 distinctive lines in the files that observation names, taken from the batch's Claude Code tool calls and never from model output: a line inside the text an `Edit` or `MultiEdit` edit wrote, or a line of a `Read` with an `offset` above 1 that its stored tool response holds. A file's timeline before a Read then ends each such row with where that code is now (`@L212`), found again by its text (exact, then ignoring whitespace), or `(code changed since)` when it is gone or now in more than one place: a line number is never guessed. Off, nothing is recorded or read and the timeline is unchanged. The recorded lines are source text and go wherever the observation goes, Cloud Sync included; secrets in them are left out only when [auto-redaction](/usage/auto-redaction) (`CLAUDE_MEM_REDACT_ENABLED`) is on. Set in `settings.json`, it applies from the next Read and the next stored observation; an environment variable of the same name overrides `settings.json`, and the worker reads its environment only when it starts. See [Line Anchors](/file-read-gate#line-anchors). |
diff --git a/scripts/eval/README.md b/scripts/eval/README.md
index f51854daf..c1e7931f7 100644
--- a/scripts/eval/README.md
+++ b/scripts/eval/README.md
@@ -4,12 +4,15 @@
## What it compares
-- **Keyword leg:** the real `SessionSearch.searchObservations` over FTS5, read to `KEYWORD_LEG_CANDIDATES` rows.
-- **Vector leg:** `LocalEmbedder` with all-MiniLM-L6-v2. Its vectors match Chroma's default embedding. The leg reads `CHROMA_BATCH_SIZE` rows, the rows of Chroma's first candidate window. Each observation is embedded the way `ChromaSync` indexes it, and ranks by its nearest document.
-- **before:** Chroma's order, with keyword rows only when the vector leg is empty. This is the worker before #6539.
+- **Keyword leg:** the real `SessionSearch.searchObservations` over FTS5, read to `KEYWORD_LEG_CANDIDATES` rows, with no date window.
+- **Vector leg:** `LocalEmbedder` with all-MiniLM-L6-v2. Its vectors match Chroma's default embedding. Each observation is embedded the way `ChromaSync` indexes it, and ranks by its nearest document.
+- **Dates:** each observation keeps its real date: the LOCOMO session date, or the merge date of the pull request. "Now" is the newest observation of the query's project. Results are also grouped by the age of a question's evidence.
- **keyword:** the keyword leg alone.
-- **after:** `fuseByReciprocalRank` with `RRF_K`. This is the worker after #6539, and the server's hybrid search.
-- **rrf k=5:** the same fusion with a smaller k, for comparison.
+- **vector 90d:** `fuseByReciprocalRank` with `RRF_K`. The vector leg drops rows older than the default 90-day window the way `ChromaSearchStrategy` does: it widens 100..1600 candidates until a page of 20 rows survives. This is a typed search after #6539.
+- **no window:** the same fusion, with the vector leg's first `CHROMA_BATCH_SIZE` rows of any age. This is the server's hybrid search.
+- **decay:** "no window", with each fused score multiplied by age^-0.5 in days, the ACT-R decay of `src/services/reinforcement/rank.ts`.
+- **recency list:** "no window", plus a third ranked list: the fused rows, newest first.
+- **rrf k=5:** "no window" with a smaller k, for comparison.
## Data
@@ -33,7 +36,26 @@ CLAUDE_MEM_DATA_DIR=$(mktemp -d) bun scripts/eval/search-fusion-eval.ts locomo <
The first run downloads the model and embeds every document, which takes a few minutes. It caches the vectors in `<folder>/*.f32`.
-## Results (2026-11-30)
+## Results (2026-12-04): recency window on the vector leg
+
+R@10 / nDCG@10, real dates:
+
+| Ranking | LOCOMO, all (1,535) | LOCOMO, evidence older than 90 days (674) | LOCOMO, evidence within 90 days (667) | LOCOMO, mixed (194) | Identifiers, all (600) | Identifiers, evidence older than 90 days (66) |
+| --- | --- | --- | --- | --- | --- | --- |
+| keyword | 0.569 / 0.444 | 0.583 / 0.432 | 0.654 / 0.530 | 0.230 / 0.191 | 0.987 / 0.971 | 1.000 / 0.971 |
+| vector 90d | 0.326 / 0.246 | 0.024 / 0.008 | 0.678 / 0.514 | 0.170 / 0.151 | 0.986 / 0.873 | 0.985 / 0.608 |
+| no window | 0.557 / 0.399 | 0.557 / 0.393 | 0.635 / 0.455 | 0.287 / 0.226 | 0.985 / 0.912 | 0.992 / 0.823 |
+| decay | 0.143 / 0.074 | 0.001 / 0.000 | 0.304 / 0.156 | 0.079 / 0.049 | 0.596 / 0.342 | 0.023 / 0.008 |
+| recency list | 0.518 / 0.318 | 0.464 / 0.233 | 0.650 / 0.445 | 0.254 / 0.177 | 0.818 / 0.732 | 0.485 / 0.468 |
+| rrf k=5 | 0.615 / 0.441 | 0.623 / 0.436 | 0.701 / 0.510 | 0.289 / 0.222 | 0.985 / 0.906 | 0.992 / 0.819 |
+
+- The window on the vector leg also hides old keyword matches. A recent row that both legs rank scores twice, so such rows fill the page. For the 674 LOCOMO questions with only old evidence, the keyword leg's top 10 held evidence for 422 of them. The "vector 90d" top 10 held it for 17.
+- Questions whose evidence is all recent lose a little without the window (LOCOMO R@10 0.678 to 0.635), because old rows compete for the page.
+- Both decay rankings are worse than "no window" in every group.
+
+## Results (2026-11-30): fusion (#6539)
+
+These numbers came from fake dates (every observation one second apart) and no window. Commit 72637708 reproduces them.
R@10 / nDCG@10:
diff --git a/scripts/eval/search-fusion-eval.ts b/scripts/eval/search-fusion-eval.ts
index 375c49958..7f0705174 100644
--- a/scripts/eval/search-fusion-eval.ts
+++ b/scripts/eval/search-fusion-eval.ts
@@ -2,19 +2,27 @@
* Offline retrieval eval for the worker's relevance search (#6539). See
* scripts/eval/README.md for the data, the commands and the last results.
*
- * Keyword leg: the real SessionSearch over FTS5, read to KEYWORD_LEG_CANDIDATES.
+ * Keyword leg: the real SessionSearch over FTS5, read to KEYWORD_LEG_CANDIDATES,
+ * with no date window, as a typed search reads it.
* Vector leg: LocalEmbedder with all-MiniLM-L6-v2, whose vectors match Chroma's
- * default embedding, read to CHROMA_BATCH_SIZE, the rows of Chroma's first
- * candidate window. Documents are embedded the way ChromaSync indexes an
+ * default embedding. Documents are embedded the way ChromaSync indexes an
* observation: one document per narrative, the title only without one; an
* observation ranks by its nearest document.
*
+ * Every observation keeps its real date (the LOCOMO session date, the PR merge
+ * date). "Now" is the newest observation of the query's project.
+ *
* Rankings compared:
- * - "before": Chroma's order, keyword rows only when the vector leg is empty
- * (supplementEmptyCategories before #6539);
* - "keyword": the keyword leg alone;
- * - "after": fuseByReciprocalRank with RRF_K, as the worker now ranks;
- * - "rrf k=5": the same fusion with a smaller k, for a later change.
+ * - "vector 90d": fuseByReciprocalRank with RRF_K, the vector leg limited to
+ * the default 90-day window the way ChromaSearchStrategy applies it: widen
+ * 100..1600 candidates until a page of PAGE rows survives the window;
+ * - "no window": the same fusion, the vector leg's first 100 rows of any age;
+ * - "decay": "no window" with each fused score times age^-0.5, the ACT-R decay
+ * of src/services/reinforcement/rank.ts;
+ * - "recency list": "no window" plus a third ranked list, the fused rows
+ * newest first;
+ * - "rrf k=5": "no window" with a smaller k, for a later change.
*/
import { existsSync, readFileSync, writeFileSync } from 'fs';
import { join } from 'path';
@@ -27,6 +35,18 @@ import { RRF_K, fuseByReciprocalRank } from '../../src/shared/reciprocal-rank-fu
interface Doc { key: string; project: string; title: string; narrative: string | null; createdAt: number }
interface Query { project: string; text: string; relevant: string[]; group: string }
+const DAY_MS = 24 * 60 * 60 * 1000;
+const PAGE = SEARCH_CONSTANTS.DEFAULT_LIMIT;
+const MONTHS = ['jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep', 'oct', 'nov', 'dec'];
+
+// LOCOMO session dates read like "1:56 pm on 8 May, 2023".
+function parseLocomoDate(text: string): number {
+ const m = /^(\d{1,2}):(\d{2})\s*(am|pm) on (\d{1,2}) (\w+),? (\d{4})$/i.exec(text.trim());
+ if (!m) throw new Error(`unparsed LOCOMO date: ${text}`);
+ const month = MONTHS.indexOf(m[5].slice(0, 3).toLowerCase());
+ const hour = (Number(m[1]) % 12) + (m[3].toLowerCase() === 'pm' ? 12 : 0);
+ return Date.UTC(Number(m[6]), month, Number(m[4]), hour, Number(m[2]));
+}
function loadLocomo(dir: string): { docs: Doc[]; queries: Query[] } {
const samples = JSON.parse(readFileSync(join(dir, 'locomo10.json'), 'utf8'));
@@ -37,14 +57,15 @@ function loadLocomo(dir: string): { docs: Doc[]; queries: Query[] } {
const conv = sample.conversation;
for (let s = 1; conv[`session_${s}`]; s++) {
const date = conv[`session_${s}_date_time`] ?? '';
- for (const turn of conv[`session_${s}`]) {
+ const start = parseLocomoDate(date);
+ conv[`session_${s}`].forEach((turn: any, t: number) => {
const text = turn.blip_caption ? `${turn.text} [shares ${turn.blip_caption}]` : turn.text;
docs.push({
key: `${project}:${turn.dia_id}`, project,
title: `${turn.speaker} on ${date}`, narrative: `${turn.speaker}: ${text}`,
- createdAt: Date.parse('2026-11-01T00:00:00Z') + docs.length * 1000,
+ createdAt: start + t * 1000,
});
- }
+ });
}
for (const qa of sample.qa) {
if (![1, 2, 3, 4].includes(qa.category) || !qa.evidence?.length) continue;
@@ -156,7 +177,9 @@ async function main() {
const projectOf = new Map(docs.map(doc => [idByKey.get(doc.key)!, doc.project]));
const epochOf = new Map(docs.map(doc => [idByKey.get(doc.key)!, doc.createdAt]));
- const policies = ['before', 'keyword', 'after', 'rrf k=5'] as const;
+ const nowOf = new Map<string, number>();
+ for (const doc of docs) nowOf.set(doc.project, Math.max(nowOf.get(doc.project) ?? 0, doc.createdAt));
+ const policies = ['keyword', 'vector 90d', 'no window', 'decay', 'recency list', 'rrf k=5'] as const;
const totals = new Map<string, Map<string, { n: number; r5: number; r10: number; ndcg10: number; mrr10: number }>>();
const ftsMs: number[] = [];
let keywordEmpty = 0;
@@ -168,9 +191,19 @@ async function main() {
const sim = dot(vector, queryVectors[qi]);
if (sim > (best.get(owner) ?? -Infinity)) best.set(owner, sim);
});
- const vector = [...best.entries()].sort((a, b) => b[1] - a[1])
- .slice(0, SEARCH_CONSTANTS.CHROMA_BATCH_SIZE)
+ const now = nowOf.get(query.project)!;
+ const byRelevance = [...best.entries()].sort((a, b) => b[1] - a[1])
.map(([id]) => ({ id, created_at_epoch: epochOf.get(id)! }));
+ const vector = byRelevance.slice(0, SEARCH_CONSTANTS.CHROMA_BATCH_SIZE);
+ // ChromaSearchStrategy: drop rows older than the window, and widen the
+ // candidate window until a page survives, at most 1600 rows.
+ const windowStart = now - SEARCH_CONSTANTS.RECENCY_WINDOW_MS;
+ let candidates: number = SEARCH_CONSTANTS.CHROMA_BATCH_SIZE;
+ let windowed = byRelevance.slice(0, candidates).filter(row => row.created_at_epoch >= windowStart);
+ while (windowed.length < PAGE && candidates < byRelevance.length && candidates < 1600) {
+ candidates = Math.min(candidates * 2, 1600);
+ windowed = byRelevance.slice(0, candidates).filter(row => row.created_at_epoch >= windowStart);
+ }
const t0 = performance.now();
const keyword = search.searchObservations(query.text, {
project: query.project, limit: SEARCH_CONSTANTS.KEYWORD_LEG_CANDIDATES, orderBy: 'relevance',
@@ -178,15 +211,30 @@ async function main() {
ftsMs.push(performance.now() - t0);
if (keyword.length === 0) keywordEmpty++;
const ids = (rows: Array<{ id: number }>) => rows.map(row => row.id);
+ const fused = fuseByReciprocalRank([vector, keyword], RRF_K);
+ const rrfScore = (id: number, lists: Array<Array<{ id: number }>>) => lists.reduce((sum, list) => {
+ const rank = list.findIndex(row => row.id === id);
+ return rank < 0 ? sum : sum + 1 / (RRF_K + rank + 1);
+ }, 0);
+ const age = (id: number) => Math.max(1, Math.floor((now - epochOf.get(id)!) / DAY_MS));
+ const decayed = fused.map(row => ({ row, score: rrfScore(row.id, [vector, keyword]) * Math.pow(age(row.id), -0.5) }))
+ .sort((a, b) => b.score - a.score).map(entry => entry.row);
+ const newestFirst = [...fused].sort((a, b) => b.created_at_epoch - a.created_at_epoch || b.id - a.id);
const ranked: Record<(typeof policies)[number], number[]> = {
- before: ids(vector.length ? vector : keyword),
keyword: ids(keyword),
- after: ids(fuseByReciprocalRank([vector, keyword], RRF_K)),
+ 'vector 90d': ids(fuseByReciprocalRank([windowed, keyword], RRF_K)),
+ 'no window': ids(fused),
+ decay: ids(decayed),
+ 'recency list': ids(fuseByReciprocalRank([vector, keyword, newestFirst], RRF_K)),
'rrf k=5': ids(fuseByReciprocalRank([vector, keyword], 5)),
};
const relevant = new Set(query.relevant.filter(k => idByKey.has(k)));
if (relevant.size === 0) return;
- for (const group of [query.group, 'all']) {
+ const ages = [...relevant].map(k => now - epochOf.get(idByKey.get(k)!)!);
+ const ageGroup = ages.every(a => a > SEARCH_CONSTANTS.RECENCY_WINDOW_MS) ? 'evidence all older than 90 days'
+ : ages.every(a => a <= SEARCH_CONSTANTS.RECENCY_WINDOW_MS) ? 'evidence all within 90 days'
+ : 'evidence mixed';
+ for (const group of [query.group, ageGroup, 'all']) {
if (!totals.has(group)) totals.set(group, new Map());
for (const policy of policies) {
const m = metrics(ranked[policy].map(id => keyById.get(id)!), relevant);
diff --git a/src/services/worker/SearchManager.ts b/src/services/worker/SearchManager.ts
index 56cebf104..dc217426b 100644
--- a/src/services/worker/SearchManager.ts
+++ b/src/services/worker/SearchManager.ts
@@ -65,9 +65,10 @@ export class SearchManager {
private timelineService: TimelineService,
/**
* Implicit window, in milliseconds, that date-less semantic searches
- * apply (CLAUDE_MEM_SEARCH_RECENCY_DAYS). Defaults to the shipped 90
- * days; 0 disables the window so every semantic match stays eligible.
- * An explicit `dateRange` on a request always wins over it.
+ * apply (CLAUDE_MEM_SEARCH_RECENCY_DAYS), except a typed relevance
+ * search (see `search`). Defaults to the shipped 90 days; 0 disables the
+ * window so every semantic match stays eligible. An explicit `dateRange`
+ * on a request always wins over it.
*/
private searchRecencyWindowMs: number = SEARCH_CONSTANTS.RECENCY_WINDOW_MS,
private contextReader: ContextReadWorkerClient | null = null,
@@ -464,20 +465,21 @@ export class SearchManager {
}
/**
- * `keywordRecencyWindow`: per-prompt injection sets it so a relevance search's
- * keyword leg keeps the semantic recency window. A typed search leaves it off
- * and reads keyword matches of any age (#6539).
+ * `recencyWindow`: per-prompt injection sets it, so a relevance search keeps
+ * the default recency window (CLAUDE_MEM_SEARCH_RECENCY_DAYS) on both legs.
+ * A typed search leaves it off and ranks Chroma and keyword matches of any
+ * age, as the server's hybrid search does (#6539).
*/
async search(
args: any,
telemetryOut?: SearchTelemetryEnvelope,
- { keywordRecencyWindow = false }: { keywordRecencyWindow?: boolean } = {}
+ { recencyWindow = false }: { recencyWindow?: boolean } = {}
): Promise<any> {
if (args.deep !== undefined && ![true, false, 'true', 'false'].includes(args.deep)) {
throw new AppError('deep must be true or false', 400, 'INVALID_SEARCH_REQUEST');
}
const state: ObservationSearchState = { status: 'not_requested' };
- const result = await this.searchMemory(args, telemetryOut, state, keywordRecencyWindow);
+ const result = await this.searchMemory(args, telemetryOut, state, recencyWindow);
if (args.deep !== true && args.deep !== 'true') return result;
const normalized = this.normalizeParams(args);
const { query, type, obs_type, concepts, files, format, ...options } = normalized;
@@ -514,7 +516,7 @@ export class SearchManager {
args: any,
telemetryOut: SearchTelemetryEnvelope | undefined,
state: ObservationSearchState,
- keywordRecencyWindow: boolean
+ recencyWindow: boolean
): Promise<any> {
const normalized = this.normalizeParams(args);
const { query, type, obs_type, concepts, files, format, ...options } = normalized;
@@ -582,6 +584,9 @@ export class SearchManager {
const dateOrdered = options.orderBy === 'date_desc' || options.orderBy === 'date_asc';
const limit = options.limit ? Number(options.limit) : (dateOrdered ? SEARCH_CONSTANTS.DEFAULT_LIMIT : undefined);
const candidateOptions = { ...options, offset: 0, limit: limit === undefined ? undefined : offset + limit };
+ // A typed relevance search ranks Chroma's matches of any age, as its
+ // keyword leg does; injection keeps the window (`recencyWindow`).
+ const relevanceOrder = (options.orderBy ?? 'relevance') === 'relevance';
try {
chromaResult = await this.orchestrator.searchChroma({
@@ -597,7 +602,8 @@ export class SearchManager {
orderBy: options.orderBy ?? 'relevance',
// Omitted-limit JSON searches historically expose the ranked window.
limit: candidateOptions.limit ?? SEARCH_CONSTANTS.CHROMA_BATCH_SIZE,
- keepCandidateWindow: (options.orderBy ?? 'relevance') === 'relevance',
+ keepCandidateWindow: relevanceOrder,
+ ...(relevanceOrder && !recencyWindow && { ignoreDefaultRecencyWindow: true }),
});
} catch (chromaError) {
const errorObject = chromaError instanceof Error ? chromaError : new Error(String(chromaError));
@@ -616,7 +622,7 @@ export class SearchManager {
// Same policies as the orchestrator pipeline. Relevance order fuses Chroma's rows
// with the keyword rows, as the server's hybrid search does. Date order refills
// every requested category Chroma left empty, then unions keyword matches by date below.
- fusedWithKeywords = (options.orderBy ?? 'relevance') === 'relevance';
+ fusedWithKeywords = relevanceOrder;
const candidates = {
...candidateOptions,
limit: candidateOptions.limit ?? offset + SEARCH_CONSTANTS.DEFAULT_LIMIT,
@@ -629,7 +635,7 @@ export class SearchManager {
};
const supplemented = fusedWithKeywords
? await this.orchestrator.fuseWithKeywordMatches(candidates, chromaResult, {
- keywordRecencyWindow,
+ keywordRecencyWindow: recencyWindow,
// Omitted-limit JSON searches keep exposing Chroma's ranked window.
keepSemanticWindow: candidateOptions.limit === undefined,
})
diff --git a/src/services/worker/http/routes/SearchRoutes.ts b/src/services/worker/http/routes/SearchRoutes.ts
index b238822e8..8c942c680 100644
--- a/src/services/worker/http/routes/SearchRoutes.ts
+++ b/src/services/worker/http/routes/SearchRoutes.ts
@@ -701,8 +701,8 @@ export class SearchRoutes extends BaseRouteHandler {
let result: { observations?: ObservationSearchResult[] } | undefined;
try {
- // Nobody asked for these rows, so an old keyword match stays out of the
- // prompt: the keyword leg keeps the semantic recency window (#6539).
+ // Nobody asked for these rows, so an old match stays out of the prompt:
+ // both legs keep the recency window (#6539).
result = await this.searchManager.search({
query,
type: 'observations',
@@ -713,7 +713,7 @@ export class SearchRoutes extends BaseRouteHandler {
limit: String(searchLimit),
format: 'json',
...(platformSource ? { platformSource } : {}),
- }, undefined, { keywordRecencyWindow: true });
+ }, undefined, { recencyWindow: true });
} catch (error) {
const normalizedError = error instanceof Error ? error : new Error(String(error));
logger.error('HTTP', 'Semantic context query failed', { query, project, platformSource }, normalizedError);
diff --git a/src/shared/SettingsDefaultsManager.ts b/src/shared/SettingsDefaultsManager.ts
index 24a5aa2e8..f6f2a74f1 100644
--- a/src/shared/SettingsDefaultsManager.ts
+++ b/src/shared/SettingsDefaultsManager.ts
@@ -780,7 +780,7 @@ export class SettingsDefaultsManager {
// re-embedded until that finishes.
CLAUDE_MEM_EMBEDDING_MODEL: 'all-MiniLM-L6-v2',
CLAUDE_MEM_CHROMA_UVX_PATH: '', // Empty = search uv's install folders, then PATH (#4195)
- CLAUDE_MEM_SEARCH_RECENCY_DAYS: '90', // Date-less semantic search only ranks matches from the last N days (#4770). 0 = no window (every match eligible); an explicit dateStart/dateEnd always wins. Restart the worker after changing it
+ CLAUDE_MEM_SEARCH_RECENCY_DAYS: '90', // Per-prompt injection, date-ordered search and the timeline only rank matches from the last N days (#4770); relevance-ordered search reads any age. 0 = no window (every match eligible); an explicit dateStart/dateEnd always wins. Restart the worker after changing it
CLAUDE_MEM_SEARCH_MAX_DISTANCE: '', // Empty disables the semantic cutoff; keyword matches are unaffected. Restart after changing it.
// Worker-native cloud sync: credentials come from cmem.ai → Connect.
CLAUDE_MEM_CLOUD_SYNC_TOKEN: '',
diff --git a/tests/scripts/export-history-scope.test.ts b/tests/scripts/export-history-scope.test.ts
index 1d9de5924..0a3b6ca92 100644
--- a/tests/scripts/export-history-scope.test.ts
+++ b/tests/scripts/export-history-scope.test.ts
@@ -66,10 +66,16 @@ const fixture = String.raw`
JSON.stringify({ CLAUDE_MEM_WORKER_PORT: String(listener.address().port) }));
try {
let normalTitles;
+ let dateOrderedTitles;
const semantic = process.env.EXPORT_CASE === 'semantic';
if (semantic) {
+ // A typed relevance search has no recency window (#6758), so it already
+ // returns every row. A date-ordered search still applies the default
+ // window; the export below must return the complete history either way.
const response = await fetch(base + '/api/search?query=meaning&project=selected&format=json');
normalTitles = (await response.json()).observations.map(row => row.title).sort();
+ const dated = await fetch(base + '/api/search?query=meaning&project=selected&format=json&orderBy=date_desc');
+ dateOrderedTitles = (await dated.json()).observations.map(row => row.title).sort();
}
const output = join(process.env.CLAUDE_MEM_DATA_DIR, 'export.json');
if (cliProject) {
@@ -86,7 +92,7 @@ const fixture = String.raw`
console.log(JSON.stringify({
titles: data.observations.map(row => row.title).sort(),
parents: data.sessions.map(row => row.project).sort(),
- summaries: data.totalSummaries, prompts: data.totalPrompts, normalTitles,
+ summaries: data.totalSummaries, prompts: data.totalPrompts, normalTitles, dateOrderedTitles,
}));
} finally {
await new Promise(resolve => listener.close(resolve));
@@ -112,7 +118,10 @@ for (const scenario of ['all', 'project', 'semantic', 'cli-project']) {
expect(actual.parents).toEqual(scenario === 'all' ? ['other', 'selected'] : [scenario === 'cli-project' ? 'selected=project' : 'selected']);
expect(actual.summaries).toBe(scenario === 'all' ? 2 : scenario === 'semantic' ? 0 : 1);
expect(actual.prompts).toBe(scenario === 'all' ? 2 : scenario === 'semantic' ? 0 : 1);
- if (scenario === 'semantic') expect(actual.normalTitles).toEqual(['Current design']);
+ if (scenario === 'semantic') {
+ expect(actual.normalTitles).toEqual(['Archived architecture', 'Current design', 'Epoch boundary']);
+ expect(actual.dateOrderedTitles).toEqual(['Current design']);
+ }
} finally {
rmSync(dir, { recursive: true, force: true });
}
diff --git a/tests/worker/http/routes/hermes-cwd.test.ts b/tests/worker/http/routes/hermes-cwd.test.ts
index 5f604600e..3acd2c1b8 100644
--- a/tests/worker/http/routes/hermes-cwd.test.ts
+++ b/tests/worker/http/routes/hermes-cwd.test.ts
@@ -85,7 +85,7 @@ describe('Hermes checkout scoping', () => {
expect(search).toHaveBeenCalledWith(
expect.objectContaining({ project: context.primary, projects: context.allProjects }),
undefined,
- { keywordRecencyWindow: true },
+ { recencyWindow: true },
);
});
@@ -94,7 +94,7 @@ describe('Hermes checkout scoping', () => {
process.env.CLAUDE_MEM_EXCLUDED_PROJECTS = '';
const search = mock(async () => ({ observations: [] }));
await request(new SearchRoutes({ search } as any), '/api/context/semantic', { q: QUERY, cwd: checkout, ...explicit });
- expect(search).toHaveBeenCalledWith(expect.objectContaining(explicit), undefined, { keywordRecencyWindow: true });
+ expect(search).toHaveBeenCalledWith(expect.objectContaining(explicit), undefined, { recencyWindow: true });
});
}
diff --git a/tests/worker/http/routes/search-routes-semantic-platform.test.ts b/tests/worker/http/routes/search-routes-semantic-platform.test.ts
index 70cb4f76e..e74c324f9 100644
--- a/tests/worker/http/routes/search-routes-semantic-platform.test.ts
+++ b/tests/worker/http/routes/search-routes-semantic-platform.test.ts
@@ -129,7 +129,7 @@ describe('/api/context/semantic platform scoping', () => {
project: 'semantic-platform-project',
platformSource: 'cursor',
format: 'json',
- }), undefined, { keywordRecencyWindow: true });
+ }), undefined, { recencyWindow: true });
expect(response.json).toHaveBeenCalledWith(expect.objectContaining({ count: 1 }));
const body = (response.json as any).mock.calls[0][0] as { context: string };
expect(body.context).toContain('CURSOR_SCOPED_OBS');
diff --git a/tests/worker/observation-semantic-filters.test.ts b/tests/worker/observation-semantic-filters.test.ts
index 892b691ff..9bfba71dc 100644
--- a/tests/worker/observation-semantic-filters.test.ts
+++ b/tests/worker/observation-semantic-filters.test.ts
@@ -100,8 +100,10 @@ function expectFilteredResults(results: any[]) {
} else if (entry.filter.date_from) {
expect(entry.text).toContain('WANTED_ARCHIVE');
expect(entry.text).not.toContain('WANTED_CURRENT');
- } else if (entry.filter.type && !entry.semantic) {
- // Both bugfix rows have equal FTS rank. Either is valid at limit=1.
+ } else if (entry.filter.type) {
+ // Both bugfix rows qualify on both paths (typed search has no recency
+ // window, #6758) and tie (equal FTS rank / equal Chroma distance).
+ // Either is valid at limit=1.
expect(entry.text.match(/WANTED_(CURRENT|ARCHIVE)/g)).toHaveLength(1);
} else {
expect(entry.text).toContain('WANTED_CURRENT');
diff --git a/tests/worker/search-manager.test.ts b/tests/worker/search-manager.test.ts
index 3600eed98..3b58693f9 100644
--- a/tests/worker/search-manager.test.ts
+++ b/tests/worker/search-manager.test.ts
@@ -1026,21 +1026,31 @@ describe('SearchManager recency window wiring (#4770)', () => {
const keptIds = (rows: Array<{ id: number }>) => rows.map(row => row.id);
- it('keeps the shipped 90-day window when the constructor gets no window (unified search)', async () => {
+ // A typed relevance search ranks Chroma matches of any age (#6758); the
+ // window applies to the per-prompt injection search (`recencyWindow`).
+ it('keeps the shipped 90-day window when the constructor gets no window (injection search)', async () => {
const { manager } = makeManager();
- const results = await manager.search({ query: 'memory', type: 'observations', limit: 10, format: 'json' });
+ const results = await manager.search({ query: 'memory', type: 'observations', limit: 10, format: 'json' },
+ undefined, { recencyWindow: true });
expect(keptIds(results.observations)).toEqual([101]);
});
+ it('keeps every match for a typed relevance search (unified search)', async () => {
+ const { manager } = makeManager();
+ const results = await manager.search({ query: 'memory', type: 'observations', limit: 10, format: 'json' });
+ expect(keptIds(results.observations)).toEqual([101, 102]);
+ });
+
it('keeps every match when the window is disabled with 0 (unified search)', async () => {
const { manager } = makeManager(0);
const results = await manager.search({ query: 'memory', type: 'observations', limit: 10, format: 'json' });
expect(keptIds(results.observations)).toEqual([101, 102]);
});
- it('honors a custom window of 30 days (unified search)', async () => {
+ it('honors a custom window of 30 days (injection search)', async () => {
const { manager } = makeManager(30 * DAY_MS);
- const results = await manager.search({ query: 'memory', type: 'observations', limit: 10, format: 'json' });
+ const results = await manager.search({ query: 'memory', type: 'observations', limit: 10, format: 'json' },
+ undefined, { recencyWindow: true });
expect(keptIds(results.observations)).toEqual([101]);
});
diff --git a/tests/worker/search/relevance-fusion.test.ts b/tests/worker/search/relevance-fusion.test.ts
index db2cfd347..2cc7a5e2b 100644
--- a/tests/worker/search/relevance-fusion.test.ts
+++ b/tests/worker/search/relevance-fusion.test.ts
@@ -107,7 +107,7 @@ describe('worker relevance search fuses Chroma with keyword matches', () => {
setup(2);
const result = await distanceLimitedManager(0.1).search({ ...args,
query: 'underwater basket weaving certification exam',
- }, undefined, { keywordRecencyWindow: true });
+ }, undefined, { recencyWindow: true });
expect(result.observations).toEqual([]);
expect(result.sessions).toEqual([]);
@@ -181,7 +181,7 @@ describe('worker relevance search fuses Chroma with keyword matches', () => {
it('keeps the recency window on the keyword leg for per-prompt injection', async () => {
setup(200);
- const result = await manager().search(args, undefined, { keywordRecencyWindow: true });
+ const result = await manager().search(args, undefined, { recencyWindow: true });
expect(result.observations.map((row: { id: number }) => row.id)).not.toContain(targetId);
expect(result.observations).toHaveLength(10);
diff --git a/tests/worker/search/semantic-filtered-candidates.test.ts b/tests/worker/search/semantic-filtered-candidates.test.ts
index 6b8703305..1f1ca2ead 100644
--- a/tests/worker/search/semantic-filtered-candidates.test.ts
+++ b/tests/worker/search/semantic-filtered-candidates.test.ts
@@ -111,6 +111,12 @@ async function runFixture(env: Record<string, string> = {}) {
const args = { query: 'retrievalneedle', project: 'filtered', type: env.SEARCH_TYPE || (sparseCategory ? 'all' : 'observations'),
orderBy: 'relevance', limit: env.LIMIT || (sparseCategory ? '20' : '2'), offset: env.OFFSET || '0', ...filter };
if (env.SEARCH_TYPE === 'default') delete args.type;
+ // A typed search (the HTTP route) ranks Chroma matches of any age (#6758).
+ // Where only their age excludes the filler rows, it passes the 90-day bound
+ // explicitly, so it walks the same filtered candidate windows as the
+ // orchestrator and the strategy do with the default window.
+ const httpArgs = sparseCategory || field === 'recency'
+ ? { ...args, dateStart: new Date(now - 90 * 86400000).toISOString() } : args;
const app = express(); new SearchRoutes(manager).setupRoutes(app);
server = app.listen(0, '127.0.0.1');
if (!server.listening) await new Promise<void>(resolve => server.once('listening', resolve));
@@ -119,7 +125,7 @@ async function runFixture(env: Record<string, string> = {}) {
calls.length = 0; windows.length = 0;
for (const ids of Object.values(hydratedByCategory)) ids.length = 0;
const result = pipeline === 'http'
- ? await (await fetch('http://127.0.0.1:' + server.address().port + '/api/search?' + new URLSearchParams({ ...args, format: 'json' }))).json()
+ ? await (await fetch('http://127.0.0.1:' + server.address().port + '/api/search?' + new URLSearchParams({ ...httpArgs, format: 'json' }))).json()
: pipeline === 'orchestrator' ? await manager.getOrchestrator().search(args)
: await new ChromaSearchStrategy(chroma, store).search({ ...args,
searchType: args.type?.includes(',') ? args.type.split(',') : args.type,
@@ -230,9 +236,18 @@ describe('unified semantic candidates after row filtering', () => {
for (const duplicate of ['0', '1']) {
const result = await runFixture({ BUDGET_SCENARIO: '1', DUPLICATE_KEYWORD: duplicate });
for (const row of result.results) {
- // The semantic match ties with or beats the keyword leg's first match,
- // the expired row: a typed search reads keyword matches of any age (#6539).
- expect(row.ids).toEqual([result.first, result.expired]);
+ // A typed search reads keyword matches of any age (#6539). The HTTP
+ // route also reads Chroma matches of any age (#6758): the expired row
+ // matches both legs and ranks first, and the second place goes to the
+ // semantic match or the keyword leg's next row, which fuse to equal
+ // scores. The orchestrator keeps the window: the semantic match ties
+ // with or beats the keyword leg's first match, the expired row.
+ if (row.pipeline === 'http') {
+ expect(row.ids[0]).toBe(result.expired);
+ expect([result.first, result.second]).toContain(row.ids[1]);
+ } else {
+ expect(row.ids).toEqual([result.first, result.expired]);
+ }
expect(new Set(row.ids).size).toBe(row.ids.length);
expect(row.calls.length).toBeLessThanOrEqual(10);
expect(row.calls.reduce((total: number, call: { n_results: number }) => total + call.n_results, 0)).toBeLessThanOrEqual(13100);
diff --git a/tests/worker/search/typed-search-vector-window.test.ts b/tests/worker/search/typed-search-vector-window.test.ts
new file mode 100644
index 000000000..62e84def8
--- /dev/null
+++ b/tests/worker/search/typed-search-vector-window.test.ts
@@ -0,0 +1,107 @@
+import { describe, expect, it, beforeEach, afterEach } from 'bun:test';
+import { SessionStore } from '../../../src/services/sqlite/SessionStore.js';
+import { SessionSearch } from '../../../src/services/sqlite/SessionSearch.js';
+import { SearchManager } from '../../../src/services/worker/SearchManager.js';
+
+// A typed relevance search fuses Chroma with the keyword leg (#6539), and the
+// keyword leg reads matches of any age. The Chroma leg still dropped rows older
+// than the default 90-day window, so a note that shares no word with the query
+// and is older than 90 days was lost, though Chroma ranked it first. The
+// server's hybrid search applies no window. Per-prompt injection keeps it.
+
+const DAY = 24 * 60 * 60 * 1000;
+const QUERY = 'authentication outage';
+
+describe('typed relevance search reads Chroma matches of any age', () => {
+ let store: SessionStore;
+ let search: SessionSearch;
+ let decoyIds: number[];
+ let targetId: number;
+
+ function storeObservation(title: string, narrative: string, ageDays: number, prompt: number): number {
+ return store.storeObservation('memory-1', 'app', {
+ type: 'discovery', title, subtitle: null, facts: [], narrative,
+ concepts: [], files_read: [], files_modified: [],
+ }, prompt, 0, Date.now() - ageDays * DAY, undefined, { skipTitleDedup: true }).id;
+ }
+
+ beforeEach(() => {
+ store = new SessionStore(':memory:');
+ search = new SessionSearch(store.db);
+ const sessionDbId = store.createSDKSession('content-1', 'app', 'search work');
+ store.ensureMemorySessionIdRegistered(sessionDbId, 'memory-1');
+ decoyIds = Array.from({ length: 30 }, (_, index) => storeObservation(
+ `Ranking helper ${index}`,
+ `Refactored a ranking helper, part ${index}.`,
+ 1 + index / 100,
+ index + 1,
+ ));
+ // No word in common with QUERY: only the embedding can find it.
+ targetId = storeObservation(
+ 'OAuth callback returned 500',
+ 'The SameSite cookie was dropped, so every sign-in failed.',
+ 200,
+ 100,
+ );
+ });
+
+ afterEach(() => {
+ store.close();
+ });
+
+ // search_observations prints one line per row; the title is enough here.
+ const formatter = {
+ formatTableHeader: () => '',
+ formatObservationIndex: (row: { title: string }) => row.title,
+ } as any;
+
+ // Chroma's order for the query: the old note first, then every decoy.
+ function manager(): SearchManager {
+ const ranking = [targetId, ...decoyIds];
+ const chromaSync = {
+ async queryChroma(_query: string, limit: number) {
+ const ids = ranking.slice(0, limit);
+ const rows = store.getObservationsByIds(ids, {});
+ const epochById = new Map(rows.map(row => [row.id, row.created_at_epoch]));
+ return {
+ ids,
+ distances: ids.map((_, index) => 0.2 + index / 100),
+ metadatas: ids.map(id => ({
+ sqlite_id: id, doc_type: 'observation', project: 'app', created_at_epoch: epochById.get(id),
+ })),
+ };
+ },
+ };
+ return new SearchManager(search, store, chromaSync as any, formatter, {} as any);
+ }
+
+ const args = { query: QUERY, type: 'observations', project: 'app', format: 'json', limit: 10 };
+ const ids = (result: any) => result.observations.map((row: { id: number }) => row.id);
+
+ it('returns a semantic match older than the recency window first', async () => {
+ const result = await manager().search(args);
+
+ expect(ids(result)[0]).toBe(targetId);
+ expect(result.observations).toHaveLength(10);
+ });
+
+ it('applies the same rule to search_observations', async () => {
+ const result = await manager().searchObservations({ query: QUERY, project: 'app', limit: 10 });
+
+ expect(result.content[0].text).toContain('OAuth callback returned 500');
+ });
+
+ it('keeps the recency window on the Chroma leg for per-prompt injection', async () => {
+ const result = await manager().search(args, undefined, { recencyWindow: true });
+
+ expect(ids(result)).not.toContain(targetId);
+ expect(result.observations).toHaveLength(10);
+ });
+
+ it('still applies an explicit date range', async () => {
+ const dateStart = new Date(Date.now() - 30 * DAY).toISOString().slice(0, 10);
+ const result = await manager().search({ ...args, dateStart });
+
+ expect(ids(result)).not.toContain(targetId);
+ });
+});