Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
feat(recall): report unmeasured fact admission floors as facts_calibration (#6590)
garrytan1ef123e2fba6
diff --git a/docs/architecture/key-files/graph-and-facts.md b/docs/architecture/key-files/graph-and-facts.mdindex 256f5076b2..d569079556 100644--- a/docs/architecture/key-files/graph-and-facts.md+++ b/docs/architecture/key-files/graph-and-facts.md@@ -76,7 +76,7 @@ rejection of serve-only flags before a brain opens.- `src/core/extract-timeline-from-meetings.ts` — normalizes canonical incoming and pack-owned outgoing `attended` edges into meeting/person roles before timeline fan-out. SQL requires a live person and live meeting (including legacy meeting notes); existing private-meeting filtering, source opt-in and source-qualified deduplication still apply. Dual-engine tests in `test/extract-timeline-attendance.test.ts` use an empty gazetteer so a body-mention fallback cannot conceal a broken attendance consumer. #6273: on a managed brain the rows are grouped per entity page and published by `publishMeetingTimelines` as database-only `managed_maintenance_meeting_timeline` requests (at most 200 rows each; the request id binds the page revision and the rows; rows already stored are not resubmitted, so a rerun admits nothing; a pending request stops that source for the run). `prepareMeetingTimeline` (dispatched from `prepared-maintenance.ts`) refuses malformed rows `invalid_params`, and at apply time re-reads each meeting (tier, title, slug, visibility) and runs the #5575 gate at the stored tier under `withWriteTrust`. The job handler throws on refused or pending writes. Test: `test/extract-timeline-from-meetings-managed.test.ts`.- `src/core/context/delta-cursor.ts` — pure helpers for delta's per-arm cursor: the opaque base64url `cursor` (`{v:1, p:[since, slug], f:[created_at, id]}`, validated like `since`), microsecond ISO normalization and the one-microsecond clamp, `nextPagesPos`/`nextFactsPos` (delivered prefix, `now() - 2 s` horizon `DELTA_COMMIT_LAG_MS`, the facts cursor computed from raw rows so a duplicate cluster split by a budget cut loses nothing), `resolveDeltaStart` and `legacyDeltaCursor`. `test/delta-cursor-integrity.test.ts`.-- `src/core/facts/question-recall.ts` — recall's `question`: `parseQuestionParam` refuses `supersessions`, `include_expired` and more than 2,000 characters with the corrected call as `fix.mcp`; `rankFactsByQuestion` resolves `entity` per source to pairs and runs `unlinkedNamesakes` on the whole filtered pool before ranking, embeds the question once through `embedQueryBounded` (the gateway's query-embedding cache, so a `query` of the same text shares it; the embedding opt-out, a missing provider or a failed embed rank by term share and set `facts_degraded.reason`), ranks with `search/fact-relevance.ts` under the `recall.question_admission` rule (`reserve` default, or `facts_arm`; pool, uncomparable count and rule read concurrently), hydrates the ranked ids through `rowToFact`, counts uncomparable facts (`facts_degraded.unembedded`, the `facts_unembedded` notice with the `embed --stale --facts` preview) and turns a DB error into `unavailable` (`fix.next: wait`). `recallHintNotice` builds `recall_hint`. Tests: `test/recall-question.test.ts` (both engines), `test/recall-question-cli.test.ts`.+- `src/core/facts/question-recall.ts` — recall's `question`: `parseQuestionParam` refuses `supersessions`, `include_expired` and more than 2,000 characters with the corrected call as `fix.mcp`; `rankFactsByQuestion` resolves `entity` per source to pairs and runs `unlinkedNamesakes` on the whole filtered pool before ranking, embeds the question once through `embedQueryBounded` (the gateway's query-embedding cache, so a `query` of the same text shares it; the embedding opt-out, a missing provider or a failed embed rank by term share and set `facts_degraded.reason`), ranks with `search/fact-relevance.ts` under the `recall.question_admission` rule (`reserve` default, or `facts_arm`; pool, uncomparable count and rule read concurrently), hydrates the ranked ids through `rowToFact`, counts uncomparable facts (`facts_degraded.unembedded`, the `facts_unembedded` notice with the `embed --stale --facts` preview), sets `calibration` (recall's informational `facts_calibration: {status: 'unmeasured', model_key}`, #6590) when the cosine arm ran on a model with no row in `FACT_ADMISSION_FLOOR_EVIDENCE` (`search/fact-relevance.ts`, shared with doctor `fact_admission_floors`), with the `facts_calibration_unmeasured` info notice deduped per brain per session by its `dedupe_key` (test `test/recall-facts-calibration-6590.test.ts`), and turns a DB error into `unavailable` (`fix.next: wait`). `recallHintNotice` builds `recall_hint`. Tests: `test/recall-question.test.ts` (both engines), `test/recall-question-cli.test.ts`.- `src/core/ops/facts.ts` — shared fact/memory operations, including `recall` and the `delta` cursor. Every recall response carries `facts_order` (`newest`, or `relevance` when `question` ranked the facts arm through `facts/question-recall.ts`); a `query` call without `question` or a fact filter emits `recall_hint`. `context_pack` and `delta` `facts[]` carry recall's `fact_id` and `provenance` (the stored `facts.source`), read in one batched `withProvenance` lookup by the delivered ids, so hot memory and MCP `_meta` stay unchanged; remote callers get provenance through the same redaction as the fact text, and it never enters `text` (#6146, `test/context-pack-fact-traceability.test.ts`). Recall keeps source/visibility and fact filters before per-arm candidate limits. Its default/explicit `facts_first` packing preserves the frozen memory-verb contract, including the positive sub-one budget quirk. Optional `query_first` packs the ranked page prefix first only with a nonblank query and positive finite budget; floor-zero and exhausted remainders explicitly return empty arms rather than call the unbounded zero-budget packer. Neither arm skips oversized prefix items or truncates. No-query and inactive-budget paths keep legacy behavior. Only policy-supplied calls add `budget_packing` effective-policy/reason and candidate/kept/dropped/estimated-used accounting. Counter sums match the frozen fields. Do not change the global packer or fact relevance to implement this policy. Delta rejects calendar-invalid ISO dates and years outside 0001-9999 (on the parsed UTC value) before normalization across fractional-second forms, while preserving valid six-digit microsecond cursors. Delta's per-arm cursor (contributor audit wave P0): the start position resolves `cursor` > `since` (whole tuple, slug only when supplied) > the session row; each arm advances through its delivered prefix only (`src/core/context/delta-cursor.ts`), an arm that failed or never finished holds, the conservative legacy `next_cursor.since`/`slug` never passes the oldest undelivered fact, and a legacy caller at an unpageable same-timestamp boundary is refused with `delta_cursor_upgrade_required`. Incomplete wakes emit `delta_incomplete` (`fix.next: wait`, `report` on the third consecutive wake, counted atomically in `session_context_state.degraded_wakes` with an in-process fallback when the store is down); a failed state read refuses with `unavailable`/`session_state` instead of re-initializing at now. `test/recall-budget-policy.test.ts` pins recall behavior; `test/ambient-recall.test.ts` pins delta cursor validation; `test/delta-cursor-integrity.test.ts` (both engines) pins every no-advance path, the facts drain, legacy safety and the commit-visibility bound.- `src/core/markdown-code.ts` — `stripCodeBlocks` masks fenced and inline code while preserving every CR/LF and UTF-16 code-unit offset. Citation paragraphs and later link references retain their original boundaries, including after an unclosed fence. `parseTimelineEntries` in `src/core/link-extraction.ts` groups the optional dash with its trailing whitespace so leading whitespace does not trigger overlapping repetition. Existing date and delimiter rules remain unchanged. Standalone backtick and tilde fences require valid closing markers; historical inline triple-backtick spans remain masked. Pinned through real FS/DB link and timeline consumers by `test/timeline-parser-regression.test.ts`; its adversarial whitespace workload runs in a timeout-bounded child process. #6133: inline spans pair backtick runs of equal length (CommonMark), found read-only by `fence-scan.ts` `scanMarkdownCode`/`inlineCodeEndAt` over a view where a bare CR is a space (so a span may still cross one), so a double-backtick span and a span holding a single backtick are masked whole and a backslash-escaped backtick opens nothing; the lint `placeholder-date` rule (`src/commands/lint.ts`) runs over the masked text, so placeholders in inline code no longer fire (`test/lint-3958.test.ts`, `test/timeline-parser-regression.test.ts`).diff --git a/docs/mcp/TOOL_REFERENCE.md b/docs/mcp/TOOL_REFERENCE.mdindex 3b084c9acf..82d728ab9c 100644--- a/docs/mcp/TOOL_REFERENCE.md+++ b/docs/mcp/TOOL_REFERENCE.md@@ -342,7 +342,7 @@ 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). 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. |+| `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`. When semantic matching ran on an embedding model whose fact admission floors were never measured, the response also carries the informational `facts_calibration: {status: "unmeasured", model_key}` (one `facts_calibration_unmeasured` notice per session explains it; `gbrain doctor --only fact_admission_floors --json` names the model): treat a short facts list as weaker evidence of "nothing matched". 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. |diff --git a/docs/protocol/MEMORY_VERBS_v1.md b/docs/protocol/MEMORY_VERBS_v1.mdindex ae737a0d5f..e5dff447a7 100644--- a/docs/protocol/MEMORY_VERBS_v1.md+++ b/docs/protocol/MEMORY_VERBS_v1.md@@ -188,6 +188,7 @@ Response — an additive SUPERSET of the plain facts envelope on EVERY call| `facts_order` | string | `relevance` (question passed) or `newest` || `facts[].relevance` | number? | question calls only: the ranking score (about 0 to 2.1); not a probability and not comparable across calls || `facts_degraded` | object? | question calls only: `reason` (`keyword_only_no_embedding_provider`, `keyword_only_embedding_disabled`, `embed_timeout`, `embed_unavailable`, `no_query_terms`, `facts_embedding_column_missing`) and `unembedded` (facts in scope without a comparable embedding; the `facts_unembedded` notice carries the `gbrain embed --stale --facts` preview) |+| `facts_calibration` | object? | question calls only, informational (additive since #6590): present when semantic matching ranked the facts on an embedding model whose fact admission floors were never measured; `status` (`unmeasured`) and `model_key` (`provider:model@dims`, the key doctor `fact_admission_floors` reports). A short or empty `facts[]` is then weaker evidence of "nothing matched". It never replaces `facts_degraded`; one `facts_calibration_unmeasured` notice (kind `info`) per brain per session explains it || `budget_tokens` / `budget_used` / `dropped_count` | int? | present for a positive finite numeric budget, including when its floor is zero || `budget_packing` | object? | present only when a valid `budget_policy` is supplied; effective policy and per-arm accounting |diff --git a/src/commands/doctor/checks/fact-admission-floors.ts b/src/commands/doctor/checks/fact-admission-floors.tsindex 6232e01e7e..7229d68405 100644--- a/src/commands/doctor/checks/fact-admission-floors.ts+++ b/src/commands/doctor/checks/fact-admission-floors.ts@@ -12,10 +12,7 @@ import type { Check } from '../../doctor.ts';import { connectedEngine, type DoctorContext, type DoctorEntry } from '../context.ts';import { embeddingsDisabled } from '../../../core/embedding-disabled.ts';import { calibrationKey } from '../../../core/facts/supersession-threshold.ts';-import { FACTS_ARM_COSINE_MIN, RESERVE_COSINE_MIN } from '../../../core/search/fact-relevance.ts';--/** Embedding models whose admission floors an eval measured, keyed `provider:model@dims`. Add a row only with an eval behind it. */-export const FACT_ADMISSION_FLOOR_EVIDENCE: Readonly<Record<string, string>> = {};+import { FACT_ADMISSION_FLOOR_EVIDENCE, FACTS_ARM_COSINE_MIN, RESERVE_COSINE_MIN } from '../../../core/search/fact-relevance.ts';async function runFactAdmissionFloors(ctx: DoctorContext): Promise<Check[]> {const engine = connectedEngine(ctx);diff --git a/src/core/error-registry.ts b/src/core/error-registry.tsindex e094feccf9..55ca6456af 100644--- a/src/core/error-registry.ts+++ b/src/core/error-registry.ts@@ -606,6 +606,7 @@ export const NOTICE_CODES = {degraded_recall: { kind: 'degraded', summary: 'A retrieval stage that affects recall did not run; an empty or thin result is not proof of absence. A failed rerank names its reason (timeout, budget, rate_limited, unreachable, auth, provider_error), the fused-order fallback and the session\'s count of reranker-degraded calls; timeout and rate_limited say to repeat the call after a delay, the rest point at doctor\'s reranker_health.' },source_binding_narrowed: { kind: 'info', summary: "A GBRAIN_SOURCE / .gbrain-source binding narrowed an unqualified read that came back empty; the fix reads another source explicitly." },degraded_dedup: { kind: 'info', summary: 'remember ran without an embedding provider, so only exact duplicates are detected.' },+ facts_calibration_unmeasured: { kind: 'info', summary: 'recall --question ranked facts with semantic matching on an embedding model whose fact admission floors were never measured (`facts_calibration: {status: "unmeasured", model_key}`); a short facts list is weaker evidence of "nothing matched". Once per brain per session; the fix is the read-only `gbrain doctor --only fact_admission_floors --json`.' },private_fact_not_pushed: { kind: 'info', summary: 'remember saved a private fact: only local CLI recall reads it, and session hooks never push it into a new agent session.' },local_transcripts: { kind: 'info', summary: 'The brain host keeps recent session transcripts that page reads never return and this connection cannot read; the fix is the CLI read (`gbrain transcripts recent --json`).' },synthesis_keyless: { kind: 'info', summary: 'think returned gathered evidence without synthesis because no chat-model key is configured (by design on a keyless brain).' },diff --git a/src/core/facts/question-recall.ts b/src/core/facts/question-recall.tsindex a48ba41dfb..2342b7443b 100644--- a/src/core/facts/question-recall.ts+++ b/src/core/facts/question-recall.ts@@ -15,13 +15,14 @@ import type { Action, Notice } from '../agent-output.ts';import type { OperationContext } from '../ops/contract.ts';import { opError } from '../ops/contract.ts';import { MEMORY_VERBS_VERSION } from '../verbs.ts';-import { isAvailable } from '../ai/gateway.ts';+import { getEmbeddingDimensions, getEmbeddingModel, isAvailable } from '../ai/gateway.ts';+import { calibrationKey } from './supersession-threshold.ts';import { rowToFact, type FactRowSqlShape } from '../engine-sql/facts.ts';import { loadEmbeddingQueryPrefix } from '../search/query-prefix.ts';import { embedQueryBounded, makeQueryEmbedDeadline } from '../search/hybrid.ts';import { resolveHnswIterativeScan } from '../search/hnsw-iterative-scan.ts';import {- QUESTION_ADMISSION_RULES, admitted, collectFactCandidates, countUncomparableFacts, poolEntityPairs, queryTerms, scoreFactCandidates,+ FACT_ADMISSION_FLOOR_EVIDENCE, QUESTION_ADMISSION_RULES, admitted, collectFactCandidates, countUncomparableFacts, poolEntityPairs, queryTerms, scoreFactCandidates,type FactPoolFilters, type FactPoolScope, type QuestionAdmissionRule,} from '../search/fact-relevance.ts';@@ -38,6 +39,18 @@ export interface FactsDegraded {unembedded?: number;}+/**+ * #6590: the cosine arm admitted facts at the absolute floors, and the+ * embedding model has no measured floor (FACT_ADMISSION_FLOOR_EVIDENCE), so on+ * a high-baseline embedder an empty or short facts list is weaker evidence of+ * "nothing matched". Informational: `facts_degraded` is unchanged.+ */+export interface FactsCalibration {+ status: 'unmeasured';+ /** `provider:model@dims`, the key doctor `fact_admission_floors` reports. */+ model_key: string;+}+export type EntityCandidate = { source_id: string; entity_slug: string };/**@@ -163,6 +176,8 @@ export interface QuestionRecall {/** fact id → relevance (cosine + term share + 0.1 when dated). */relevance: Map<number, number>;degraded?: FactsDegraded;+ /** Present when the cosine arm ran on a model with no measured admission floor. */+ calibration?: FactsCalibration;/** The source holding the most uncomparable facts, for the `embed --stale --facts` fix. */unembeddedSource?: string;ambiguousEntity: EntityCandidate[] | null;@@ -208,11 +223,13 @@ export async function rankFactsByQuestion(ctx: OperationContext, input: Question? await ctx.engine.executeRaw<FactRowSqlShape>('SELECT * FROM facts WHERE source_id = ANY($1::text[]) AND id = ANY($2::bigint[])', [input.factSources, ids]): [];const byId = new Map(raw.map(r => { const row = rowToFact(r); return [row.id, { ...row, embedding: null }] as const; }));+ const modelKey = embedding && pool.column ? calibrationKey(getEmbeddingModel(), getEmbeddingDimensions()) : null;return {rows: ids.flatMap(id => byId.get(id) ?? []),relevance: new Map(ranked.map(s => [s.candidate.id, Math.round(s.score * 1e4) / 1e4])),ambiguousEntity: null,...(degraded ? { degraded } : {}),+ ...(modelKey && FACT_ADMISSION_FLOOR_EVIDENCE[modelKey] === undefined ? { calibration: { status: 'unmeasured' as const, model_key: modelKey } } : {}),...(uncomparable[0] ? { unembeddedSource: uncomparable[0].source_id } : {}),};} catch (error) {@@ -236,12 +253,33 @@ export function recallHintNotice(p: Record<string, unknown>, queryText: string):};}-/** Notices for a question-ranked recall: facts the cosine arm could not compare, with the preview-then-approve embed fix. */-export function questionRecallNotices(ranking: QuestionRecall): Notice[] {+const FACT_FLOORS_VERIFY = { argv: ['gbrain', 'doctor', '--only', 'fact_admission_floors', '--json'] };++/**+ * #6590: the once-per-session explanation of `facts_calibration`. Kind info+ * (muteable); its `dedupe_key` (brain + model key) keeps it to one notice per+ * brain per session in the notice ledger, while the response field rides+ * every call.+ */+export function factsCalibrationNotice(calibration: FactsCalibration, brainId?: string): Notice {+ return {+ code: 'facts_calibration_unmeasured',+ kind: 'info',+ why: `recall ranked saved facts with semantic matching on embedding model ${calibration.model_key}, whose fact admission floors were never measured (facts_calibration: unmeasured). `+ + 'If this model scores unrelated text high, a fact can pass for a question nothing answers, so a short facts list is weaker evidence than on a measured model; check the facts against the question before relying on them. Results and facts_degraded are unchanged.',+ fix: { argv: FACT_FLOORS_VERIFY.argv, consent: [], actor: 'agent', requires_exclusive: false, verify: FACT_FLOORS_VERIFY,+ why: "Read-only: doctor's fact_admission_floors names the model key, the cosine floors in use and whether an eval measured them." },+ dedupe_key: `${brainId ?? 'host'}|${calibration.model_key}`,+ };+}++/** Notices for a question-ranked recall: the unmeasured-floor explanation, and facts the cosine arm could not compare with the preview-then-approve embed fix. */+export function questionRecallNotices(ranking: QuestionRecall, brainId?: string): Notice[] {+ const calibration = ranking.calibration ? [factsCalibrationNotice(ranking.calibration, brainId)] : [];const n = ranking.degraded?.unembedded ?? 0;- if (!n || !ranking.unembeddedSource) return [];+ if (!n || !ranking.unembeddedSource) return calibration;const base = ['gbrain', 'embed', '--stale', '--facts', '--source', ranking.unembeddedSource];- return [{+ return [...calibration, {code: 'facts_unembedded',kind: 'degraded',why: `${n} saved fact(s) in scope have no embedding this brain can compare with the question (none stored, another embedding model, a changed text or other dimensions), so they were ranked by word overlap alone and a relevant one can be missing.`,diff --git a/src/core/ops/facts.ts b/src/core/ops/facts.tsindex af4982b883..24e32f7ccc 100644--- a/src/core/ops/facts.ts+++ b/src/core/ops/facts.ts@@ -399,7 +399,7 @@ const recall: Operation = {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);+ for (const notice of questionRecallNotices(ranking, ctx.brainId)) ctx.emitNotice?.(notice);} else if (p.supersessions === true) {// Visibility filters at the ENGINE level (before each source's LIMIT),// same as the sibling fact-list arms — a post-merge filter would let a@@ -607,6 +607,7 @@ const recall: Operation = {total: packedFacts.length,facts_order: ranking ? 'relevance' : 'newest',...(ranking?.degraded ? { facts_degraded: ranking.degraded } : {}),+ ...(ranking?.calibration ? { facts_calibration: ranking.calibration } : {}),...(ambiguousEntity ? { ambiguous_entity: { candidates: ambiguousEntity, suggestion: AMBIGUOUS_ENTITY_SUGGESTION } } : {}),...(pending_consolidation_count !== undefined ? { pending_consolidation_count } : {}),// MEMORY_VERBS v1 envelope (G1B superset — additive on every response).diff --git a/src/core/search/fact-relevance.ts b/src/core/search/fact-relevance.tsindex 78c3a1d61d..9bc9fb612a 100644--- a/src/core/search/fact-relevance.ts+++ b/src/core/search/fact-relevance.ts@@ -66,6 +66,13 @@ export const RESERVE_COSINE_MIN = 0.5;const RESERVE_TERM_SHARE_MIN = 0.34;/** The facts-arm floor; `query`'s facts arm (facts-arm.ts) and the `facts_arm` admission rule share it. */export const FACTS_ARM_COSINE_MIN = 0.6;+/**+ * Embedding models whose admission floors an eval measured, keyed+ * `provider:model@dims` (facts/supersession-threshold.ts calibrationKey). Add+ * a row only with an eval behind it. Doctor `fact_admission_floors` and+ * recall's `facts_calibration` (#6590) read it.+ */+export const FACT_ADMISSION_FLOOR_EVIDENCE: Readonly<Record<string, string>> = {};export interface FactPoolScope {sourceId?: string; sourceIds?: string[]; remote: boolean;diff --git a/src/core/verbs.ts b/src/core/verbs.tsindex 8622d7cf0d..a9524aecd5 100644--- a/src/core/verbs.ts+++ b/src/core/verbs.ts@@ -581,6 +581,15 @@ export const RESPONSE_SCHEMAS: Record<VerbName, Record<string, unknown>> = {unembedded: { type: 'integer', description: 'Facts in scope without a comparable embedding (ranked by word overlap only).' },},},+ facts_calibration: {+ type: 'object',+ description: 'Informational, present when question ranking used semantic matching on an embedding model whose fact admission floors were never measured: a short facts list is weaker evidence of "nothing matched". Never replaces facts_degraded.',+ required: ['status', 'model_key'],+ properties: {+ status: { type: 'string', enum: ['unmeasured'] },+ model_key: { type: 'string', description: 'provider:model@dims, the key doctor fact_admission_floors reports.' },+ },+ },results: {type: 'array',description: 'Search arm — present only when `query` was passed.',diff --git a/test/recall-facts-calibration-6590.test.ts b/test/recall-facts-calibration-6590.test.tsnew file mode 100644index 0000000000..462910d045--- /dev/null+++ b/test/recall-facts-calibration-6590.test.ts@@ -0,0 +1,119 @@+/**+ * #6590: recall `question` admits a fact on cosine similarity alone at fixed+ * floors (fact-relevance.ts) that no embedding model has measured, so on a+ * high-baseline embedder an unrelated question can clear them. The response+ * now says so: an informational `facts_calibration: { status: 'unmeasured',+ * model_key }` whenever the cosine arm ran on a model without measured+ * floors, plus one `facts_calibration_unmeasured` info notice per brain per+ * session whose fix is doctor `fact_admission_floors`. `facts_degraded` and+ * the degraded_recall notice are unchanged (MEMORY_VERBS v1 keeps its closed+ * `facts_degraded.reason` enum).+ *+ * PGLite in-memory; the embedder is a deterministic bag-of-words transport ($0).+ */+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { dispatchToolCall } from '../src/mcp/dispatch.ts';+import { NoticeLedger } from '../src/core/notice-ledger.ts';+import { configureGateway, getEmbeddingModel, resetGateway, __setEmbedTransportForTests, __clearQueryEmbedCacheForTests } from '../src/core/ai/gateway.ts';+import { RESPONSE_SCHEMAS } from '../src/core/verbs.ts';+import { NOTICE_CODES } from '../src/core/error-registry.ts';+import { FACT_ADMISSION_FLOOR_EVIDENCE } from '../src/core/search/fact-relevance.ts';++const MODEL_KEY_RE = /^openai:text-embedding-3-large@\d+$/;+let engine: PGLiteEngine;+let dims = 1536;++function bagOfWords(text: string): number[] {+ const v = new Array<number>(dims).fill(0);+ for (const token of text.toLowerCase().split(/[^a-z0-9]+/).filter(t => t.length >= 3)) {+ let h = 2166136261;+ for (const ch of token) h = Math.imul(h ^ ch.charCodeAt(0), 16777619) >>> 0;+ v[h % dims]! += 1;+ }+ const norm = Math.hypot(...v) || 1;+ return v.map(x => x / norm);+}++function keyed(): void {+ configureGateway({ embedding_model: 'openai:text-embedding-3-large', embedding_dimensions: dims, env: { OPENAI_API_KEY: 'sk-fake' } });+ __setEmbedTransportForTests((async (args: { values: string[] }) => ({ embeddings: args.values.map(bagOfWords) })) as never);+}++function keyless(): void {+ __setEmbedTransportForTests(null);+ configureGateway({ embedding_model: 'openai:text-embedding-3-large', embedding_dimensions: dims, env: {} });+}++type Res = Awaited<ReturnType<typeof dispatchToolCall>>;+const body = (res: Res) => JSON.parse(res.content[0]!.text) as Record<string, unknown>;+const codes = (res: Res) => ((res._meta?.gbrain_notices ?? []) as Array<{ code: string }>).map(n => n.code);++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ const [col] = await engine.executeRaw<{ dims: number }>(`SELECT a.atttypmod AS dims FROM pg_attribute a WHERE a.attrelid = to_regclass('facts') AND a.attname = 'embedding'`);+ dims = Number(col!.dims);+ keyed();+ await engine.putPage('people/alice-example', { type: 'person', title: 'Alice Example', compiled_truth: 'Alice is a founder.' });+ const text = 'Alice Example drinks dark roast coffee every morning';+ await engine.executeRaw(+ `INSERT INTO facts (source_id, entity_slug, fact, kind, visibility, valid_from, source, source_markdown_slug, embedding, embedding_model, embedded_text_hash, embedded_at)+ VALUES ('default', 'people/alice-example', $1, 'fact', 'world', now(), 'test', 'people/alice-example', $2::text::vector, $3, md5($1), now())`,+ [text, `[${bagOfWords(text).join(',')}]`, getEmbeddingModel()]);+}, 60_000);++afterAll(async () => {+ __setEmbedTransportForTests(null);+ resetGateway();+ await engine?.disconnect();+}, 60_000);++beforeEach(() => {+ __clearQueryEmbedCacheForTests();+ keyed();+});++describe('#6590 recall facts_calibration', () => {+ test('a question ranked by semantic matching on an unmeasured model carries facts_calibration; one notice per session', async () => {+ const opts = { remote: true, transport: 'stdio' as const, sourceId: 'default', noticeLedger: new NoticeLedger() };+ const first = await dispatchToolCall(engine as never, 'recall', { question: 'Does Alice Example drink dark roast coffee?' }, opts);+ const firstBody = body(first);+ expect(firstBody.facts_order).toBe('relevance');+ expect((firstBody.facts as unknown[]).length).toBeGreaterThan(0);+ expect(firstBody.facts_calibration).toEqual({ status: 'unmeasured', model_key: expect.stringMatching(MODEL_KEY_RE) });+ expect(firstBody.facts_degraded).toBeUndefined();+ expect(codes(first)).toContain('facts_calibration_unmeasured');+ const block = first.content.find(c => c.text.startsWith('[gbrain notice facts_calibration_unmeasured kind=info]'));+ expect(block?.text).toContain('gbrain doctor --only fact_admission_floors --json');+ expect(FACT_ADMISSION_FLOOR_EVIDENCE[(firstBody.facts_calibration as { model_key: string }).model_key]).toBeUndefined();++ const second = await dispatchToolCall(engine as never, 'recall', { question: 'What coffee does Alice Example like?' }, opts);+ expect(body(second).facts_calibration).toEqual(firstBody.facts_calibration);+ expect(codes(second)).not.toContain('facts_calibration_unmeasured');+ }, 60_000);++ test('no semantic matching (keyless brain) means no facts_calibration; facts_degraded keeps its closed reason', async () => {+ keyless();+ const res = await dispatchToolCall(engine as never, 'recall', { question: 'Does Alice Example drink dark roast coffee?' },+ { remote: true, transport: 'stdio' as const, sourceId: 'default', noticeLedger: new NoticeLedger() });+ const out = body(res);+ expect(out.facts_calibration).toBeUndefined();+ expect((out.facts_degraded as { reason: string }).reason).toBe('keyword_only_no_embedding_provider');+ expect(codes(res)).not.toContain('facts_calibration_unmeasured');+ }, 60_000);++ test('a newest-first recall (no question) has no facts_calibration', async () => {+ const res = await dispatchToolCall(engine as never, 'recall', { entity: 'people/alice-example' },+ { remote: true, transport: 'stdio' as const, sourceId: 'default', noticeLedger: new NoticeLedger() });+ expect(body(res).facts_calibration).toBeUndefined();+ }, 60_000);++ test('the field is declared in the recall response schema and the notice code is registered', () => {+ const props = (RESPONSE_SCHEMAS.recall as { properties: Record<string, { properties?: Record<string, { enum?: string[] }> }> }).properties;+ expect(props.facts_calibration?.properties?.status?.enum).toEqual(['unmeasured']);+ expect(props.facts_calibration?.properties?.model_key).toBeDefined();+ expect((NOTICE_CODES as Record<string, { kind: string }>).facts_calibration_unmeasured?.kind).toBe('info');+ });+});