Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
extraction: date-grounded prompt variant, extractor event dates, page-date valid_from; doctor checks
garrytan2eb8d0893579
diff --git a/src/commands/doctor/checks/ranking-extraction.ts b/src/commands/doctor/checks/ranking-extraction.tsnew file mode 100644index 0000000000..1d91acfe0d--- /dev/null+++ b/src/commands/doctor/checks/ranking-extraction.ts@@ -0,0 +1,77 @@+/**+ * Ranking and extraction settings: the brain's inbound-degree shape next to+ * the resolved hub-dampening half degree, and which LLM extraction prompts+ * resolve relative dates against the source's observation date.+ *+ * Both are informational (status ok): they report state and the next step,+ * never a recommended value — a degree histogram is not a relevance prior.+ */++import type { Check } from '../../doctor.ts';+import { connectedEngine, type DoctorContext, type DoctorEntry } from '../context.ts';+import { checkError } from '../check-fix.ts';+import { loadSearchModeConfig, resolveSearchMode } from '../../../core/search/mode.ts';+import { getExtractorVariant } from '../../../core/facts/extract.ts';++async function runHubDegreeShape(ctx: DoctorContext): Promise<Check[]> {+ const engine = connectedEngine(ctx);+ const checks: Check[] = [];+ try {+ const modeInput = await loadSearchModeConfig(engine);+ const halfDegree = resolveSearchMode({ mode: modeInput.mode, overrides: modeInput.overrides }).hub_dampening;+ const [row] = await engine.executeRaw<{ pages: number; p50: number | null; p90: number | null; p99: number | null; max: number | null; above: number }>(+ `WITH d AS (+ SELECT p.id, COUNT(DISTINCT l.from_page_id)::int AS n+ FROM pages p LEFT JOIN links l ON l.to_page_id = p.id AND l.from_page_id <> p.id+ AND l.link_source IS DISTINCT FROM 'mentions'+ WHERE p.deleted_at IS NULL GROUP BY p.id)+ SELECT COUNT(*)::int AS pages,+ percentile_disc(0.5) WITHIN GROUP (ORDER BY n) AS p50,+ percentile_disc(0.9) WITHIN GROUP (ORDER BY n) AS p90,+ percentile_disc(0.99) WITHIN GROUP (ORDER BY n) AS p99,+ MAX(n) AS max,+ COUNT(*) FILTER (WHERE $1::float8 > 0 AND n > $1::float8 + 1)::int AS above+ FROM d`, [typeof halfDegree === 'number' ? halfDegree : 0]);+ const shape = `inbound links per page p50 ${row?.p50 ?? 0}, p90 ${row?.p90 ?? 0}, p99 ${row?.p99 ?? 0}, max ${row?.max ?? 0} over ${row?.pages ?? 0} pages`;+ const setting = typeof halfDegree === 'number'+ ? `hub dampening at half degree ${halfDegree}: ${row?.above ?? 0} page(s) keep less than half of their backlink/graph lift.`+ : 'hub dampening is off (search.hub_dampening).';+ checks.push({+ name: 'hub_degree_shape',+ status: 'ok',+ message: `${shape}; ${setting} To see whether hub pages crowd a query, run gbrain search "<query>" --explain and read each row's backlink inbound count and hub weight.`,+ });+ } catch {+ checks.push(checkError('hub_degree_shape', 'read the inbound link degree shape'));+ }+ return checks;+}++export const hubDegreeShapeEntry: DoctorEntry = {+ name: 'hub_degree_shape',+ emits: ['hub_degree_shape'],+ run: runHubDegreeShape,+};++/** Extraction prompts the `extraction.date_grounding` setting changes. */+const GROUNDED_CONSUMERS = ['fact extraction (page hook, extract_facts, conversation facts)', 'life chronicle events', 'dream synthesis', 'extract_atoms', 'propose_takes'];++async function runExtractionDateGrounding(ctx: DoctorContext): Promise<Check[]> {+ const engine = connectedEngine(ctx);+ const checks: Check[] = [];+ const variant = await getExtractorVariant(engine);+ checks.push({+ name: 'extraction_date_grounding',+ status: 'ok',+ message: variant.dateGrounding+ ? `Relative dates resolve against each source's observation date in: ${GROUNDED_CONSUMERS.join(', ')}. Facts extracted before this was enabled keep their original wording; re-extract a source only with the user's consent (gbrain extract-conversation-facts --source-id <id> --dry-run previews it).`+ : 'extraction.date_grounding is off: extraction prompts keep relative dates ("last week") as written. Dated pages still store their facts at the page date.',+ });+ return checks;+}++export const extractionDateGroundingEntry: DoctorEntry = {+ name: 'extraction_date_grounding',+ emits: ['extraction_date_grounding'],+ run: runExtractionDateGrounding,+};diff --git a/src/commands/doctor/registry.ts b/src/commands/doctor/registry.tsindex 1e54ec8fef..1c68b94c58 100644--- a/src/commands/doctor/registry.ts+++ b/src/commands/doctor/registry.ts@@ -62,6 +62,7 @@ import {staleMentionsEntry,timelineHistoryEntry,} from './checks/graph-health.ts';+import { extractionDateGroundingEntry, hubDegreeShapeEntry } from './checks/ranking-extraction.ts';import {integrityEntry,jsonbIntegrityEntry,@@ -137,6 +138,8 @@ export const DOCTOR_CHECK_REGISTRY: readonly DoctorEntry[] = [orphanRatioEntry,staleMentionsEntry,timelineHistoryEntry,+ hubDegreeShapeEntry,+ extractionDateGroundingEntry,integrityEntry,jsonbIntegrityEntry,whoknowsEntry,diff --git a/src/commands/extract-conversation-facts.ts b/src/commands/extract-conversation-facts.tsindex 727900d5bb..b7d8fd5896 100644--- a/src/commands/extract-conversation-facts.ts+++ b/src/commands/extract-conversation-facts.ts@@ -66,6 +66,7 @@import type { BrainEngine, NewFact } from '../core/engine.ts';import type { Page } from '../core/types.ts';+import { observationDateFrom, resolveObservationDate, type ObservationDate } from '../core/ai/date-grounding.ts';import {extractFactsFromTurnWithOutcome,isFactsExtractionEnabled,@@ -498,6 +499,21 @@ export function splitIntoSegments(// Segment rendering with topical/temporal header.// ---------------------------------------------------------------------------+/**+ * Observation date of a conversation segment (date-grounding.ts): the+ * segment's own timestamp when it came from the transcript itself or the+ * page's frontmatter date — never the synthetic epoch fallback, and never a+ * timestamp the parser derived from effective_date (which may be an event+ * date). Otherwise the page's observation date, or null (unknown).+ */+export function segmentObservationDate(page: Pick<Page, 'slug' | 'frontmatter' | 'effective_date'>, startIso: string | undefined): ObservationDate | null {+ const day = startIso?.slice(0, 10);+ const context = deriveDateContext({ page: page as Page });+ const explicit = !!day && !day.startsWith('1970-')+ && (context.source === 'explicit' || context.source === 'frontmatter_date' || day !== context.fallbackDate);+ return explicit ? observationDateFrom(startIso) : resolveObservationDate({ slug: page.slug, frontmatter: page.frontmatter });+}+export function renderSegmentForExtraction(pageTitle: string,segment: ConversationSegment,@@ -1121,6 +1137,7 @@ async function processPage(source: PER_SEGMENT_SOURCE_PREFIX,engine: state.engine,abortSignal: state.signal,+ observationDate: segmentObservationDate(page, seg.startIso),});if (!extraction.ok) {// #3669 — rethrow BudgetExhausted UNWRAPPED. Wrapping it in a plain@@ -1172,9 +1189,13 @@ async function processPage(// Preserve the conversation's valid time instead of defaulting every// extracted fact to extraction time. Epoch-anchored parses have no// trustworthy date, so they retain the existing now() fallback.- ...(seg.startIso && !seg.startIso.startsWith('1970-')- ? { valid_from: new Date(seg.startIso) }- : {}),+ // A validated event date the extractor stated (date-grounding variant)+ // wins over the segment start.+ ...(fact.valid_from+ ? { valid_from: fact.valid_from }+ : seg.startIso && !seg.startIso.startsWith('1970-')+ ? { valid_from: new Date(seg.startIso) }+ : {}),context:fact.context ?? `from ${page.slug} segment ${seg.startIso}..${seg.endIso}`,}));diff --git a/src/core/chronicle/extract-events.ts b/src/core/chronicle/extract-events.tsindex 32a7919eed..b22e6ca95e 100644--- a/src/core/chronicle/extract-events.ts+++ b/src/core/chronicle/extract-events.ts@@ -307,13 +307,20 @@ export function defaultJudge(engine: BrainEngine): ChronicleJudge {const n = parseInt(capRaw, 10);if (Number.isFinite(n) && n > 0) maxTokens = n;}+ // extraction.date_grounding: the page date is the observation date; a+ // relative "last Tuesday" resolves against it, never against today.+ const { getExtractorVariant } = await import('../facts/extract.ts');+ const grounded = (await getExtractorVariant(engine)).dateGrounding === true;+ const { observationDateFrom, observationDateLine, observationDateRule } = await import('../ai/date-grounding.ts');+ const dateLine = grounded ? `${observationDateLine(observationDateFrom(input.effectiveDate))}\n` : '';let text: string;try {const res = await chat({- system: JUDGE_SYSTEM,+ system: grounded ? `${JUDGE_SYSTEM}\n${observationDateRule()}` : JUDGE_SYSTEM,messages: [{role: 'user',content:+ dateLine +`<page slug="${input.slug}" type="${input.type}" date="${input.effectiveDate ?? ''}">\n` +`${input.title}\n\n${body}\n</page>\n\n` +`Known attendees: ${input.attendees.slice(0, 10).join(', ') || '(none)'}.\nExtract the events.`,diff --git a/src/core/config.ts b/src/core/config.tsindex 8f2ed7308e..131f1e4f78 100644--- a/src/core/config.ts+++ b/src/core/config.ts@@ -1439,6 +1439,7 @@ export const KNOWN_CONFIG_KEYS: readonly string[] = [// B-16: confidence stored for an extracted candidate whose confidence is// missing or non-numeric (a number in 0..1). Unset keeps the legacy 1.0.'facts.extraction_missing_confidence',+ 'extraction.date_grounding', 'facts.attribution', // extraction prompt variants (facts/extract.ts getExtractorVariant)// [ENG-8] Brain-level default visibility for facts writes when the caller// didn't specify one: 'private' (default) | 'world'. Resolved by// src/core/facts/visibility.ts; explicit caller values always win.diff --git a/src/core/cycle/extract-atoms.ts b/src/core/cycle/extract-atoms.tsindex a3ea434086..53fddf5276 100644--- a/src/core/cycle/extract-atoms.ts+++ b/src/core/cycle/extract-atoms.ts@@ -58,6 +58,8 @@// sourceId arg — atoms always wrote to 'default' regardless of source,// which made the NOT EXISTS guard ineffective on federated brains.+import { observationDateLine, observationDateRule } from '../ai/date-grounding.ts';+import { getExtractorVariant } from '../facts/extract.ts';import type { BrainEngine, LinkBatchInput } from '../engine.ts';import { stripReasoningBlocks } from '../llm-json.ts';import type { PhaseResult } from '../cycle.ts';@@ -887,6 +889,7 @@ export async function runPhaseExtractAtoms(// "Keep safe defaults" comment) still leaves extractModel on this default,// matching the pre-refactor fail-soft behavior exactly.let extractModel = resolveTierDefault('utility');+ const dateGrounding = (await getExtractorVariant(engine)).dateGrounding === true;let budgetCap = DEFAULT_BUDGET_USD;let explicitBudget = false; // operator SET cycle.extract_atoms.budget_usd// #4529/#4540: the per-item input/output caps were hardcoded (slice(0, 50_000) +@@ -1095,6 +1098,9 @@ export async function runPhaseExtractAtoms(}const originLabel = item.kind === 'transcript' ? item.filePath : item.slug;+ // extraction.date_grounding: the source's own date (file name or dated+ // slug) is the observation date; undated sources say unknown.+ const observedOn = sourceDate(originLabel, '');// #4706: bind the cut ONCE. This is the exact text the model receives,// and quote provenance is verified against THIS rather than the full// item, so a quote can only verify against text the model actually saw.@@ -1112,11 +1118,12 @@ export async function runPhaseExtractAtoms(}const result = await chat({model: extractModel,- system: EXTRACT_PROMPT,+ system: dateGrounding ? `${EXTRACT_PROMPT}\n\n${observationDateRule()}` : EXTRACT_PROMPT,messages: [{role: 'user',- content: transcriptMessage(originLabel, promptContent),+ content: (dateGrounding ? `${observationDateLine(observedOn ? { date: observedOn, source: 'filename' } : null)}\n` : '') ++ transcriptMessage(originLabel, promptContent),},],maxTokens: maxOutputTokens, responseSchema: ATOMS_RESPONSE_SCHEMA,diff --git a/src/core/cycle/propose-takes.ts b/src/core/cycle/propose-takes.tsindex d0fa1e773e..570fcf3b9b 100644--- a/src/core/cycle/propose-takes.ts+++ b/src/core/cycle/propose-takes.ts@@ -37,6 +37,8 @@* phase can run hermetically in unit tests without touching the gateway.*/+import { observationDateLine, observationDateRule, resolveObservationDate, type ObservationDate } from '../ai/date-grounding.ts';+import { getExtractorVariant } from '../facts/extract.ts';import { randomUUID, createHash } from 'node:crypto';import { BaseCyclePhase, CYCLE_DEADLINE_RESERVE_MS, type ScopedReadOpts, type BasePhaseOpts } from './base-phase.ts';import { defaultTimeoutMsFor } from '../minions/handler-timeouts.ts';@@ -194,6 +196,15 @@ export type ProposeTakesExtractor = (input: {retryMaxTokens?: number;/** #5425: include EXTRACT_TAKES_ATTRIBUTION_RULES (opt-in). */attributionRules?: boolean;+ /**+ * extraction.date_grounding: resolve relative deadlines ("by Q3", "in 18+ * months") against the page's observation date. Prompt-only; the+ * idempotency key (prompt_version) is unchanged so enabling it never+ * reprocesses pages.+ */+ dateGrounding?: boolean;+ /** The page's observation date (date-grounding.ts), null when undated. */+ observationDate?: ObservationDate | null;}) => Promise<ProposedTake[]>;export interface ProposeTakesOpts extends BasePhaseOpts {@@ -418,6 +429,9 @@ export async function defaultExtractor(? EXTRACT_TAKES_PROMPT.replace('For each gradeable claim,', `${EXTRACT_TAKES_ATTRIBUTION_RULES}For each gradeable claim,`): EXTRACT_TAKES_PROMPT).replace('{EXISTING_TAKES_JSON}', JSON.stringify(input.existingTakes, null, 2))+ .replace('PAGE PROSE:\n', input.dateGrounding+ ? `${observationDateRule()}\n${observationDateLine(input.observationDate ?? null)}\n\nPAGE PROSE:\n`+ : 'PAGE PROSE:\n').replace('{PAGE_BODY}', input.pageBody);// #4494: per-run configurable caps (dream.propose_takes.max_tokens /@@ -702,6 +716,7 @@ class ProposeTakesPhase extends BaseCyclePhase {const extractor = opts.extractor ?? defaultExtractor;const attributionRules = String(await Promise.resolve(engine.getConfig?.('dream.propose_takes.attribution_rules')).catch(() => null) ?? '').trim() === 'true';+ const dateGrounding = (await getExtractorVariant(engine)).dateGrounding === true;const promptVersion = opts.promptVersion ?? `${PROPOSE_TAKES_PROMPT_VERSION}${attributionRules ? PROPOSE_TAKES_ATTRIBUTION_PROMPT_SUFFIX : ''}`;const pageLimit = opts.pageLimit ?? 100;const skipPagesWithFence = opts.skipPagesWithFence ?? false;@@ -908,6 +923,7 @@ class ProposeTakesPhase extends BaseCyclePhase {maxTokens: extractorMaxTokens,retryMaxTokens: extractorRetryMaxTokens,attributionRules,+ ...(dateGrounding ? { dateGrounding, observationDate: resolveObservationDate({ slug: page.slug }) } : {}),});} catch (err) {result.llm_calls_failed += 1;diff --git a/src/core/cycle/synthesize.ts b/src/core/cycle/synthesize.tsindex 21e64967ef..bd3f22e04e 100644--- a/src/core/cycle/synthesize.ts+++ b/src/core/cycle/synthesize.ts@@ -1,3 +1,5 @@+import { observationDateLine, observationDateRule } from '../ai/date-grounding.ts';+import { getExtractorVariant } from '../facts/extract.ts';import { maintenancePreflight, publishMaintenancePage, type MaintenanceAuthority } from '../persistence/prepared-maintenance.ts';import { postprocessManagedSynthesis, withPublishPending } from './synthesize-postprocess.ts';import { acceptedPendingReceipt } from '../persistence/accepted-pending.ts';@@ -883,6 +885,7 @@ async function runPhaseSynthesizeInner(config.mode,summaryDate,config.attributionRules,+ config.dateGrounding,));// One check for the whole chunk set: a transcript never half-submits.const callsPerChild = config.mode === 'agentic' ? config.maxTurns : 1;@@ -1483,6 +1486,8 @@ export interface SynthConfig {allowUnpriced: boolean;/** dream.synthesize.attribution_rules: add SYNTH_ATTRIBUTION_RULE to the prompt (#5425, opt-in). */attributionRules: boolean;+ /** extraction.date_grounding: label the transcript date as the observation date and resolve relative dates against it. */+ dateGrounding: boolean;cooldownHours: number;/*** D1: Override the per-chunk token budget (model_context × HEADROOM_RATIO@@ -1749,6 +1754,7 @@ export async function loadSynthConfig(engine: BrainEngine): Promise<SynthConfig>budgetUsd: parseBudgetUsd(await engine.getConfig('dream.synthesize.budget_usd'), DEFAULT_SYNTH_BUDGET_USD),allowUnpriced: await loadAllowUnpriced(engine),attributionRules: (await engine.getConfig('dream.synthesize.attribution_rules'))?.trim() === 'true',+ dateGrounding: (await getExtractorVariant(engine)).dateGrounding === true,cooldownHours,maxPromptTokens,maxChunksPerTranscript,@@ -2782,8 +2788,16 @@ function buildSynthesisPrompt(cycleDate: string = utcDate(),// #5425: opt-in speaker/withdrawal rule (dream.synthesize.attribution_rules).attributionRules = false,+ // extraction.date_grounding: the transcript's own date is the observation date;+ // the cycle date is never used to resolve relative references.+ dateGrounding = false,): string {const dateHint = t.inferredDate ?? cycleDate;+ const dateContextLine = !dateGrounding+ ? `- Today's date: ${dateHint}`+ : t.inferredDate+ ? `- ${observationDateLine({ date: t.inferredDate, source: 'caller' })}\n- ${observationDateRule().split('\n').join('\n ')}`+ : `- Observation date: unknown (today is ${cycleDate}; never resolve relative dates against it — keep them as written)`;const baseSlugSegment = sanitizeForSlug(t.basename) || `session-${dateHint}`;const isChunked = chunkTotal > 1;const hashSuffix = isChunked@@ -2816,7 +2830,7 @@ function buildSynthesisPrompt(return `You are synthesizing a conversation transcript into the user's personal knowledge brain.CONTEXT-- Today's date: ${dateHint}+${dateContextLine}- Transcript hash suffix (USE THIS in slugs): ${hashSuffix}- Source file basename: ${baseSlugSegment}${chunkBanner}${priorContradictionsBlock}${triageMapBlock}${linkManifestBlock}${allowedPathsBlock}diff --git a/src/core/doctor-categories.ts b/src/core/doctor-categories.tsindex 47bd973088..02e0f53dfa 100644--- a/src/core/doctor-categories.ts+++ b/src/core/doctor-categories.ts@@ -117,6 +117,10 @@ export const BRAIN_CHECK_NAMES: ReadonlySet<string> = new Set(['grade_confidence_drift','graph_coverage','graph_signals_coverage',+ // Ranking/extraction settings: degree shape next to search.hub_dampening,+ // and which extraction prompts resolve relative dates (informational).+ 'hub_degree_shape',+ 'extraction_date_grounding','hidden_by_search_policy','image_assets','integrity',diff --git a/src/core/facts/backstop.ts b/src/core/facts/backstop.tsindex 218d479d57..a9f822c8ba 100644--- a/src/core/facts/backstop.ts+++ b/src/core/facts/backstop.ts@@ -37,6 +37,7 @@* commit 13 wires it.*/+import { observationDateFrom, resolveObservationDate, type ObservationDate } from '../ai/date-grounding.ts';import type { BrainEngine, FactInsertStatus, NewFact } from '../engine.ts';import type { ResolutionSource } from '../entities/resolve.ts';import { isFactsBackstopEligible } from './eligibility.ts';@@ -158,6 +159,16 @@ export type FactsBackstopResult =skipped_reason?: import('./extract.ts').ExtractFailureReason;};+/** One pipeline run's input: the turn text plus its page provenance and observation date. */+interface PipelineInput {+ turnText: string;+ isDreamGenerated: boolean;+ ref?: string;+ pageSlug?: string;+ /** When the text was written or said; null/undefined = unknown. */+ observationDate?: ObservationDate | null;+}+interface ParsedPageInput {slug: string;type: PageType;@@ -518,6 +529,7 @@ async function runPipeline(// #4819: page provenance for DB-only rows. The turn-path entry// (runFactsPipeline) has no page, so it leaves this unset.pageSlug: parsedPage.slug,+ observationDate: resolveObservationDate({ slug: parsedPage.slug, frontmatter: parsedPage.frontmatter }),},ctx,abortSignal,@@ -552,7 +564,7 @@ async function runPipeline(* fallback regardless of local_path.*/async function runPipelineWithBody(- input: { turnText: string; isDreamGenerated: boolean; ref?: string; pageSlug?: string },+ input: PipelineInput,ctx: FactsBackstopCtx,abortSignal?: AbortSignal,): Promise<{ inserted: number; duplicate: number; superseded: number; fact_ids: number[]; entity_slugs: string[]; skipped_reason?: import('./extract.ts').ExtractFailureReason }> {@@ -575,10 +587,14 @@ async function runPipelineWithBody(/** The actual pipeline body — always runs inside a BudgetTracker scope (#4210). */async function runPipelineBodyInner(- input: { turnText: string; isDreamGenerated: boolean; ref?: string; pageSlug?: string },+ input: PipelineInput,ctx: FactsBackstopCtx,abortSignal?: AbortSignal,): Promise<{ inserted: number; duplicate: number; superseded: number; fact_ids: number[]; entity_slugs: string[]; skipped_reason?: import('./extract.ts').ExtractFailureReason }> {+ // Observation time (date-grounding.ts): a dated page's facts default to the+ // page's own date, never the sync/run time. Precedence stays extractor-stated+ // event date > caller validFrom > observation date > now (resolveValidFrom).+ if (!ctx.validFrom && input.observationDate) ctx = { ...ctx, validFrom: new Date(`${input.observationDate.date}T00:00:00.000Z`) };const { extractFactsFromTurnWithOutcome, FactsExtractionError } = await import('./extract.ts');const { resolveEntitySlugWithSource } = await import('../entities/resolve.ts');const { cosineSimilarity } = await import('./classify.ts');@@ -621,6 +637,7 @@ async function runPipelineBodyInner(abortSignal,model: ctx.model,notabilityAdmission,+ observationDate: input.observationDate ?? observationDateFrom(ctx.validFrom ?? null),...(managed ? { embedding: managed.embedding ?? null } : {}),});const outcome = managed ? await withAIInvocationPreflight(async call => {diff --git a/src/core/facts/extract.ts b/src/core/facts/extract.tsindex 2c6d9b42d7..7560798c04 100644--- a/src/core/facts/extract.ts+++ b/src/core/facts/extract.ts@@ -21,6 +21,7 @@* gateway-down errors are absorbed into NULL-embedding rows.*/+import { observationDateLine, observationDateRule, parseExtractedEventDate, type ObservationDate } from '../ai/date-grounding.ts';import { chat, embedOne, isAvailable, getEmbeddingModel } from '../ai/gateway.ts';import { classifyGlobalLlmError } from '../ai/errors.ts';import { stripReasoningBlocks } from '../llm-json.ts';@@ -107,6 +108,26 @@ export async function getFactsExtractionPromptAppendix(return raw.trim();}+/**+ * Extraction prompt variants (`extraction.date_grounding`,+ * `facts.attribution`): both default off until a held-out verdict sets them.+ * `true` / `on` enable; anything else (unset included) is off.+ */+export interface ExtractorVariant {+ /** Resolve relative dates against the observation date; emit valid_from. */+ dateGrounding?: boolean;+ /** Keep assistant-made claims as their own, attributed facts. */+ attribution?: boolean;+}++export async function getExtractorVariant(engine?: BrainEngine): Promise<ExtractorVariant> {+ if (!engine) return {};+ const on = (v: string | null) => v != null && ['true', 'on', '1'].includes(v.trim().toLowerCase());+ const read = (key: string) => Promise.resolve().then(() => engine.getConfig(key)).catch(() => null);+ const [grounding, attribution] = await Promise.all([read('extraction.date_grounding'), read('facts.attribution')]);+ return { dateGrounding: on(grounding), attribution: on(attribution) };+}+/*** #3852: deterministic junk gate for extracted fact text. The LLM extractor —* especially over agent-session transcripts — sometimes emits non-knowledge:@@ -218,6 +239,13 @@ export interface ExtractInput {embedding?: FactEmbeddingSignature | null;/** Cap on number of facts returned per turn. Defaults to 10. */maxFactsPerTurn?: number;+ /**+ * When the turn was written or said (date-grounding.ts). Used only when the+ * date-grounding variant is on; null = unknown (relative dates kept as written).+ */+ observationDate?: ObservationDate | null;+ /** Prompt variant; undefined → read `extraction.date_grounding` / `facts.attribution` from config. */+ variant?: ExtractorVariant;/** Optional pre-embedding admission selector for extracted fact tiers. */notabilityAdmission?: {allowed: readonly FactNotability[];@@ -344,9 +372,29 @@ function renderExtractorSystem(admitsLow: boolean): string {const EXTRACTOR_SYSTEM_ADMITS_LOW = renderExtractorSystem(true);const EXTRACTOR_SYSTEM_SKIPS_LOW = renderExtractorSystem(false);-/** @internal Exported for the prompt-shape test. */-export function buildExtractorSystem(admitsLow: boolean): string {- return admitsLow ? EXTRACTOR_SYSTEM_ADMITS_LOW : EXTRACTOR_SYSTEM_SKIPS_LOW;+/** Date-grounding block: the shared rule plus the per-fact event date. */+const DATE_GROUNDING_BLOCK = [+ '',+ observationDateRule(),+ '- A turn prefixed with its own timestamp ("<speaker> (<ts>): ...") is observed at that timestamp.',+ '- Add "valid_from" to every fact object: "YYYY-MM-DD" when the claim states or implies the specific date it',+ ' became true (resolved against the observation date), else null. Never use the observation date as a guess.',+].join('\n');++/** Speaker block: who asserted a claim, never whether it is true or accepted. */+const ATTRIBUTION_BLOCK = [+ '',+ 'Speakers: a claim the assistant made (a recommendation, answer, plan or research result) is its own fact,',+ 'phrased "Assistant recommended …" / "Assistant said …" — never stated as the user\'s claim, never dropped.',+ 'The user accepting it is a separate fact only when the user explicitly accepts it ("User accepted the',+ 'assistant\'s suggestion to …"); rejected or corrected suggestions produce no user fact. A named third',+ 'party\'s claim keeps the speaker\'s name in the fact text.',+].join('\n');++/** @internal Exported for the prompt-shape test. Both variants off → the historical prompt, byte-identical. */+export function buildExtractorSystem(admitsLow: boolean, variant: ExtractorVariant = {}): string {+ const base = admitsLow ? EXTRACTOR_SYSTEM_ADMITS_LOW : EXTRACTOR_SYSTEM_SKIPS_LOW;+ return base + (variant.dateGrounding ? DATE_GROUNDING_BLOCK : '') + (variant.attribution ? ATTRIBUTION_BLOCK : '');}/** Extractor input ceiling; corpus windows (context/corpus-windows.ts) are cut to fit it. */@@ -394,6 +442,17 @@ const FACTS_EXTRACTION_SCHEMA: Record<string, unknown> = {};const FACTS_RESPONSE_SCHEMA = { name: 'facts_extraction', schema: FACTS_EXTRACTION_SCHEMA };+/** The grounded variant's schema: every fact also carries a nullable valid_from. */+const FACTS_GROUNDED_RESPONSE_SCHEMA = (() => {+ const items = (FACTS_EXTRACTION_SCHEMA.properties as { facts: { items: Record<string, unknown> } }).facts.items;+ const groundedItems = {+ ...items,+ properties: { ...(items.properties as Record<string, unknown>), valid_from: { type: ['string', 'null'] } },+ required: [...(items.required as string[]), 'valid_from'],+ };+ return { name: 'facts_extraction', schema: { ...FACTS_EXTRACTION_SCHEMA, properties: { facts: { type: 'array', items: groundedItems } } } };+})();+export type ExtractFailureReason =| 'chat_unavailable'| 'provider_error'@@ -516,15 +575,18 @@ export async function extractFactsFromTurnWithOutcome(// because those reuse `extractorSystem`. Read AFTER the availability gate —// a chat_unavailable early return must not pay config round-trips (#4298// resolved the model/gate ordering; these reads sit behind it).- const [promptAppendix, junkFilterOn, missingConfidence] = await Promise.all([+ const [promptAppendix, junkFilterOn, missingConfidence, variant] = await Promise.all([getFactsExtractionPromptAppendix(input.engine),isJunkFilterEnabled(input.engine),getMissingConfidence(input.engine),+ input.variant ?? getExtractorVariant(input.engine),]);const extractorSystem = promptAppendix- ? `${buildExtractorSystem(admitsLow)}\n\n${promptAppendix}`- : buildExtractorSystem(admitsLow);- const userContent = `<turn>\n${cleaned}\n</turn>\n\nExtract up to ${cap} facts.${+ ? `${buildExtractorSystem(admitsLow, variant)}\n\n${promptAppendix}`+ : buildExtractorSystem(admitsLow, variant);+ const responseSchema = variant.dateGrounding ? FACTS_GROUNDED_RESPONSE_SCHEMA : FACTS_RESPONSE_SCHEMA;+ const dateLine = variant.dateGrounding ? `${observationDateLine(input.observationDate ?? null)}\n` : '';+ const userContent = `${dateLine}<turn>\n${cleaned}\n</turn>\n\nExtract up to ${cap} facts.${input.entityHints && input.entityHints.length? ` Known entity slugs the user already mentioned: ${input.entityHints.slice(0, ENTITY_HINTS_CAP).join(', ')}.`: ''@@ -541,7 +603,7 @@ export async function extractFactsFromTurnWithOutcome(messages: [{ role: 'user', content: userContent }],maxTokens,abortSignal: input.abortSignal,- responseSchema: FACTS_RESPONSE_SCHEMA,+ responseSchema,});// #2113: never checked pre-fix — a truncated response (stopReason// 'length', e.g. reasoning tokens eating the cap on mandatory-reasoning@@ -559,7 +621,7 @@ export async function extractFactsFromTurnWithOutcome(messages: [{ role: 'user', content: userContent }],maxTokens: effectiveMaxTokens,abortSignal: input.abortSignal,- responseSchema: FACTS_RESPONSE_SCHEMA,+ responseSchema,});if (result.stopReason === 'length') {process.stderr.write(@@ -600,7 +662,7 @@ export async function extractFactsFromTurnWithOutcome(messages: [{ role: 'user', content: userContent }],maxTokens: effectiveMaxTokens,abortSignal: input.abortSignal,- responseSchema: FACTS_RESPONSE_SCHEMA,+ responseSchema,});} catch (err) {if (isAbort(err)) throw err;@@ -719,6 +781,12 @@ export async function extractFactsFromTurnWithOutcome(claim_value: claimValue,claim_unit: claimUnit,claim_period: claimPeriod,+ // Date grounding: a validated extractor-stated event date wins over the+ // caller's fallback (backstop precedence). Malformed / out-of-range+ // dates are dropped, never guessed.+ ...(variant.dateGrounding && parseExtractedEventDate(candidate.valid_from)+ ? { valid_from: parseExtractedEventDate(candidate.valid_from)! }+ : {}),});}@@ -770,6 +838,8 @@ interface RawExtracted {value?: number | null;unit?: string | null;period?: string | null;+ /** Date-grounding variant: the event date the extractor stated (raw string; validated on use). */+ valid_from?: string | null;}/**@@ -854,6 +924,7 @@ function tryArrayShapeDetailed(s: string): ParsedExtractorShape | null {value: (typeof o.value === 'number' && Number.isFinite(o.value)) ? o.value : null,unit: typeof o.unit === 'string' ? o.unit : null,period: typeof o.period === 'string' ? o.period : null,+ valid_from: typeof o.valid_from === 'string' ? o.valid_from : null,});}return { facts: out, invalidCandidates };diff --git a/test/doctor-ranking-extraction.test.ts b/test/doctor-ranking-extraction.test.tsnew file mode 100644index 0000000000..2509698033--- /dev/null+++ b/test/doctor-ranking-extraction.test.ts@@ -0,0 +1,61 @@+/**+ * hub_degree_shape and extraction_date_grounding doctor checks.+ *+ * Protects: the degree-shape check reports the inbound-link percentiles and+ * how many pages the resolved half degree dampens by more than half, never a+ * recommended value; the date-grounding check names the setting and its+ * consumers; both stay informational (ok) and categorized.+ * Seams: none; in-memory PGLite.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { extractionDateGroundingEntry, hubDegreeShapeEntry } from '../src/commands/doctor/checks/ranking-extraction.ts';+import { categorizeCheck } from '../src/core/doctor-categories.ts';+import type { DoctorContext } from '../src/commands/doctor/context.ts';++let engine: PGLiteEngine;+const ctx = () => ({ engine, args: [], progress: { heartbeat() {} } }) as unknown as DoctorContext;++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ await engine.putPage('companies/hub-example', { type: 'company', title: 'Hub', compiled_truth: 'hub' });+ const links = [];+ for (let i = 0; i < 12; i++) {+ await engine.putPage(`meetings/m-${i}`, { type: 'meeting', title: `M${i}`, compiled_truth: 'sync' });+ links.push({ from_slug: `meetings/m-${i}`, to_slug: 'companies/hub-example', link_type: 'mentions_company' });+ }+ await engine.addLinksBatch(links);+}, 60_000);+afterAll(async () => { if (engine) await engine.disconnect(); });++describe('hub_degree_shape', () => {+ test('off: reports the shape and that dampening is off', async () => {+ const [check] = await hubDegreeShapeEntry.run(ctx());+ expect(check.status).toBe('ok');+ expect(check.message).toContain('max 12');+ expect(check.message).toContain('hub dampening is off');+ expect(categorizeCheck('hub_degree_shape')).toBe(categorizeCheck('graph_coverage'));+ });++ test('on: counts pages above the half degree, recommends nothing', async () => {+ await engine.setConfig('search.hub_dampening', '5');+ const [check] = await hubDegreeShapeEntry.run(ctx());+ expect(check.message).toContain('half degree 5: 1 page(s)');+ expect(check.message).not.toMatch(/set .*hub_dampening/);+ await engine.setConfig('search.hub_dampening', 'off');+ });+});++describe('extraction_date_grounding', () => {+ test('reports off by default and lists consumers when on', async () => {+ const [off] = await extractionDateGroundingEntry.run(ctx());+ expect(off.message).toContain('is off');+ await engine.setConfig('extraction.date_grounding', 'true');+ const [on] = await extractionDateGroundingEntry.run(ctx());+ expect(on.message).toContain('propose_takes');+ expect(categorizeCheck('extraction_date_grounding')).toBe(categorizeCheck('graph_coverage'));+ await engine.setConfig('extraction.date_grounding', 'false');+ });+});diff --git a/test/facts/backstop-page-date.test.ts b/test/facts/backstop-page-date.test.tsnew file mode 100644index 0000000000..6afc49e015--- /dev/null+++ b/test/facts/backstop-page-date.test.ts@@ -0,0 +1,78 @@+/**+ * Page-body facts take the page's observation date, never the sync time.+ *+ * Protects: a dated note (meetings/2019-05-01-…) imported today stores its+ * extracted facts at 2019-05-01; an undated page keeps the now() default; an+ * explicit caller validFrom still wins over the page date; and such facts+ * decay as old evidence in hot-memory ranking (effectiveConfidence).+ * Seams: gateway chat transport stub; in-memory PGLite.+ */+import { afterAll, afterEach, beforeAll, describe, expect, test } from 'bun:test';+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';+import { runFactsBackstop, type FactsBackstopCtx } from '../../src/core/facts/backstop.ts';+import { __setChatTransportForTests, resetGateway, type ChatResult } from '../../src/core/ai/gateway.ts';+import { __resetFactsQueueForTests } from '../../src/core/facts/queue.ts';+import { effectiveConfidence } from '../../src/core/facts/decay.ts';++let engine: PGLiteEngine;+beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+});+afterAll(async () => { await engine.disconnect(); });+afterEach(() => { __setChatTransportForTests(null); resetGateway(); __resetFactsQueueForTests(); });++const BODY = 'this is a real meeting note longer than eighty characters for the backstop gate. '.repeat(2);++function chatStub(fact: string) {+ __setChatTransportForTests(async (): Promise<ChatResult> => ({+ text: JSON.stringify({ facts: [{ fact, kind: 'fact', entity: null, confidence: 1, notability: 'high' }] }),+ blocks: [], stopReason: 'end',+ usage: { input_tokens: 0, output_tokens: 0, cache_read_tokens: 0, cache_creation_tokens: 0 },+ model: 'test:stub', providerId: 'test',+ }));+}++const ctx = (overrides: Partial<FactsBackstopCtx> = {}): FactsBackstopCtx =>+ ({ engine, sourceId: 'default', sessionId: null, source: 'mcp:put_page', mode: 'inline', ...overrides });++async function validFromOf(ids: number[]): Promise<Date> {+ const rows = await engine.executeRaw<{ valid_from: Date }>('SELECT valid_from FROM facts WHERE id = $1', [ids[0]]);+ return new Date(rows[0].valid_from);+}++describe('backstop valid_from for page-body facts', () => {+ test('a dated page stores its facts at the page date', async () => {+ chatStub('Acme-example renewed its contract');+ const r = await runFactsBackstop({ slug: 'meetings/2019-05-01-acme-example-renewal', type: 'meeting', compiled_truth: BODY, frontmatter: {} }, ctx());+ expect(r.mode === 'inline' && r.inserted).toBe(1);+ const at = await validFromOf(r.mode === 'inline' ? r.fact_ids : []);+ expect(at.toISOString().slice(0, 10)).toBe('2019-05-01');+ });++ test('an undated page keeps the now() default', async () => {+ chatStub('Beta-example hired a designer');+ const before = Date.now();+ const r = await runFactsBackstop({ slug: 'notes/beta-example-hiring', type: 'note', compiled_truth: BODY, frontmatter: {} }, ctx());+ const at = await validFromOf(r.mode === 'inline' ? r.fact_ids : []);+ expect(at.getTime()).toBeGreaterThanOrEqual(before - 60_000);+ });++ test('a caller validFrom still wins over the page date', async () => {+ chatStub('Gamma-example closed a round');+ const r = await runFactsBackstop({ slug: 'meetings/2019-06-01-gamma-example', type: 'meeting', compiled_truth: BODY, frontmatter: {} },+ ctx({ validFrom: new Date('2020-01-02T00:00:00Z') }));+ const at = await validFromOf(r.mode === 'inline' ? r.fact_ids : []);+ expect(at.toISOString().slice(0, 10)).toBe('2020-01-02');+ });++ test('archive-dated facts rank as old evidence in hot memory', () => {+ const base = { id: 1, fact: 'x', kind: 'event' as const, confidence: 1, expired_at: null, valid_until: null };+ const now = new Date('2026-10-04T00:00:00Z');+ const old = effectiveConfidence({ ...base, valid_from: new Date('2019-05-01T00:00:00Z') } as never, now);+ const fresh = effectiveConfidence({ ...base, valid_from: now } as never, now);+ expect(old).toBeLessThan(0.001);+ expect(fresh).toBe(1);+ });+});diff --git a/test/facts/extract-date-grounding.test.ts b/test/facts/extract-date-grounding.test.tsnew file mode 100644index 0000000000..2d7fe572c0--- /dev/null+++ b/test/facts/extract-date-grounding.test.ts@@ -0,0 +1,107 @@+/**+ * Date-grounded and speaker-attributed fact extraction (prompt variants).+ *+ * Protects: with both variants off the extractor prompt and schema are+ * byte-identical to the historical ones; with date grounding on, the system+ * prompt carries the shared relative-date rule, the user message carries the+ * observation date (or says unknown — never today's date), and a validated+ * extractor-stated event date becomes the fact's valid_from while malformed+ * or out-of-range dates are dropped; the attribution variant adds the speaker+ * rule; the conversation extractor never treats an epoch fallback as an+ * observation date.+ * Seams: gateway chat transport stub (no provider call).+ */+import { afterAll, beforeEach, describe, expect, test } from 'bun:test';+import { configureGateway, resetGateway, __setChatTransportForTests } from '../../src/core/ai/gateway.ts';+import type { ChatOpts, ChatResult } from '../../src/core/ai/gateway.ts';+import { buildExtractorSystem, extractFactsFromTurnWithOutcome } from '../../src/core/facts/extract.ts';+import { observationDateRule } from '../../src/core/ai/date-grounding.ts';+import { segmentObservationDate } from '../../src/commands/extract-conversation-facts.ts';+import type { Page } from '../../src/core/types.ts';++function chatResult(text: string): ChatResult {+ return {+ text, blocks: [{ type: 'text', text }], stopReason: 'end',+ usage: { input_tokens: 1, output_tokens: 1, cache_read_tokens: 0, cache_creation_tokens: 0 },+ model: 'anthropic:claude-sonnet-4-6', providerId: 'anthropic',+ } as ChatResult;+}++beforeEach(() => {+ resetGateway();+ __setChatTransportForTests(null);+ configureGateway({ chat_model: 'anthropic:claude-sonnet-4-6', env: { ANTHROPIC_API_KEY: 'sk-ant-test' } });+});+afterAll(() => {+ __setChatTransportForTests(null);+ configureGateway({ embedding_model: 'openai:text-embedding-3-large', embedding_dimensions: 1536, env: { ...process.env } });+});++async function run(variant: { dateGrounding?: boolean; attribution?: boolean }, reply: unknown, observationDate: { date: string; source: 'filename' } | null = null) {+ const seen: ChatOpts[] = [];+ __setChatTransportForTests(async (opts) => { seen.push(opts); return chatResult(JSON.stringify(reply)); });+ const outcome = await extractFactsFromTurnWithOutcome({+ turnText: 'User (2026-03-10): I flew to Lisbon last week.', source: 'test:grounding', variant, observationDate, embedding: null,+ });+ return { seen, outcome };+}++describe('extractor prompt variants', () => {+ test('both off → the historical prompt, schema and user message', async () => {+ expect(buildExtractorSystem(true, {})).toBe(buildExtractorSystem(true));+ const { seen } = await run({}, { facts: [] }, { date: '2026-03-10', source: 'filename' });+ expect(seen[0].system).toBe(buildExtractorSystem(true));+ expect(JSON.stringify(seen[0].responseSchema)).not.toContain('valid_from');+ expect((seen[0].messages[0].content as string).startsWith('<turn>')).toBe(true);+ });++ test('grounding on → rule in the system prompt, observation date in the user message, valid_from in the schema', async () => {+ const { seen } = await run({ dateGrounding: true }, { facts: [] }, { date: '2026-03-10', source: 'filename' });+ expect(seen[0].system).toContain(observationDateRule());+ expect(seen[0].messages[0].content as string).toStartWith('Observation date: 2026-03-10');+ expect(JSON.stringify(seen[0].responseSchema)).toContain('valid_from');+ });++ test('grounding on with no observation date says unknown, never a guessed date', async () => {+ const { seen } = await run({ dateGrounding: true }, { facts: [] }, null);+ expect(seen[0].messages[0].content as string).toStartWith('Observation date: unknown');+ });++ test('attribution on → the speaker rule; off → absent', async () => {+ expect(buildExtractorSystem(true, { attribution: true })).toContain('Assistant recommended');+ expect(buildExtractorSystem(true)).not.toContain('Assistant recommended');+ });+});++describe('extractor-stated event dates', () => {+ test('a valid date becomes valid_from; malformed and far-future dates are dropped; grounding off ignores the field', async () => {+ const reply = { facts: [+ { fact: 'User flew to Lisbon last week (week of 2026-03-02)', kind: 'event', notability: 'high', valid_from: '2026-03-04' },+ { fact: 'User plans a trip', kind: 'event', notability: 'high', valid_from: 'next spring' },+ { fact: 'User will retire', kind: 'event', notability: 'high', valid_from: '2099-01-01' },+ ] };+ const on = await run({ dateGrounding: true }, reply, { date: '2026-03-10', source: 'filename' });+ expect(on.outcome.ok).toBe(true);+ const facts = on.outcome.ok ? on.outcome.facts : [];+ expect(facts[0].valid_from?.toISOString()).toBe('2026-03-04T00:00:00.000Z');+ expect(facts[1].valid_from).toBeUndefined();+ expect(facts[2].valid_from).toBeUndefined();+ const off = await run({}, reply);+ expect(off.outcome.ok && off.outcome.facts.every(f => f.valid_from === undefined)).toBe(true);+ });+});++describe('segmentObservationDate', () => {+ const page = (fm: Record<string, unknown>, slug = 'conversations/chat-x'): Pick<Page, 'slug' | 'frontmatter' | 'effective_date'> =>+ ({ slug, frontmatter: fm, effective_date: null } as Pick<Page, 'slug' | 'frontmatter' | 'effective_date'>);+ test('an explicit transcript timestamp is the observation date', () => {+ expect(segmentObservationDate(page({}), '2026-03-10T09:00:00Z')).toEqual({ date: '2026-03-10', source: 'caller' });+ });+ test('the epoch fallback is never an observation date; a dated slug still is', () => {+ expect(segmentObservationDate(page({}), '1970-01-01T00:00:00Z')).toBeNull();+ expect(segmentObservationDate(page({}, 'daily/2026-02-01'), '1970-01-01T00:00:00Z')).toEqual({ date: '2026-02-01', source: 'filename' });+ });+ test('a frontmatter date drives the segment date', () => {+ expect(segmentObservationDate(page({ date: '2025-12-24' }), '2025-12-24T00:00:00Z')).toEqual({ date: '2025-12-24', source: 'caller' });+ });+});