Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
feat(recall): relative since phrases; question ranks expired facts with include_expired
garrytand9178794ce25
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex e684c965f5..158edd62d2 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -10,6 +10,16 @@ credits are retained; no result has been reassigned to another provider. Originaidentifiers and attribution are available in the pre-removal Git revision`6040075c6cb95be5881cc2e1b76ef7d71f4e5d29` (retained on 2026-09-23).+## [Unreleased] - recall: relative `since` phrases and `question` with `include_expired` (W1 follow-up)++**`recall` takes `since: "6 weeks ago"` or `"last month"`, and ranks expired facts for a `question` when you pass `include_expired: true`. Both used to be refused.**++### Itemized changes++- `since` on `recall` (MCP and `gbrain recall --since`) falls back to relative phrases after its existing grammar: `"N weeks|months|years ago"`, `"a week ago"`, `"an hour ago"`, compact `"3w"`, `"2mo"`, `"1y"`, and `"last month"`, `"past 2 weeks"`, `"the last 6 weeks"`. Months and years step the UTC calendar and clamp the day. Every value that parsed before gives the same instant (`src/core/facts/since-parse.ts`). In the dev-only A12 agent smoke, an agent's `since: "6 weeks ago"` was refused and it fell back to a less precise call.+- `question` with `include_expired: true` ranks expired, superseded and lapsed facts alongside active ones, under the same read policy and filters, instead of returning `invalid_params`. Each row keeps its `expired_at` and `valid_until`. Without `include_expired`, ranking covers active facts only, as before. `question` with `supersessions` is still refused.+- The `include_expired` and `since` parameter descriptions say how they now behave; no parameter was added, renamed or made required.+## [0.60.202.0] - 2026-10-13**A page-unit call with its own budget now gets whole pages that fill that budget instead of many partial ones, and search can grade its candidates before the cross-encoder to report how often the reranker was paying for an answer retrieval already found. The page cut is on by default (`gbrain config set search.page_rank_cut off` restores the old path); the grade is off by default and never changes results.**diff --git a/docs/mcp/TOOL_REFERENCE.md b/docs/mcp/TOOL_REFERENCE.mdindex ffe2e9d570..16ef31d421 100644--- a/docs/mcp/TOOL_REFERENCE.md+++ b/docs/mcp/TOOL_REFERENCE.md@@ -328,14 +328,14 @@ MEMORY VERB (v1): retrieve saved facts/snippets — the protocol read verb. Filt| Parameter | Type | Guidance || --- | --- | --- || `entity` | string | Entity slug (canonical). Returns facts about this entity newest first, each labelled with its source_id. Across several granted sources, same-slug entities that no entity-identity group links are different entities: facts comes back empty and ambiguous_entity names each (source_id, entity_slug); pass source_id to read one. |-| `question` | string | Ranks active facts by relevance to this question (cosine to its embedding plus whole-word term share, +0.1 for a writer-dated fact) instead of newest first. Facts below the admission rule are left out, so an empty facts[] is a valid answer. Each fact carries `relevance` (a ranking score, about 0 to 2.1, not comparable across calls); the response carries `facts_order: "relevance"` and, when ranking ran without full semantic matching, `facts_degraded`. Applies inside `entity`, `session_id`, `since` and `grep`. Does not search pages (`query` does; both may be passed). Rejected with `supersessions` or `include_expired`, and over 2,000 characters (invalid_params, with the corrected call as `fix`). One query embedding per call, shared with a `query` of the same text. |+| `question` | string | Ranks active facts by relevance to this question (cosine to its embedding plus whole-word term share, +0.1 for a writer-dated fact) instead of newest first. Facts below the admission rule are left out, so an empty facts[] is a valid answer. Each fact carries `relevance` (a ranking score, about 0 to 2.1, not comparable across calls); the response carries `facts_order: "relevance"` and, when ranking ran without full semantic matching, `facts_degraded`. Applies inside `entity`, `session_id`, `since` and `grep`. Does not search pages (`query` does; both may be passed). With `include_expired`, expired and superseded facts are ranked too. Rejected with `supersessions`, and over 2,000 characters (invalid_params, with the corrected call as `fix`). One query embedding per call, shared with a `query` of the same text. || `query` | string | MEMORY_VERBS v1: free-text retrieval over pages (hybrid search arm). Response adds results[] (slug, title, chunk, evidence, create_safety, provenance). Combinable with entity (both arms run). Degrades to keyword-only search when no embedding provider is configured (search_degraded notes it; never an error). || `budget_tokens` | number | MEMORY_VERBS v1: server-side token budget (char/4 estimate). Facts pack first, then results. Response adds budget_tokens, budget_used, dropped_count. || `budget_policy` | string (`facts_first`, `query_first`) | Optional packing order. facts_first (default) packs facts first, then page results. query_first packs the ranked page prefix before facts only with a nonblank query and positive finite budget; a positive budget below one token keeps neither arm. Without a nonblank query and an active budget, packing stays facts_first. Neither policy skips oversized items or truncates. Supplying this option adds budget_packing accounting. Keep fact-focused/entity-filtered questions on facts_first. || `source_id` | string | Optional concrete source id for both facts and page results. Narrows the caller’s authorized scope, including an explicit default; a denied, missing, or archived source fails rather than widening. Omit to preserve the existing context/grant scope. |-| `since` | string | ISO 8601 datetime or duration shorthand (e.g. "8 hours ago"). Filters the FACTS arm only, on event time (valid_from, falling back to created_at); composes with `entity` and `session_id`. An unparseable value is rejected (invalid_params). |+| `since` | string | ISO 8601 datetime, duration shorthand (e.g. "8 hours ago", "2d") or a relative phrase ("6 weeks ago", "a month ago", "last month", "the past 2 years"; months and years step the calendar). Filters the FACTS arm only, on event time (valid_from, falling back to created_at); composes with `entity` and `session_id`. An unparseable value is rejected (invalid_params). || `session_id` | string | Source session id (e.g. topic-A). Returns facts captured in that session. |-| `include_expired` | boolean | When true, include expired_at IS NOT NULL rows. Default false. |+| `include_expired` | boolean | When true, include expired_at IS NOT NULL rows. Default false. With `question`, expired, superseded and lapsed facts are ranked alongside active ones (each row keeps its `expired_at` and `valid_until`). || `supersessions` | boolean | When true, return only the supersession audit log (facts with superseded_by set), newest first by COALESCE(expired_at, valid_until). || `limit` | number | Per-arm cap: max fact rows AND max search results. Default 50, cap 100. || `grep` | string | Substring filter on fact text (case-insensitive). Applied in SQL before the limit, so matches on high-cardinality entities are found even outside the newest-N window. |diff --git a/docs/protocol/MEMORY_VERBS_v1.md b/docs/protocol/MEMORY_VERBS_v1.mdindex 0c71583e6d..76ff7823fb 100644--- a/docs/protocol/MEMORY_VERBS_v1.md+++ b/docs/protocol/MEMORY_VERBS_v1.md@@ -122,21 +122,23 @@ Retrieve saved facts and (with `query`) budget-packed page snippets.- `entity` scopes the FACTS arm; `query` runs the hybrid-search arm overpages; both present ⇒ both arms run.- `since`: ISO 8601 date/datetime — filters the FACTS arm only in v1. (The- reference implementation also accepts relative phrases like `"8 hours ago"`- as a convenience; only ISO 8601 is part of the frozen contract.) The window+ reference implementation also accepts relative phrases like `"8 hours ago"`,+ `"6 weeks ago"` and `"last month"` as a convenience; only ISO 8601 is part+ of the frozen contract.) The windowis measured on event time (`valid_from`, falling back to `created_at`) andcomposes with `entity` and `session_id` in the same query, before theper-arm limit. An unparseable value is rejected with `invalid_params`.- `limit` is a PER-ARM cap (facts and search results each).- `question`: optional string (at most 2,000 characters). The FACTS arm then- returns active facts ranked by relevance to the question instead of newest+ returns active facts (every fact, expired and superseded included, with+ `include_expired: true`) ranked by relevance to the question instead of newestfirst: cosine to the question's embedding plus whole-word term share, plus0.1 when the fact carries a writer-supplied date. Facts below the admissionrule are not returned, so an empty `facts[]` is a valid answer. `entity`,`session_id`, `since` and `grep` filter before ranking. `question` does not- search pages; `query` does, and both may be passed. `supersessions: true` or- `include_expired: true` with `question` is `invalid_params` (ranking covers- active facts only); the error's `fix.mcp` is the call without them. One query+ search pages; `query` does, and both may be passed. `supersessions: true`+ with `question` is `invalid_params` (the supersession log is not ranked); the+ error's `fix.mcp` is the call without it. One queryembedding per call, no model call. Without an embedding provider, withembeddings turned off, or when the embed fails, facts rank by term share and`facts_degraded.reason` says why. A server without question ranking ignoresdiff --git a/llms-full.txt b/llms-full.txtindex 91ca5833ef..b30dd2094d 100644--- a/llms-full.txt+++ b/llms-full.txt@@ -8810,21 +8810,23 @@ Retrieve saved facts and (with `query`) budget-packed page snippets.- `entity` scopes the FACTS arm; `query` runs the hybrid-search arm overpages; both present ⇒ both arms run.- `since`: ISO 8601 date/datetime — filters the FACTS arm only in v1. (The- reference implementation also accepts relative phrases like `"8 hours ago"`- as a convenience; only ISO 8601 is part of the frozen contract.) The window+ reference implementation also accepts relative phrases like `"8 hours ago"`,+ `"6 weeks ago"` and `"last month"` as a convenience; only ISO 8601 is part+ of the frozen contract.) The windowis measured on event time (`valid_from`, falling back to `created_at`) andcomposes with `entity` and `session_id` in the same query, before theper-arm limit. An unparseable value is rejected with `invalid_params`.- `limit` is a PER-ARM cap (facts and search results each).- `question`: optional string (at most 2,000 characters). The FACTS arm then- returns active facts ranked by relevance to the question instead of newest+ returns active facts (every fact, expired and superseded included, with+ `include_expired: true`) ranked by relevance to the question instead of newestfirst: cosine to the question's embedding plus whole-word term share, plus0.1 when the fact carries a writer-supplied date. Facts below the admissionrule are not returned, so an empty `facts[]` is a valid answer. `entity`,`session_id`, `since` and `grep` filter before ranking. `question` does not- search pages; `query` does, and both may be passed. `supersessions: true` or- `include_expired: true` with `question` is `invalid_params` (ranking covers- active facts only); the error's `fix.mcp` is the call without them. One query+ search pages; `query` does, and both may be passed. `supersessions: true`+ with `question` is `invalid_params` (the supersession log is not ranked); the+ error's `fix.mcp` is the call without it. One queryembedding per call, no model call. Without an embedding provider, withembeddings turned off, or when the embed fails, facts rank by term share and`facts_degraded.reason` says why. A server without question ranking ignoresdiff --git a/src/commands/recall.ts b/src/commands/recall.tsindex 37236a2736..5ba46339a8 100644--- a/src/commands/recall.ts+++ b/src/commands/recall.ts@@ -40,6 +40,7 @@ import { callRemoteTool, RemoteMcpError, unpackToolResult } from '../core/mcp-climport { readCursor, writeCursor } from '../core/recall-cursor-state.ts';import { resolveSourceId, resolveSourceIdEngineFree, SourceTargetError } from '../core/source-resolver.ts';import { usageError } from '../cli/cli-error.ts';+import { parseRelativeSince } from '../core/facts/since-parse.ts';// Same kebab-case shape gate the source-resolver applies. v0.32: applied// locally on thin-client where the canonical resolver's assertSourceExists@@ -204,7 +205,7 @@ function parseSinceParam(raw: string): Date | null {n * 24 * 60 * 60 * 1000;return new Date(Date.now() - ms);}- return null;+ return parseRelativeSince(raw);}function validateAndNormalizeFlags(flags: ParsedFlags): void {diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex bce6b22e6c..23c93dc381 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -528,6 +528,8 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText }{ since: '0.60.202.0', text: '`recall` with `budget_tokens` and a `return_unit` now fills its budget: saved facts are packed first and the delivered evidence gets the budget they leave, so the same parameters return more evidence (up to about 16% more on long conversations). Before, delivered blocks were dropped after the facts and re-counted with a rougher estimate. `budget_policy: "query_first"` is unchanged.' },// W5 adaptive page-unit cut, default on after memory proof wave 2 (gbrain-evals #126). `since` is the VERSION placeholder.{ since: '0.60.202.0', text: 'A `return_unit: "page"` call that passes its own budget (`token_budget` on `search` and `query`, `budget_tokens` on `recall`) now stops adding pages once their whole delivered pages fill 1.5 times that budget (`search.page_rank_cut: whole_pages`, `search.page_rank_cut_factor: 1.5`), and the search mode\'s chunk-token cut no longer limits it: you get fewer pages, more of them whole, filling the budget, instead of many partial ones. On 72 BEAM conversations (regression evidence, not held-out) accuracy moved -0.25 points against the cut off (lower bound -1.00, non-inferior at the -3 margin) with delivered context at budget. The response reports it as `delivery.page_rank_cut`. `gbrain config set search.page_rank_cut off` restores the old behavior.' },+ // W1 follow-up (memory proof wave 2). `since` is a placeholder equal to the branch's VERSION until the merge-slot stamp.+ { since: '0.60.202.0', text: '`recall` now accepts relative `since` phrases it used to refuse (`"6 weeks ago"`, `"a month ago"`, `"last month"`, `"the past 2 years"`; months and years step the calendar), and `question` with `include_expired: true` now ranks expired and superseded facts alongside active ones instead of refusing the call. Every `since` value that parsed before gives the same window, and calls without `include_expired` rank active facts only, as before.' },];/** The newest disclosed change's release: the notice id moves only when a release adds rows. */diff --git a/src/core/facts/question-recall.ts b/src/core/facts/question-recall.tsindex 5897afbf32..a48ba41dfb 100644--- a/src/core/facts/question-recall.ts+++ b/src/core/facts/question-recall.ts@@ -1,6 +1,6 @@/*** recall's `question` ranking (MEMORY_VERBS v1 additive field): active facts- * ranked by relevance to the question instead of by recency, inside any+ * (every fact with `include_expired`) ranked by relevance to the question instead of by recency, inside any* `entity`, `session_id`, `since` or `grep` filter. The candidate pool and* the score are fact-relevance.ts's (shared with the temporal fact reserve);* the read policy is recall's own (source scope, trust floor, quarantine and@@ -86,9 +86,9 @@ function invalidQuestionCall(message: string, suggestion: string, retry: Record<}/**- * The validated `question`, or null when absent. Refuses the combinations- * ranking cannot honor (`supersessions`, `include_expired`) and an over-long- * question, each with the corrected call as its fix.+ * The validated `question`, or null when absent. Refuses the combination+ * ranking cannot honor (`supersessions`) and an over-long question, each with+ * the corrected call as its fix. `include_expired` widens the ranked pool.*/export function parseQuestionParam(p: Record<string, unknown>): string | null {if (p.question === undefined || p.question === null) return null;@@ -104,11 +104,6 @@ export function parseQuestionParam(p: Record<string, unknown>): string | null {throw invalidQuestionCall('question cannot be combined with supersessions: the supersession log is ordered by when facts were replaced, not ranked.','Drop supersessions to rank active facts, or drop question to read the supersession log.', rest, 'The same recall without supersessions.');}- if (p.include_expired === true) {- const { include_expired: _e, ...rest } = args;- throw invalidQuestionCall('question cannot be combined with include_expired: ranking runs over active facts only.',- 'Drop include_expired to rank active facts, or drop question to list expired facts newest first.', rest, 'The same recall without include_expired.');- }if (question.length > QUESTION_MAX_CHARS) {throw invalidQuestionCall(`question is ${question.length} characters; the limit is ${QUESTION_MAX_CHARS}.`,`Shorten question to at most ${QUESTION_MAX_CHARS} characters.`, { ...args, question: question.slice(0, QUESTION_MAX_CHARS) }, `The same recall with question cut to ${QUESTION_MAX_CHARS} characters.`);@@ -159,6 +154,8 @@ export interface QuestionRecallInput {sessionId: string | null;since: Date | null;grep: string | null;+ /** Rank expired, superseded and lapsed facts too (recall's `include_expired`). */+ includeExpired?: boolean;}export interface QuestionRecall {@@ -171,13 +168,14 @@ export interface QuestionRecall {ambiguousEntity: EntityCandidate[] | null;}-/** Active facts ranked by relevance to `question` under recall's read policy and filters. */+/** Active facts (all facts with `includeExpired`) ranked by relevance to `question` under recall's read policy and filters. */export async function rankFactsByQuestion(ctx: OperationContext, input: QuestionRecallInput): Promise<QuestionRecall> {const { question, scope } = input;const filters: FactPoolFilters = {...(input.sessionId ? { sessionId: input.sessionId } : {}),...(input.since ? { since: input.since } : {}),...(input.grep ? { grep: input.grep } : {}),+ ...(input.includeExpired ? { includeExpired: true } : {}),};const empty = (degraded?: FactsDegraded, ambiguousEntity: EntityCandidate[] | null = null): QuestionRecall => ({ rows: [], relevance: new Map(), ambiguousEntity, ...(degraded ? { degraded } : {}) });try {diff --git a/src/core/facts/since-parse.ts b/src/core/facts/since-parse.tsnew file mode 100644index 0000000000..48ee4c23cd--- /dev/null+++ b/src/core/facts/since-parse.ts@@ -0,0 +1,53 @@+/**+ * Relative `since` phrases for recall (a dependency-free leaf shared by the+ * recall op and the recall CLI). Both parsers try their existing grammar+ * first (ISO 8601, epoch millis, "8 hours ago", "2d") and fall back to this+ * one, so every input that parsed before keeps its result.+ *+ * Accepted (case-insensitive, any spacing):+ * - "6 weeks ago", "a week ago", "an hour ago", "one month ago"+ * - compact weeks, months and years: "3w", "2mo", "1y" (optionally "... ago")+ * - "last month", "past week", "the last 6 weeks", "in the past 2 years"+ * Months and years step the UTC calendar, clamping the day to the target+ * month's length (March 31 minus one month is February 28 or 29).+ */++const UNITS: Array<[RegExp, 'second' | 'minute' | 'hour' | 'day' | 'week' | 'month' | 'year']> = [+ [/^(?:s|secs?|seconds?)$/, 'second'],+ [/^(?:mins?|minutes?)$/, 'minute'],+ [/^(?:h|hrs?|hours?)$/, 'hour'],+ [/^(?:d|days?)$/, 'day'],+ [/^(?:w|wks?|weeks?)$/, 'week'],+ [/^(?:mo|mos|months?)$/, 'month'],+ [/^(?:y|yrs?|years?)$/, 'year'],+];++const AGO_RE = /^(?:(?<n>\d+)\s*|(?<one>an?|one)\s+)(?<unit>[a-z]+)(?:\s+ago)?$/;+const LAST_RE = /^(?:in\s+)?(?:the\s+)?(?:last|past)\s+(?:(?:(?<n>\d+)|(?<one>an?|one))\s+)?(?<unit>[a-z]+)$/;++function step(now: number, n: number, unit: string): Date | null {+ const fixed: Record<string, number> = { second: 1000, minute: 60_000, hour: 3_600_000, day: 86_400_000, week: 604_800_000 };+ if (fixed[unit] !== undefined) {+ const d = new Date(now - n * fixed[unit]);+ return Number.isFinite(d.getTime()) ? d : null;+ }+ const d = new Date(now);+ const months = d.getUTCFullYear() * 12 + d.getUTCMonth() - (unit === 'year' ? n * 12 : n);+ const year = Math.floor(months / 12);+ const month = months - year * 12;+ const lastDay = new Date(Date.UTC(year, month + 1, 0)).getUTCDate();+ const out = new Date(Date.UTC(year, month, Math.min(d.getUTCDate(), lastDay), d.getUTCHours(), d.getUTCMinutes(), d.getUTCSeconds(), d.getUTCMilliseconds()));+ return Number.isFinite(out.getTime()) ? out : null;+}++/** The start of a relative `since` window, or null when the phrase is not one of the forms above. */+export function parseRelativeSince(raw: string, now: number = Date.now()): Date | null {+ const s = raw.trim().toLowerCase().replace(/\s+/g, ' ');+ const g = (s.match(AGO_RE) ?? s.match(LAST_RE))?.groups;+ if (!g) return null;+ const unit = UNITS.find(([re]) => re.test(g.unit!))?.[1];+ if (!unit) return null;+ const count = g.n === undefined ? 1 : Number(g.n);+ if (!Number.isSafeInteger(count)) return null;+ return step(now, count, unit);+}diff --git a/src/core/operation-manifest.generated.ts b/src/core/operation-manifest.generated.tsindex 7cd950c179..2f17a4532e 100644--- a/src/core/operation-manifest.generated.ts+++ b/src/core/operation-manifest.generated.ts@@ -4900,7 +4900,7 @@ export const OPERATION_MANIFEST: OperationMeta[] = [},"since": {"type": "string",- "description": "ISO 8601 or \"8 hours ago\"."+ "description": "ISO 8601, \"8 hours ago\" or \"last month\"."},"session_id": {"type": "string",@@ -4908,7 +4908,7 @@ export const OPERATION_MANIFEST: OperationMeta[] = [},"include_expired": {"type": "boolean",- "description": "Include expired."+ "description": "Include expired facts (with question, ranked too)."},"supersessions": {"type": "boolean",diff --git a/src/core/ops/facts.ts b/src/core/ops/facts.tsindex ade2b59773..4dbe8155f7 100644--- a/src/core/ops/facts.ts+++ b/src/core/ops/facts.ts@@ -49,6 +49,7 @@ import { activationSuppressionNotice, suppressionSummary } from '../eligibility/import { stampPageTrust, stampRowTrust } from '../eligibility/stamp.ts';import type { TrustTier } from '../trust/tier.ts';import { AUDIT_ROW_SOURCES } from '../facts/audit-sources.ts';+import { parseRelativeSince } from '../facts/since-parse.ts';import { parseQuestionParam, questionRecallNotices, rankFactsByQuestion, recallHintNotice, unlinkedNamesakes, type EntityCandidate, type QuestionRecall } from '../facts/question-recall.ts';// ============================================================@@ -270,9 +271,9 @@ const recall: Operation = {budget_tokens: { type: 'number', description: 'Token budget; facts pack first.' },budget_policy: { type: 'string', enum: ['facts_first', 'query_first'], description: 'Default facts_first.' },source_id: { type: 'string', description: 'One source you may read.' },- since: { type: 'string', description: 'ISO 8601 or "8 hours ago".' },+ since: { type: 'string', description: 'ISO 8601, "8 hours ago" or "last month".' },session_id: { type: 'string', description: "This session's facts." },- include_expired: { type: 'boolean', description: 'Include expired.' },+ include_expired: { type: 'boolean', description: 'Include expired facts (with question, ranked too).' },supersessions: { type: 'boolean', description: 'Supersession log only.' },limit: { type: 'number', description: 'Per-arm max (default 50, cap 100).' },grep: { type: 'string', description: 'Text substring.' },@@ -375,7 +376,7 @@ const recall: Operation = {throw verbError('invalid_params',`since is not a parseable timestamp or duration: "${String(p.since).slice(0, 60)}"`,- 'Pass an ISO 8601 datetime (e.g. "2026-08-11T00:00:00Z"), Unix epoch millis, or a duration such as "8 hours ago" / "2d".',+ 'Pass an ISO 8601 datetime (e.g. "2026-08-11T00:00:00Z"), Unix epoch millis, a duration such as "8 hours ago" / "2d", or a relative phrase such as "6 weeks ago" / "last month".',);}const question = parseQuestionParam(p);@@ -394,7 +395,7 @@ const recall: Operation = {};if (question !== null) {- ranking = await rankFactsByQuestion(ctx, { question, params: p, factSources, limit, entity: entityParam, sessionId: sessionParam, since, grep,+ ranking = await rankFactsByQuestion(ctx, { question, params: p, factSources, limit, entity: entityParam, sessionId: sessionParam, since, grep, includeExpired,scope: { sourceIds: factSources, remote: ctx.remote !== false, excludePrivate, minTrust: eligibility.floor, suppressFlagged: eligibility.suppressFlagged } });({ rows, ambiguousEntity } = ranking);for (const notice of questionRecallNotices(ranking)) ctx.emitNotice?.(notice);@@ -1262,10 +1263,11 @@ export function clampRecallLimit(raw: unknown): number {/*** Parse a `since` parameter into a Date. Accepts ISO 8601, plain duration- * shorthand ("8 hours ago", "3 days ago", "30m", "1h", "2d", "7d"), or- * Unix epoch millis. Returns null on unparseable input.+ * shorthand ("8 hours ago", "3 days ago", "30m", "1h", "2d", "7d"), Unix+ * epoch millis, or a relative phrase (since-parse.ts: "6 weeks ago",+ * "last month"). Returns null on unparseable input.*/-function parseSinceParam(raw: unknown): Date | null {+export function parseSinceParam(raw: unknown): Date | null {if (raw == null) return null;if (typeof raw === 'number' && Number.isFinite(raw)) return new Date(raw);if (typeof raw !== 'string') return null;@@ -1288,7 +1290,7 @@ function parseSinceParam(raw: unknown): Date | null {n * 24 * 60 * 60 * 1000;return new Date(Date.now() - ms);}- return null;+ return parseRelativeSince(s);}/**diff --git a/src/core/search/fact-relevance.ts b/src/core/search/fact-relevance.tsindex 69059c1cf0..38498e8541 100644--- a/src/core/search/fact-relevance.ts+++ b/src/core/search/fact-relevance.ts@@ -75,6 +75,8 @@ export interface FactPoolFilters {/** Event time, COALESCE(valid_from, created_at). */since?: Date;grep?: string;+ /** Also pool expired, superseded and lapsed facts (recall's `include_expired`). */+ includeExpired?: boolean;}export interface FactPoolOpts {@@ -120,8 +122,8 @@ function poolPredicate(scope: FactPoolScope, filters: FactPoolFilters | undefineconst params: unknown[] = [scope.sourceIds?.length ? scope.sourceIds : [scope.sourceId ?? 'default'], [...AUDIT_ROW_SOURCES]];const bind = (v: unknown) => { params.push(v); return `$${params.length}`; };const clauses = [- 'f.source_id = ANY($1::text[]) AND f.expired_at IS NULL AND f.superseded_by IS NULL',- '(f.valid_until IS NULL OR f.valid_until > now()) AND f.source != ALL($2::text[])',+ filters?.includeExpired ? 'f.source_id = ANY($1::text[])' : 'f.source_id = ANY($1::text[]) AND f.expired_at IS NULL AND f.superseded_by IS NULL',+ filters?.includeExpired ? 'f.source != ALL($2::text[])' : '(f.valid_until IS NULL OR f.valid_until > now()) AND f.source != ALL($2::text[])',quarantinedProvenanceFilterFragment('f'),...(scope.remote ? [`f.visibility = 'world'`] : []),...(scope.excludePrivate ? [privateProvenanceFilterFragment('f')] : []),@@ -231,11 +233,12 @@ export async function countUncomparableFacts(engine: BrainEngine, scope: FactPooconst column = await factsEmbeddingColumn(engine);if (!column) return [];const declared = column.dims === dims;+ const active = filters?.includeExpired ? '' : ' AND f.expired_at IS NULL';// Cheap candidates first (idx_facts_unembedded, idx_facts_embedding_model), then the read policy on those rows only.const uncomparable = declared- ? `SELECT f.id FROM facts f WHERE f.source_id = ANY($1::text[]) AND f.expired_at IS NULL AND (f.embedding IS NULL OR f.embedded_text_hash IS DISTINCT FROM md5(f.fact))- UNION SELECT f.id FROM facts f WHERE f.source_id = ANY($1::text[]) AND f.expired_at IS NULL AND (f.embedding_model IS NULL OR f.embedding_model < ${model} OR f.embedding_model > ${model})`- : `SELECT f.id FROM facts f WHERE f.source_id = ANY($1::text[]) AND f.expired_at IS NULL AND NOT (${comparable(model, `$${params.length + 2}`)})`;+ ? `SELECT f.id FROM facts f WHERE f.source_id = ANY($1::text[])${active} AND (f.embedding IS NULL OR f.embedded_text_hash IS DISTINCT FROM md5(f.fact))+ UNION SELECT f.id FROM facts f WHERE f.source_id = ANY($1::text[])${active} AND (f.embedding_model IS NULL OR f.embedding_model < ${model} OR f.embedding_model > ${model})`+ : `SELECT f.id FROM facts f WHERE f.source_id = ANY($1::text[])${active} AND NOT (${comparable(model, `$${params.length + 2}`)})`;const rows = await customPlan<{ source_id: string; n: number | string }>(engine,`WITH u AS MATERIALIZED (${uncomparable})SELECT f.source_id, count(*) AS n FROM facts f WHERE f.id IN (SELECT id FROM u) AND ${where}diff --git a/test/fixtures/goldens/cli/tools-json.json b/test/fixtures/goldens/cli/tools-json.jsonindex 5a9b903fc2..7b46f5bad6 100644--- a/test/fixtures/goldens/cli/tools-json.json+++ b/test/fixtures/goldens/cli/tools-json.json@@ -2,8 +2,8 @@"golden": {"exitCode": 0,"stderr": "",- "stdoutBytes": 231878,- "stdoutSha256": "b1d2ef871d92ce9360a547ac5cc1651136a6eb12a96799fcdd317459870690b9",+ "stdoutBytes": 231928,+ "stdoutSha256": "2cf3ded2c08406a354bd1a845e551f793f1f59e7a3a09b0102235aa190783844","toolNames": ["remember","entity",@@ -5817,7 +5817,7 @@"type": "string"},"include_expired": {- "description": "Include expired.",+ "description": "Include expired facts (with question, ranked too).","type": "boolean"},"include_pending": {@@ -5868,7 +5868,7 @@"type": "string"},"since": {- "description": "ISO 8601 or \"8 hours ago\".",+ "description": "ISO 8601, \"8 hours ago\" or \"last month\".","type": "string"},"source_id": {diff --git a/test/recall-question.test.ts b/test/recall-question.test.tsindex c954a49e2b..65b28a45f5 100644--- a/test/recall-question.test.ts+++ b/test/recall-question.test.ts@@ -256,14 +256,54 @@ for (const kind of testBackends()) {const sup = await refusal({ question: COFFEE, supersessions: true });expect(sup.code).toBe('invalid_params');expect(sup.fix?.mcp).toEqual({ tool: 'recall', arguments: { question: COFFEE } });- const exp = await refusal({ question: COFFEE, include_expired: true, entity: ENTITY });- expect(exp.code).toBe('invalid_params');- expect(exp.fix?.mcp).toEqual({ tool: 'recall', arguments: { question: COFFEE, entity: ENTITY } });const long = await refusal({ question: 'coffee '.repeat(400) });expect(long.code).toBe('invalid_params');expect(String((long.fix?.mcp?.arguments as R).question).length).toBe(QUESTION_MAX_CHARS);});+ test('include_expired with question ranks expired, superseded and lapsed facts alongside active ones; without it they stay out', async () => {+ await fact('oldroast', { text: 'OLDROAST Alice Example drank dark roast coffee every morning before the switch', daysAgo: 40 });+ await fact('lapsed', { text: 'LAPSED Alice Example dark roast coffee morning subscription', daysAgo: 41 });+ await fact('replaced', { text: 'REPLACED Alice Example dark roast coffee morning order', daysAgo: 42 });+ await engine.executeRaw(`UPDATE facts SET expired_at = now() - interval '1 day' WHERE id = $1`, [ids.oldroast]);+ await engine.executeRaw(`UPDATE facts SET valid_until = now() - interval '1 day' WHERE id = $1`, [ids.lapsed]);+ await engine.executeRaw(`UPDATE facts SET superseded_by = $1, expired_at = now() WHERE id = $2`, [ids.roast, ids.replaced]);+ try {+ const active = markers((await recall(local(), { question: COFFEE, limit: 100 })).facts);+ for (const m of ['OLDROAST', 'LAPSED', 'REPLACED']) expect(active).not.toContain(m);+ const r = await recall(local(), { question: COFFEE, include_expired: true, limit: 100 });+ expect(r.facts_order).toBe('relevance');+ const all = markers(r.facts);+ expect(all).toEqual(expect.arrayContaining(['ROAST', 'OLDROAST', 'LAPSED', 'REPLACED']));+ const scores = r.facts.map((f: R) => f.relevance);+ expect([...scores].sort((a, b) => b - a)).toEqual(scores);+ expect(r.facts.find((f: R) => f.id === ids.oldroast).expired_at).not.toBeNull();+ const newest = new Set((await recall(local(), { include_expired: true, limit: 100 })).facts.map((f: R) => f.id));+ for (const f of r.facts) expect(newest.has(f.id)).toBe(true);+ for (const c of untrusted()) {+ const remote = markers((await recall(c, { question: COFFEE, include_expired: true, limit: 100 })).facts);+ expect(remote).toContain('OLDROAST');+ expect(remote).not.toContain('PRIVVIS');+ }+ } finally {+ await engine.executeRaw('DELETE FROM facts WHERE id = ANY($1::bigint[])', [[ids.oldroast, ids.lapsed, ids.replaced]]);+ }+ });++ test('since takes relative phrases (weeks, months, "a week ago", "last month") with or without question; an unparseable phrase is still refused', async () => {+ const window = (r: R) => markers(r.facts);+ expect(window(await recall(local(), { question: COFFEE, since: '3 weeks ago' }))).toContain('TEA');+ expect(window(await recall(local(), { question: COFFEE, since: '3 weeks ago' }))).not.toContain('ROAST');+ expect(window(await recall(local(), { question: COFFEE, since: '6 weeks ago' }))).toContain('ROAST');+ expect(window(await recall(local(), { question: COFFEE, since: 'last month' }))).toContain('TEA');+ expect(window(await recall(local(), { since: 'a week ago' }))).toEqual(expect.arrayContaining(['OFFSITE', 'HIRING']));+ expect(window(await recall(local(), { since: 'a week ago' }))).not.toContain('TEA');+ expect(window(await recall(local(), { since: '3 weeks ago' }))).toEqual(window(await recall(local(), { since: '21d' })));+ let refused: OperationError | null = null;+ try { await recall(local(), { question: COFFEE, since: 'a while back' }); } catch (e) { refused = e as OperationError; }+ expect(refused?.code).toBe('invalid_params');+ });+test('the admission rule is configurable between the two preregistered rule sets', async () => {await engine.setConfig(QUESTION_ADMISSION_KEY, 'facts_arm');try {diff --git a/test/recall-since-relative.test.ts b/test/recall-since-relative.test.tsnew file mode 100644index 0000000000..e738237315--- /dev/null+++ b/test/recall-since-relative.test.ts@@ -0,0 +1,81 @@+/**+ * recall `since` relative phrases (src/core/facts/since-parse.ts). The recall+ * op's parser keeps its grammar and falls back to the relative one, so the+ * additive check compares it with a copy of the grammar it had before the+ * fallback on every form that grammar accepted. Op-level coverage on both+ * engines is in test/recall-question.test.ts.+ */+import { describe, expect, test } from 'bun:test';+import { parseRelativeSince } from '../src/core/facts/since-parse.ts';+import { parseSinceParam } from '../src/core/ops/facts.ts';++const NOW = Date.UTC(2026, 2, 31, 12, 0, 0);+const DAY = 86_400_000;++function previousGrammar(raw: unknown): Date | null {+ if (raw == null) return null;+ if (typeof raw === 'number' && Number.isFinite(raw)) return new Date(raw);+ if (typeof raw !== 'string') return null;+ const s = raw.trim();+ if (!s) return null;+ const iso = Date.parse(s);+ if (Number.isFinite(iso)) return new Date(iso);+ const ago = s.match(/^(\d+)\s*(s|sec|seconds?|m|min|minutes?|h|hr|hours?|d|days?)(?:\s+ago)?$/i);+ if (!ago) return null;+ const n = parseInt(ago[1]!, 10);+ const unit = ago[2]!.toLowerCase();+ const ms = unit.startsWith('s') ? n * 1000 : unit.startsWith('m') ? n * 60_000 : unit.startsWith('h') ? n * 3_600_000 : n * DAY;+ return new Date(Date.now() - ms);+}++describe('parseRelativeSince', () => {+ test('weeks, months and years, counted or "a"/"an"/"one", with or without "ago"', () => {+ const at = (s: string) => parseRelativeSince(s, NOW)?.toISOString() ?? null;+ expect(at('6 weeks ago')).toBe(new Date(NOW - 42 * DAY).toISOString());+ expect(at('6 Weeks Ago')).toBe(new Date(NOW - 42 * DAY).toISOString());+ expect(at('a week ago')).toBe(new Date(NOW - 7 * DAY).toISOString());+ expect(at('an hour ago')).toBe(new Date(NOW - 3_600_000).toISOString());+ expect(at('3w')).toBe(new Date(NOW - 21 * DAY).toISOString());+ expect(at('1 month ago')).toBe('2026-02-28T12:00:00.000Z');+ expect(at('2mo')).toBe('2026-01-31T12:00:00.000Z');+ expect(at('one year ago')).toBe('2025-03-31T12:00:00.000Z');+ expect(at('1y')).toBe('2025-03-31T12:00:00.000Z');+ });++ test('"last" and "past" windows', () => {+ const at = (s: string) => parseRelativeSince(s, NOW)?.toISOString() ?? null;+ expect(at('last month')).toBe('2026-02-28T12:00:00.000Z');+ expect(at('last week')).toBe(new Date(NOW - 7 * DAY).toISOString());+ expect(at('past 2 weeks')).toBe(new Date(NOW - 14 * DAY).toISOString());+ expect(at('the last 6 weeks')).toBe(new Date(NOW - 42 * DAY).toISOString());+ expect(at('in the past 2 years')).toBe('2024-03-31T12:00:00.000Z');+ expect(at('last year')).toBe('2025-03-31T12:00:00.000Z');+ });++ test('anything else is not a relative phrase', () => {+ for (const s of ['month ago', 'weeks ago', 'last', 'last few weeks', 'aweek', 'a while back', 'next week', '6 fortnights ago', '99999999999999999999 years ago', '9999999 years ago']) {+ expect(parseRelativeSince(s, NOW)).toBeNull();+ }+ });+});++describe('recall parseSinceParam stays additive', () => {+ test('every form the previous grammar accepted parses to the same instant', () => {+ const forms: unknown[] = ['2026-08-11T00:00:00Z', '2026-08-11', 'Tue, 11 Aug 2026 00:00:00 GMT', 1_786_406_400_000,+ '8 hours ago', '3 days ago', '30m', '1h', '2d', '7d', '45 sec', '10 minutes ago', ' 2d '];+ for (const f of forms) {+ const before = previousGrammar(f);+ const after = parseSinceParam(f);+ expect(before).not.toBeNull();+ expect(Math.abs(after!.getTime() - before!.getTime())).toBeLessThan(1000);+ }+ });++ test('forms the previous grammar refused now parse, and garbage is still refused', () => {+ for (const f of ['6 weeks ago', 'last month', 'a week ago', '2mo']) {+ expect(previousGrammar(f)).toBeNull();+ expect(parseSinceParam(f)).toBeInstanceOf(Date);+ }+ for (const f of ['a while back', '', ' ', null, undefined, {}, Number.NaN]) expect(parseSinceParam(f)).toBeNull();+ });+});