Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
think: read in a date frame (current date, page content dates) with optional notes-first reading; eval-only fact-key and time-scope arms
garrytanc019bd5aeb6d
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsvindex c8d143f471..4760586293 100644--- a/scripts/module-size-limits.tsv+++ b/scripts/module-size-limits.tsv@@ -36,7 +36,7 @@ src/core/embedding-migration.ts 1569 ratchet new row: crossed 1500 in v0.46.25.0src/core/github-source.ts 1530 ratchet new row: crossed the 1500 unlisted cap in v0.46.23.0 review fix wave (scope-state gating, client hardening, symlink containment); merged reliability/shared-skills source integration; managed sweep lease wrapper; fix wave 3 lane A: config parser peeled to github-source-config.ts (-47), +account pin wiring and pinned-installation refreshsrc/commands/hook.ts 1903 ratchet cathedral-5 heartbeat extraction offsets part of the BrainBench-seam growth; grown v0.46.26.0 megawave hooks-ipc (#4245); +108 monthly backup check: banner + gated session-start note + detached spawn (backup/status-file readers); +28 ship-review egress hardening: per-harness capture dispatch (capture-spec), memorable gate + receipt + relay block, fail-closed unscanned/newest-guess skips; +79 ambient-writeback WP4: hookStop bank step (gate -> bankWritebackTurn -> IPC flush; gate/bank logic live in core/facts + corpus-segments); +41 adversarial fix wave: wide-tail retry when the 128KB window misses the user turn, by-design heartbeat outcome classes, source-in-name banking; +11 #5413 session-end skips claude-cli self-transcripts; +11 #5701: hook lanes pass allowOversize so a long session reaches the bounded tail readsrc/core/chunkers/code.ts 1588 ratchet new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (decorated-python defs #3821, version-gate + timeout chunker fixes); grown wave-g (#4511): named defs never folded into merged chunks; grown #4669: skip WASM parse for languages without TOP_LEVEL_TYPES; +6 N13-1: CodeChunkMetadata.definesFunction field + merge-guard stamp (predicate lives in def-types.ts)-src/core/config.ts 1838 ratchet +8 #5988: sync.holds/hold_cap/hold_escalate_count/hold_escalate_pct/parser_regression key registration (read by persistence/sync-holds.ts); +3 agent operator wave A4: GBrainConfig.consent file-plane slot + 2 consent.preapprove.* key rows (logic in core/consent.ts); +1 System One v1: decide.* key prefix (validated by ai/decide/config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (spend-controls hint #3703, config-set validation); +3 wave G #3974: sync.include_working_tree key; grown wave-g (#4540 #4494 #4415): extractor caps + intent-pattern config keys; +1 chat-connectors: connectors. config prefix; wave-k: config-table snapshot serving the DB-plane reads (#3980 + #2119 merge); +8: loadConfig hook for ~/.gbrain/.env, loader lives in gbrain-env-file.ts (#3893); +17: litellm/together key-fold slots (#3904 reimpl: two GBrainConfig fields + KNOWN_CONFIG_KEYS rows); +1: link_resolution.cross_source key (#3908); +4 v0.47 gmail-loops: loops.extraction_enabled key; +1: pricing.overrides key (#4633 adoption); +7 #4667 adoption: sync.exclude key registration; +4: eval fix wave keys (quote_verify + 3 rescue knobs); +memorable file-plane key registration (integrations.memorable.enabled + consent-event doc); +33 ambient-writeback: memory.* + brain.audience key registration + GBrainConfig.memory mirror slot (resolvers live in facts/writeback-config.ts); +38 2026-08 wave: retrieval_reflex_volunteer key + env mapping (volunteer-arm kill switch) + E5a registration of the 10 adaptive_return*/autocut*/crag_* search (incl. adversarial batch isEnvDisabled dedup); ambient-writeback (master merge): facts/writeback-config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave; prior growth: sync/intent/chat-connectors/litellm/pricing/loops key folds; +34: #4702 content_sanity.disabled_patterns (type + DB-plane parse/merge + key registration); composition true-up (fix-wave multi-train) | merged v0.48.1.0: master #4788 writeback keys + wave #4702/#4748 keys; master: | merged v0.48.1.0 true-up; ranker wave v0.48.4.0: +4 KNOWN_CONFIG_KEYS rows (+8); +5 #4895: CWD_DOTENV_FILES gains the per-NODE_ENV .local variants Bun auto-loads; +2 #5003: sync.include_hidden key registration; +57 #4605: search.* registry reconciled to the keys mode.ts reads (+20 knob rows, +4 direct-read singletons) + GBrainConfig.search slot + adaptive_return* DB-plane merge; +2 pre-landing review: fts.reindex_in_progress key registration (#4795 marker escape hatch); +4 #4987: auto_timeline key registration (the documented off switch was rejected as unknown); lowered to 1793: GHSA wave v0.50.5.0 moved CWD_DOTENV_FILES + dotenvValuesForKey into core/env-trust.ts (-49, re-exported); re-summed to the merged line count after merging master v0.50.2.0 (#5122) with the v0.50.5.0 security wave; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +1 at the merge; evidence delivery: 5 registered config keys + comment (+7); +2 #5691: embedding_query_prefix key registration; evidence delivery auto v2: search.return_budget_conversation key row (+1); +1 #5836: facts.entity_inference key row; +6 #5824: search.vector_legacy_guard key row + GBrainConfig.search slot + DB-plane merge; +3 wave 8 lane D1 #5885: takes.auto_embed key row; +3 #5232: GBrainConfig.persistence.write_wait_ms file-plane slot + key row (resolver in persistence/write-wait.ts); +2 F4b: planner.* and import.analyze_every_pages keys; +3 cat40 cost wave C1 (garrytan/gbrain-evals#57 follow-ups): mcp.result_rows GBrainConfig slot + key row (resolver in mcp/result-rows.ts); v0.60.46.0 merge: both waves' +3 compose (1824 + 3 = 1827 measured); +4 #5984: sync.bulk, sync.bulk_size, sync.bulk_max_txn_ms known keys; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (1838 measured)+src/core/config.ts 1839 ratchet +8 #5988: sync.holds/hold_cap/hold_escalate_count/hold_escalate_pct/parser_regression key registration (read by persistence/sync-holds.ts); +3 agent operator wave A4: GBrainConfig.consent file-plane slot + 2 consent.preapprove.* key rows (logic in core/consent.ts); +1 System One v1: decide.* key prefix (validated by ai/decide/config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (spend-controls hint #3703, config-set validation); +3 wave G #3974: sync.include_working_tree key; grown wave-g (#4540 #4494 #4415): extractor caps + intent-pattern config keys; +1 chat-connectors: connectors. config prefix; wave-k: config-table snapshot serving the DB-plane reads (#3980 + #2119 merge); +8: loadConfig hook for ~/.gbrain/.env, loader lives in gbrain-env-file.ts (#3893); +17: litellm/together key-fold slots (#3904 reimpl: two GBrainConfig fields + KNOWN_CONFIG_KEYS rows); +1: link_resolution.cross_source key (#3908); +4 v0.47 gmail-loops: loops.extraction_enabled key; +1: pricing.overrides key (#4633 adoption); +7 #4667 adoption: sync.exclude key registration; +4: eval fix wave keys (quote_verify + 3 rescue knobs); +memorable file-plane key registration (integrations.memorable.enabled + consent-event doc); +33 ambient-writeback: memory.* + brain.audience key registration + GBrainConfig.memory mirror slot (resolvers live in facts/writeback-config.ts); +38 2026-08 wave: retrieval_reflex_volunteer key + env mapping (volunteer-arm kill switch) + E5a registration of the 10 adaptive_return*/autocut*/crag_* search (incl. adversarial batch isEnvDisabled dedup); ambient-writeback (master merge): facts/writeback-config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave; prior growth: sync/intent/chat-connectors/litellm/pricing/loops key folds; +34: #4702 content_sanity.disabled_patterns (type + DB-plane parse/merge + key registration); composition true-up (fix-wave multi-train) | merged v0.48.1.0: master #4788 writeback keys + wave #4702/#4748 keys; master: | merged v0.48.1.0 true-up; ranker wave v0.48.4.0: +4 KNOWN_CONFIG_KEYS rows (+8); +5 #4895: CWD_DOTENV_FILES gains the per-NODE_ENV .local variants Bun auto-loads; +2 #5003: sync.include_hidden key registration; +57 #4605: search.* registry reconciled to the keys mode.ts reads (+20 knob rows, +4 direct-read singletons) + GBrainConfig.search slot + adaptive_return* DB-plane merge; +2 pre-landing review: fts.reindex_in_progress key registration (#4795 marker escape hatch); +4 #4987: auto_timeline key registration (the documented off switch was rejected as unknown); lowered to 1793: GHSA wave v0.50.5.0 moved CWD_DOTENV_FILES + dotenvValuesForKey into core/env-trust.ts (-49, re-exported); re-summed to the merged line count after merging master v0.50.2.0 (#5122) with the v0.50.5.0 security wave; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +1 at the merge; evidence delivery: 5 registered config keys + comment (+7); +2 #5691: embedding_query_prefix key registration; evidence delivery auto v2: search.return_budget_conversation key row (+1); +1 #5836: facts.entity_inference key row; +6 #5824: search.vector_legacy_guard key row + GBrainConfig.search slot + DB-plane merge; +3 wave 8 lane D1 #5885: takes.auto_embed key row; +3 #5232: GBrainConfig.persistence.write_wait_ms file-plane slot + key row (resolver in persistence/write-wait.ts); +2 F4b: planner.* and import.analyze_every_pages keys; +3 cat40 cost wave C1 (garrytan/gbrain-evals#57 follow-ups): mcp.result_rows GBrainConfig slot + key row (resolver in mcp/result-rows.ts); v0.60.46.0 merge: both waves' +3 compose (1824 + 3 = 1827 measured); +4 #5984: sync.bulk, sync.bulk_size, sync.bulk_max_txn_ms known keys; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (1838 measured); +1 P6: think.reading_notes key registrationsrc/core/bootstrap/harness.ts 2711 ratchet +29 live-PGLite-serve lane: LIVE_SERVE refusal ahead of source resolution + unpinned --token hooks (CI e2e fix); +46 wave review: resolveHookSource dep (serve-parity resolver + federated grant), --source shape validation, loud SOURCE_UNRESOLVED instead of a silent 'default'; +10: #4574 parseCodexBlockBearer http_headers shape + legacy bearer_token fallback; +4 at megawave/wave-k merge; +codex hooks lane: step-7 codex hooks.json + config.toml trust pair, removeHarness arm; +234 ambient-writeback WP3: kind:'instructions' targets (plan/apply/converge-off/remove/status probes, OV-A4 override pre-check) — splice/render mechanics live in instructions-block.ts; +59 adversarial fix wave: registrar-mode block suppression, converge-failure receipt tracking, MCP-confirmed guard before block install; +26 round-3 fixes: codex-lane MCP-confirmed guard + smoke-rollback block strip; master: | merged v0.48.1.0 true-up; +41 #4897 resolveImplicitSource dep + defaultResolveImplicitSource: hooks/token/receipt bind to the serve's implicit default source when --source is omitted; +23 #4586 statusHarness live claude-code mcp verdict (URL mismatch or same-scope non-HTTP registration reads failed, receipt untouched); shared-skills integration on company-ingestion base; +18 #5671: logAmbientPostureNotes helper (registrar note moved out of applyHarness + pre-consent warning when an explicit private facts default meets the HTTP harness; text shared with doctor in facts/writeback-config.ts); +24 #5893: rotation grant carry wiring and its rotationCarry/withheldOperationsNote helpers (carry rules live in token-mint.ts carryLegacyGrant); +6 #5878: --refresh-skills flag and status epoch line (refresh logic lives in harness-skills.ts); +7 #4618 seat: HarnessFlags.seat field, --seat/--no-seat parse via hooks.ts parseSeatFlags, GBRAIN_SEAT in the hook envsrc/core/oauth-provider.ts 1236 ratchet new row: crossed the 1500 unlisted cap absorbing #3819 (DCR 400 invalid_client_metadata + scope filtering + custom-scheme redirect_uris + pseudo-scheme guard); merged v0.49: transactional grant enforcement shared with hosted grant policies; +1 #5222 resourceUrl optionsrc/core/ops/pages.ts 663 ratchet crossed the unlisted 1500 cap in the fix wave: pack-vocabulary enforcement on capture (#4721) + get_page alias follow (#4275) landed together; next growth should peel a pages-ops submodule; +3: alias hop reads the canonical in the owning source (ship-review); +5: explicit source_id liveness check in get_page/list_pages (#4620); +3: #4857 total-order slug sort + list_pages source_id parse; +5: #4620 explicit removed-source id fails loudly; master integration: +4: authenticated delegated private-write boundary and auto-link suppression; #5105: canonical page mutations peeled into persistence modules; +2 v0.50.5.0 purge parameter and shared preflight call; preparation composes through the persistence modules; +7: source-qualified deep-research fetch authorization and ambiguity refusal (codec lives in deep-research-id.ts); +1 #5567: remote get_page keeps materialized markers; +1 #5622: trusted local capture file parameter; +5 #5709: get_page include_timeline_entries (rows via get_timeline's read policy); +8 GBRA-36 security wave: required outputRedaction policy on each pages op; +1 #5154: list_pages passes listColumnsOnly; +17 #5641: list_pages exposes the updated_after_slug keyset cursor and updated_at_iso; +8 agent operator wave A2: every op declares mutating + idempotent (tags only); +7 F3b (#5954): list_pages pagination meta + listing_truncated notice for MCP callers (logic in ops/list-pages-pagination.ts); +4 #5988: get_page file_held (one indexed hold lookup; logic in persistence/held-reads.ts)diff --git a/src/commands/eval-longmemeval.ts b/src/commands/eval-longmemeval.tsindex 45493418b3..8b6998404e 100644--- a/src/commands/eval-longmemeval.ts+++ b/src/commands/eval-longmemeval.ts@@ -129,6 +129,7 @@ import {} from '../core/search/mode.ts';import { buildCaptureExtras } from '../eval/longmemeval/capture.ts';import * as decideLane from '../eval/longmemeval/decide-lane.ts';+import * as retrievalArms from '../eval/longmemeval/retrieval-arms.ts';import { resolveModel } from '../core/model-config.ts';import type { ThinkLLMClient } from '../core/think/index.ts';import { createProgress } from '../core/progress.ts';@@ -212,7 +213,7 @@ interface ParsedArgs {judgeConcurrency: number;allowIncompleteJudgments: boolean;/** System One arm (`--decide*`, src/eval/decide-eval-flags.ts) and the eval-only `--eval-pool-depth`. */- decide: decideLane.DecideEvalOptions; evalPoolDepth?: number;+ decide: decideLane.DecideEvalOptions; evalPoolDepth?: number; arms: retrievalArms.RetrievalArmOptions;}interface LmeFlag {@@ -392,6 +393,7 @@ const LME_FLAGS: LmeFlag[] = ['--judge --resume-from FILE until all three are 0.'],apply: (o) => { o.allowIncompleteJudgments = true; } },...decideLane.LME_DECIDE_FLAGS,+ ...retrievalArms.LME_RETRIEVAL_ARM_FLAGS,];function parseArgs(args: string[]): ParsedArgs {@@ -416,7 +418,7 @@ function parseArgs(args: string[]): ParsedArgs {yes: false,judgeConcurrency: 1,allowIncompleteJudgments: false,- decide: decideLane.newDecideEvalOptions(),+ decide: decideLane.newDecideEvalOptions(), arms: retrievalArms.newRetrievalArmOptions(),};const byName = new Map(LME_FLAGS.map(f => [f.name, f]));for (let i = 0; i < args.length; i++) {@@ -550,6 +552,7 @@ interface RunContext {*/embedTxn: <T>(fn: () => Promise<T>) => Promise<T>;decide: decideLane.DecideEvalRun | null;+ factKeys: { arm: retrievalArms.FactKeyArm; spend: retrievalArms.FactKeySpend } | null;}interface QuestionOutcome {@@ -593,6 +596,7 @@ function resolvePins(opts: ParsedArgs, runOpts: RunOpts, trajectoryEnabled: booltrajectory: trajectoryEnabled,...(searchPins ? { search_pins: searchPins } : {}),...(opts.evalPoolDepth ? { eval_pool_depth: opts.evalPoolDepth } : {}), ...(decide ? { decide: decide.runConfig } : {}),+ ...retrievalArms.armPins(opts.arms),};return { pins, knobs };}@@ -1117,6 +1121,7 @@ export async function runEvalLongMemEval(args: string[], runOpts: RunOpts = {}):const ctx: RunContext = {opts, model, readerConfig, readerHash, client, trajectoryEnabled, extractorClient, extractorModel, decide: decideRun,+ factKeys: await retrievalArms.resolveFactKeyArm(opts.arms, extractorClient),expandFn: runOpts.expandFn ?? expandQuery,replay,retrievalConfigHash: retrievalHash,@@ -1391,6 +1396,7 @@ async function runOneQuestion(const aliasMap: AliasMap = makeAliasMap();let meta: HybridSearchMeta | undefined;+ const extra0: Record<string, unknown> = {};const decideBefore = await decideLane.lmeSpendBefore(engine, ctx.decide);let pool: SearchResult[] | undefined;let preRerank: SearchResult[] | undefined;@@ -1416,9 +1422,10 @@ async function runOneQuestion(});}}+ if (ctx.factKeys) Object.assign(extra0, { fact_keys: await retrievalArms.applyFactKeyArm(engine, adapterPages, ctx.factKeys.arm, ctx.factKeys.spend) });if (opts.keywordOnly) return engine.searchKeyword(q.question, { limit: opts.topK });const searchOpts: HybridSearchOpts = {- limit: opts.topK,+ limit: opts.arms.timeScope ? Math.max(opts.topK, opts.arms.timeScopePool) : opts.topK,// Per-call wins over the bundle: expansion fires ONLY with --expansion.expansion: opts.expansion,...(expandFn ? { expandFn } : {}),@@ -1428,7 +1435,11 @@ async function runOneQuestion(? { onRerankPool: (p: readonly SearchResult[], pre?: readonly SearchResult[]) => { pool = [...p]; preRerank = pre ? [...pre] : undefined; } }: {}),};- return hybridSearch(engine, q.question, searchOpts);+ const found = await hybridSearch(engine, q.question, searchOpts);+ if (!opts.arms.timeScope) return found;+ const scoped = retrievalArms.applyTimeScopeArm(found, q, pageMeta, opts.arms.timeScope, opts.topK);+ Object.assign(extra0, retrievalArms.timeScopeRowExtras(scoped.row, slugToRaw, gold, opts.topK));+ return scoped.results;});// Trajectory routing for temporal / knowledge_update intents. Skips for@@ -1487,6 +1498,7 @@ async function runOneQuestion(searchMeta.reranked = results.some(r => Number.isFinite(r.rerank_score)) && !rerankerSkipped;const extra: Record<string, unknown> = {+ ...extra0,retrieval_config_hash: ctx.retrievalConfigHash,...readerFields,search_meta: searchMeta,diff --git a/src/commands/think.ts b/src/commands/think.tsindex 85ddc25ca2..83350f6c64 100644--- a/src/commands/think.ts+++ b/src/commands/think.ts@@ -62,6 +62,12 @@ Options:or archived source is a hard error (exit 1).--since YYYY-MM-DD Start of temporal window--until YYYY-MM-DD End of temporal window+ --reference-date YYYY-MM-DD+ Date the question's relative time words ("last month")+ resolve against (default: today in brain.timezone)+ --reading-notes on|off|auto+ Notes-first reading for this call (default:+ think.reading_notes config); notes print with --json only--with-calibration Inject the active calibration profile (anti-bias rewrite)--calibration-holder <h> Holder whose calibration profile to use (default: self)--json Output as JSON@@ -83,7 +89,7 @@ prints what would have been the input (exit 0).// #4508: --source and --calibration-holder were MISSING here — the flag and// its value joined the positional question, so `think "q" --source X`// echoed `# --source X q` and silently ignored the scope.- const flagNames = ['--anchor', '--rounds', '--model', '--since', '--until', '--source', '--calibration-holder'];+ const flagNames = ['--anchor', '--rounds', '--model', '--since', '--until', '--source', '--calibration-holder', '--reference-date', '--reading-notes'];const positional: string[] = [];for (let i = 0; i < args.length; i++) {const a = args[i];@@ -106,6 +112,13 @@ prints what would have been the input (exit 0).const model = flagValue(args, '--model');const since = flagValue(args, '--since');const until = flagValue(args, '--until');+ const referenceDate = flagValue(args, '--reference-date');+ const readingNotesFlag = flagValue(args, '--reading-notes');+ if (readingNotesFlag !== undefined && !['on', 'off', 'auto'].includes(readingNotesFlag)) {+ console.error(`--reading-notes must be on, off or auto (got "${readingNotesFlag}").`);+ process.exit(1);+ }+ const readingNotes = readingNotesFlag as 'on' | 'off' | 'auto' | undefined;// v0.36.1.0 (E1, D22) — anti-bias rewrite mode. Off by default (no// regression for existing think users). When on, the active calibration// profile gets injected per D22 placement (after retrieval, before question).@@ -149,6 +162,8 @@ prints what would have been the input (exit 0).}const raw = await callRemoteTool(cfg!, 'think', {question, anchor, rounds, model, since, until,+ ...(referenceDate ? { reference_date: referenceDate } : {}),+ ...(readingNotes ? { reading_notes: readingNotes } : {}),// save/take intentionally NOT forwarded — server would ignore them;// we surface the intent above so users know what they lose.}, { timeoutMs: 180_000 });@@ -184,6 +199,8 @@ prints what would have been the input (exit 0).}result = await runThink(engine, {question, anchor, rounds, save, take, model, since, until,+ ...(referenceDate ? { referenceDate } : {}),+ ...(readingNotes ? { readingNotes } : {}),// Fail-closed trust: local CLI must say so explicitly, or trajectory// injection degrades to visibility='world' rows.remote: false,diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.tsindex 742267af39..6ef12e7aa2 100644--- a/src/core/cli-flag-registry.generated.ts+++ b/src/core/cli-flag-registry.generated.ts@@ -54,7 +54,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'engine': ['--apply-rewrites', '--brain', '--break-lock', '--db-url', '--help', '--http', '--json', '--path', '--prefer-postgres', '--probe', '--source', '--supabase', '--url', '--yes'],'enrich': ['--accept-pending', '--access', '--add', '--allowed-operations', '--asof', '--background', '--bound-slug-prefixes', '--brain', '--client', '--concurrency', '--confirm-destructive', '--date', '--dated-since', '--days', '--dry-run', '--embedding-dimensions', '--embedding-model', '--entities', '--explain', '--federated-read', '--follow', '--force', '--full', '--fuzzy', '--help', '--http', '--id', '--include-deleted', '--input', '--json', '--kind', '--limit', '--max-cost', '--max-cost-usd', '--max-runtime', '--max-usd', '--min-context', '--model', '--multimodal', '--no-accept-pending', '--no-autopilot-install', '--order', '--output', '--page', '--params', '--path', '--phase', '--progress-interval', '--progress-json', '--quiet', '--rate', '--recent', '--reenrich-after', '--refresh-operations', '--resume', '--scopes', '--session', '--since', '--slugs', '--source', '--source-id', '--sources', '--stale', '--status', '--surface', '--thin', '--thin-threshold', '--timeout', '--to', '--types', '--url', '--wait', '--workers', '--yes'],'errors': ['--brain', '--changed', '--help', '--json', '--source'],- 'eval': ['--ab-relational', '--accept-pending', '--against', '--allow-incomplete-judgments', '--allow-mixed-run-config', '--allow-regression', '--asof', '--autocut', '--background', '--baseline', '--batch', '--brain', '--budget-usd', '--budget-usd-answer', '--budget-usd-retrieval', '--by-type', '--by-type-floor', '--by-type-floor-metric', '--candidate', '--capture-pool', '--committed-baseline', '--compare', '--compare-limit', '--concurrent', '--config-a', '--config-b', '--corpus', '--cycles', '--days', '--decide', '--decide-calibration', '--decide-dataset', '--decide-force-on', '--decide-provider', '--decide-threshold', '--dedup-cosine', '--dedup-max-per-page', '--dedup-type-ratio', '--dimensions', '--distance-min', '--draws', '--embed-cache', '--embedder', '--embedding-dimensions', '--embedding-model', '--eval-pool-depth', '--expand', '--expansion', '--expansion-replay', '--expansion-variant-budget', '--explain', '--fixtures', '--follow', '--force-rechunk', '--format', '--from-capture', '--from-db', '--gold', '--grounding-min', '--harness', '--help', '--include-abstention', '--include-holdout', '--input', '--json', '--judge', '--judge-concurrency', '--judge-model', '--justification', '--k', '--keyword-only', '--limit', '--llm', '--max-pair-chars', '--max-tokens', '--max-usd', '--mcp-only', '--md', '--metric', '--min-recall', '--mode', '--model', '--models', '--modes', '--name-only', '--no-accept-pending', '--no-cache', '--no-embed-cache', '--no-expand', '--no-llm', '--no-trajectory', '--older-than', '--out', '--output', '--output-dir', '--parallel', '--parity-baseline', '--progress-interval', '--progress-json', '--qrels', '--queries-file', '--query', '--question-ids', '--questions', '--quiet', '--reader-max-tokens', '--reader-mode', '--receipt-dir', '--record', '--refresh-cache', '--reranker', '--resume-from', '--retrieval-only', '--rrf-k', '--rubric-version', '--runs', '--sample', '--sampling', '--save', '--search-pin', '--seed', '--severity', '--short', '--show-toplevel', '--since', '--skip-replay', '--slot', '--slot-a-model', '--slot-b-model', '--slot-c-model', '--slug', '--slug-prefix', '--source', '--stale', '--status', '--strategy', '--suite', '--suites', '--supabase', '--task', '--threshold', '--threshold-expected-top1', '--threshold-first-relevant-hit', '--threshold-jaccard', '--threshold-latency-multiplier', '--threshold-recall-at-k', '--threshold-top1', '--timeout', '--tool', '--top-k', '--top-regressions', '--until', '--update-baseline', '--usefulness-min', '--vectors', '--verbose', '--verify', '--wait', '--with-code-intel', '--yes'],+ 'eval': ['--ab-relational', '--accept-pending', '--against', '--allow-incomplete-judgments', '--allow-mixed-run-config', '--allow-regression', '--asof', '--autocut', '--background', '--baseline', '--batch', '--brain', '--budget-usd', '--budget-usd-answer', '--budget-usd-retrieval', '--by-type', '--by-type-floor', '--by-type-floor-metric', '--candidate', '--capture-pool', '--committed-baseline', '--compare', '--compare-limit', '--concurrent', '--config-a', '--config-b', '--corpus', '--cycles', '--days', '--decide', '--decide-calibration', '--decide-dataset', '--decide-force-on', '--decide-provider', '--decide-threshold', '--dedup-cosine', '--dedup-max-per-page', '--dedup-type-ratio', '--dimensions', '--distance-min', '--draws', '--embed-cache', '--embedder', '--embedding-dimensions', '--embedding-model', '--eval-pool-depth', '--expand', '--expansion', '--expansion-replay', '--expansion-variant-budget', '--explain', '--fact-extractor', '--fact-keys', '--fact-keys-max-usd', '--fact-keys-model', '--fixtures', '--follow', '--force-rechunk', '--format', '--from-capture', '--from-db', '--gold', '--grounding-min', '--harness', '--help', '--include-abstention', '--include-holdout', '--input', '--json', '--judge', '--judge-concurrency', '--judge-model', '--justification', '--k', '--keyword-only', '--limit', '--llm', '--max-pair-chars', '--max-tokens', '--max-usd', '--mcp-only', '--md', '--metric', '--min-recall', '--mode', '--model', '--models', '--modes', '--name-only', '--no-accept-pending', '--no-cache', '--no-embed-cache', '--no-expand', '--no-llm', '--no-trajectory', '--older-than', '--out', '--output', '--output-dir', '--parallel', '--parity-baseline', '--progress-interval', '--progress-json', '--qrels', '--queries-file', '--query', '--question-ids', '--questions', '--quiet', '--reader-max-tokens', '--reader-mode', '--receipt-dir', '--record', '--refresh-cache', '--reranker', '--resume-from', '--retrieval-only', '--rrf-k', '--rubric-version', '--runs', '--sample', '--sampling', '--save', '--search-pin', '--seed', '--severity', '--short', '--show-toplevel', '--since', '--skip-replay', '--slot', '--slot-a-model', '--slot-b-model', '--slot-c-model', '--slug', '--slug-prefix', '--source', '--stale', '--status', '--strategy', '--suite', '--suites', '--supabase', '--task', '--threshold', '--threshold-expected-top1', '--threshold-first-relevant-hit', '--threshold-jaccard', '--threshold-latency-multiplier', '--threshold-recall-at-k', '--threshold-top1', '--time-scope', '--time-scope-pool', '--timeout', '--tool', '--top-k', '--top-regressions', '--until', '--update-baseline', '--usefulness-min', '--vectors', '--verbose', '--verify', '--wait', '--with-code-intel', '--yes'],'export': ['--accept-pending', '--background', '--brain', '--dir', '--explain', '--fix', '--follow', '--help', '--json', '--no-accept-pending', '--progress-interval', '--progress-json', '--quiet', '--repo', '--restore-only', '--slug-prefix', '--source', '--timeout', '--type', '--wait'],'extract': ['--accept-pending', '--admin-intent', '--after-slug', '--apply-preview', '--background', '--backup-verified', '--brain', '--break-lock', '--by-mention', '--catch-up', '--checkpoint', '--concurrency', '--confirm', '--db-url', '--dir', '--dry-run', '--expected-epoch', '--expected-state', '--explain', '--follow', '--from-meetings', '--help', '--http', '--include-frontmatter', '--infer-dates', '--json', '--kind', '--limit', '--manifest', '--ner', '--no-accept-pending', '--pack', '--path', '--progress-interval', '--progress-json', '--prune-orphans', '--quiet', '--rebuild', '--repair-attendance', '--self-transfer', '--since', '--source', '--source-id', '--stale', '--timeout', '--type', '--verbose', '--wait', '--workers', '--yes'],'extract-conversation-facts': ['--accept-pending', '--admin-intent', '--background', '--brain', '--concurrency', '--confirm-destructive', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--expected-epoch', '--expected-state', '--explain', '--follow', '--force', '--help', '--input', '--json', '--limit', '--manifest', '--max-cost', '--max-cost-usd', '--max-runtime', '--no-accept-pending', '--no-embedding', '--output', '--override-disabled', '--path', '--progress-interval', '--progress-json', '--quiet', '--rate', '--segment-limit', '--self-transfer', '--since', '--sleep', '--slug', '--source', '--source-id', '--stale', '--status', '--supabase', '--timeout', '--to', '--types', '--url', '--wait', '--workers', '--yes'],@@ -124,7 +124,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'sweep': ['--accept-pending', '--background', '--batch-limit', '--brain', '--budget-ms', '--delete-brain', '--explain', '--follow', '--help', '--home', '--json', '--no-accept-pending', '--no-delegate', '--once', '--progress-interval', '--progress-json', '--quiet', '--source', '--timeout', '--wait'],'sync': ['--abbrev-ref', '--abort', '--accept-pending', '--account', '--adopt-columns', '--adopt-permissions', '--all', '--allow-empty', '--apply', '--apply-rewrites', '--auto', '--background', '--batch-size', '--brain', '--branch', '--break-lock', '--by-mention', '--cached', '--catch-up', '--concurrency', '--confirm-destructive', '--content-audit', '--count', '--db-url', '--delete-brain', '--depth', '--detach', '--diff-filter', '--dim', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--exclude', '--exclude-standard', '--expect', '--explain', '--facts', '--fast', '--ff-only', '--filters', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from-meetings', '--full', '--full-history', '--git-dir', '--git-path', '--hard-deadline', '--harness', '--help', '--home', '--http', '--id', '--images', '--include-ambiguous', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--include-repairs', '--index-audit', '--infer-dates', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--json', '--kind', '--lang', '--link-source', '--link-type', '--locks', '--log-noop', '--markdown', '--max-age', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-sources', '--max-usd', '--migrate-legacy', '--migrate-only', '--missing-path', '--multimodal', '--name-only', '--name-status', '--ner', '--no-accept-pending', '--no-auto-embed', '--no-autopilot-install', '--no-bulk', '--no-delegate', '--no-embed', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-pull', '--no-recurse-submodules', '--no-renames', '--no-schema-pack', '--no-verify', '--older-than', '--only', '--operations', '--others', '--overwrite', '--pace', '--pace-max-concurrency', '--pack', '--parallel', '--params', '--path', '--path-format', '--pglite', '--phase', '--pid-file', '--porcelain', '--prefer-postgres', '--preview', '--priority', '--probe', '--probe-pglite', '--progress-interval', '--progress-json', '--prune-orphans', '--query', '--queue', '--quiet', '--reauth', '--rebase', '--rebuild', '--refresh', '--regenerate', '--remediate', '--remediation-plan', '--remove', '--replace', '--repo', '--request-id', '--reset', '--reset-checkpoint', '--restore-only', '--resume', '--retry-failed', '--retry-held', '--scope', '--scopes', '--serial', '--short', '--show-current', '--show-toplevel', '--since', '--skills-dir', '--skip-failed', '--slot', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--stale', '--status', '--stdin', '--strategy', '--supabase', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--timeout', '--to', '--token', '--top-k', '--type', '--url', '--verbose', '--verify', '--version', '--wait', '--watch', '--window', '--workers', '--working-tree', '--yes'],'takes': ['--accept', '--batch-size', '--brain', '--bucket-size', '--by', '--claim', '--dim', '--dir', '--domain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--evidence', '--expected-revision', '--expired', '--force', '--from-pages', '--help', '--holder', '--include-covered', '--json', '--kind', '--limit', '--max-pages', '--no-embed', '--no-embedding', '--offset', '--outcome', '--path', '--quality', '--reject', '--request-id', '--row', '--semantic', '--since', '--sort', '--source', '--source-id', '--stale', '--status', '--supabase', '--to', '--unit', '--until', '--value', '--weight', '--who', '--yes'],- 'think': ['--anchor', '--brain', '--calibration-holder', '--help', '--json', '--mcp-only', '--model', '--only', '--rounds', '--save', '--since', '--source', '--take', '--until', '--with-calibration'],+ 'think': ['--anchor', '--brain', '--calibration-holder', '--help', '--json', '--mcp-only', '--model', '--only', '--reading-notes', '--reference-date', '--rounds', '--save', '--since', '--source', '--take', '--until', '--with-calibration'],'transcripts': ['--accept-pending', '--all', '--all-discovery', '--background', '--brain', '--days', '--dry-run', '--embed', '--explain', '--facts', '--follow', '--format', '--full', '--help', '--include-self', '--json', '--limit', '--max-bytes', '--max-cost-usd', '--no-accept-pending', '--progress-interval', '--progress-json', '--quiet', '--since', '--source', '--source-id', '--timeout', '--wait'],'upgrade': ['--acknowledge-no-backup', '--admin-intent', '--all', '--apply', '--apply-clean-hunks', '--backup-confirmed', '--brain', '--changed', '--check', '--concurrency', '--confirm-quiesced', '--content-root', '--cost-estimate', '--embedding-dimensions', '--embedding-model', '--expected-epoch', '--expected-state', '--export-db-only', '--export-source', '--ff-only', '--force', '--force-all', '--force-orchestrator', '--force-retry', '--force-schema', '--format', '--help', '--host-dir', '--inject-bootstrap', '--inline', '--install', '--interval', '--json', '--limit', '--list', '--manifest', '--markdown', '--max-rss', '--migrate-only', '--migration', '--mode', '--multimodal', '--name-only', '--no-autopilot-install', '--no-bun-floor-check', '--no-embed', '--no-inject', '--no-worker', '--non-interactive', '--now', '--once', '--only', '--path', '--pause', '--quiet', '--reason', '--remediation-plan', '--repo', '--require-db', '--resume', '--self-transfer', '--skills-dir', '--skip-verify', '--source', '--stale', '--status', '--swap-only', '--target', '--uninstall', '--user', '--vectors', '--verify', '--version', '--workers', '--yes'],'waiting': ['--all', '--as-of', '--brain', '--fail-fast', '--help', '--json', '--note', '--source', '--stale-ok', '--status', '--tools-json', '--top', '--type'],diff --git a/src/core/config.ts b/src/core/config.tsindex 60c1fb60d9..cb0565ba14 100644--- a/src/core/config.ts+++ b/src/core/config.ts@@ -1363,6 +1363,7 @@ export const KNOWN_CONFIG_KEYS: readonly string[] = ['search.return_budget_conversation','search.return_budget_max_remote','think.return_unit',+ 'think.reading_notes',// Models tier system (v0.31.12)'models.default','models.tier.utility',diff --git a/src/core/event-dates.ts b/src/core/event-dates.tsnew file mode 100644index 0000000000..19c9974203--- /dev/null+++ b/src/core/event-dates.ts@@ -0,0 +1,41 @@+/**+ * Dates a page's content mentions, resolved deterministically (no LLM).+ *+ * Three times are kept apart, matching the facts pipeline's vocabulary:+ * the observation date (when the text was written or said), the dates the+ * text mentions (when the events it describes happened), and the recorded+ * time (when GBrain stored the row, never used here). Relative phrases+ * ("yesterday", "two weeks ago") resolve only against a known observation+ * date; without one, only absolute dates are extracted.+ *+ * Code fences, inline code and URLs are skipped, so version strings and+ * timestamps in code do not become event dates.+ */++import { findTimeMentions, type DayRange } from './temporal-grammar.ts';++export interface EventDate extends DayRange {+ origin: 'observation' | 'mention' | 'relative';+ surface: string;+ qualified: boolean;+}++const PLACEHOLDER_DAY = '1970-01-01';++function stripCodeAndUrls(text: string): string {+ return text+ .replace(/```[\s\S]*?```/g, ' ')+ .replace(/`[^`\n]*`/g, ' ')+ .replace(/\bhttps?:\/\/\S+/g, ' ');+}++export function extractEventDates(text: string, observationDate: string | null): EventDate[] {+ const clean = stripCodeAndUrls(text);+ const out: EventDate[] = [];+ if (observationDate) out.push({ start: observationDate, end: observationDate, origin: 'observation', surface: '', qualified: false });+ for (const m of findTimeMentions(clean, observationDate ?? PLACEHOLDER_DAY, 'past')) {+ if (m.kind === 'relative' && !observationDate) continue;+ out.push({ start: m.start, end: m.end, origin: m.kind === 'absolute' ? 'mention' : 'relative', surface: m.cue.slice(0, 80), qualified: m.qualified });+ }+ return out;+}diff --git a/src/core/fact-keys.ts b/src/core/fact-keys.tsnew file mode 100644index 0000000000..bc728cd1ea--- /dev/null+++ b/src/core/fact-keys.ts@@ -0,0 +1,87 @@+/**+ * Fact keys: short facts extracted from a page, merged into the embedding+ * input of the page's own chunks so a question phrased like the fact finds+ * the page — while search still returns the page's original text.+ *+ * Merging the facts into the chunk's embedding input (one key per chunk) is+ * the measured-better design; adding each fact as its own separately-ranked+ * key enlarges the index and ranks worse than no expansion at all.+ *+ * Pure: no DB, no network. Callers supply the extracted items and the page's+ * chunks; this module decides which facts each chunk carries and builds the+ * embedding input. The stored `chunk_text` is never changed.+ */++export type FactKeyAssignment = 'chunk' | 'page';++/** Maximum fact-key characters attached to one chunk. */+export const FACT_KEYS_MAX_CHARS = 800;++const STOPWORDS = new Set(['the', 'a', 'an', 'and', 'or', 'of', 'to', 'in', 'on', 'for', 'with', 'is', 'was', 'are', 'were',+ 'be', 'been', 'it', 'that', 'this', 'at', 'by', 'from', 'as', 'user', 'users', 'i', 'my', 'me', 'they', 'their', 'has', 'have', 'had']);++function tokens(text: string): Set<string> {+ return new Set((text.toLowerCase().match(/[\p{L}\p{N}]+/gu) ?? []).filter(t => t.length > 2 && !STOPWORDS.has(t)));+}++function sanitize(item: string): string {+ return item.replace(/<\/?context>/gi, '').replace(/\s+/g, ' ').trim();+}++function capJoin(items: string[]): string | null {+ let out = '';+ for (const item of items) {+ const next = out ? `${out}; ${item}` : item;+ if (next.length > FACT_KEYS_MAX_CHARS) break;+ out = next;+ }+ return out || null;+}++/**+ * Fact-key text per chunk (null = no keys). `chunk` assigns each fact to the+ * chunk sharing the most content words with it (ties to the earliest chunk;+ * a fact sharing none goes to the first chunk); `page` gives every chunk all+ * of the page's facts. Code and image chunks never carry keys.+ */+export function assignFactKeys(+ items: readonly string[],+ chunks: ReadonlyArray<{ chunk_text: string; chunk_source?: string | null }>,+ assignment: FactKeyAssignment,+): Array<string | null> {+ const clean = [...new Set(items.map(sanitize).filter(Boolean))];+ const eligible = chunks.map(c => c.chunk_source !== 'fenced_code' && c.chunk_source !== 'image_asset');+ const out: Array<string | null> = chunks.map(() => null);+ if (clean.length === 0 || !eligible.some(Boolean)) return out;+ if (assignment === 'page') {+ const text = capJoin(clean);+ return chunks.map((_, i) => (eligible[i] ? text : null));+ }+ const chunkTokens = chunks.map(c => tokens(c.chunk_text));+ const buckets: string[][] = chunks.map(() => []);+ const first = eligible.indexOf(true);+ for (const item of clean) {+ const t = tokens(item);+ let best = first;+ let bestScore = 0;+ for (let i = 0; i < chunks.length; i++) {+ if (!eligible[i]) continue;+ let score = 0;+ for (const w of t) if (chunkTokens[i].has(w)) score++;+ if (score > bestScore) { best = i; bestScore = score; }+ }+ buckets[best].push(item);+ }+ return buckets.map((b, i) => (eligible[i] ? capJoin(b) : null));+}++/**+ * The embedding input for a chunk carrying fact keys, in the same+ * `<context>` wrapper the title prefix uses. Null keys return the plain+ * title-wrapped (or raw, without a title) input unchanged.+ */+export function factKeyedEmbeddingInput(chunkText: string, title: string | null, factKeys: string | null): string {+ const safeTitle = (title ?? '').replace(/<\/?context>/gi, '').replace(/\s+/g, ' ').trim().slice(0, 300);+ if (!factKeys) return safeTitle ? `<context>${safeTitle}\n</context>\n${chunkText}` : chunkText;+ return `<context>${safeTitle}\nFacts: ${factKeys}\n</context>\n${chunkText}`;+}diff --git a/src/core/ops/takes.ts b/src/core/ops/takes.tsindex 0395cb51e0..83db092046 100644--- a/src/core/ops/takes.ts+++ b/src/core/ops/takes.ts@@ -191,6 +191,10 @@ async function countMcpResolved(ctx: OperationContext): Promise<number> {/** runThink names the CLI flag; op callers get the param on their own surface and a caller-class code. */function thinkModelError(ctx: OperationContext, e: unknown): unknown {+ if (e instanceof Error && e.name === 'ReferenceDateError') {+ return opError('invalid_params', `think: ${e.message}`,+ `Nothing was synthesized. Pass ${opTransport(ctx) === 'cli' ? paramUse(ctx, 'reference_date') : '`reference_date`'} as a past or current YYYY-MM-DD, or omit it to use today in brain.timezone.`);+ }if (!(e instanceof Error) || !e.message.startsWith('think: --model ')) return e;const name = opTransport(ctx) === 'cli' ? paramUse(ctx, 'model') : '`model`';return opError('invalid_params',@@ -213,6 +217,8 @@ const think: Operation = {model: { type: 'string', description: 'Model override (alias or full id). Falls through models.think → models.default → GBRAIN_MODEL → opus.' },since: { type: 'string', description: 'Start of temporal window (YYYY-MM-DD or YYYY-MM)' },until: { type: 'string', description: 'End of temporal window' },+ reference_date: { type: 'string', description: 'YYYY-MM-DD the question\'s relative time words resolve against (default: today in brain.timezone).' },+ reading_notes: { type: 'string', enum: ['on', 'off', 'auto'], description: 'Notes-first reading for this call (default: think.reading_notes). Notes return in reading_notes, never in the answer.' },},// Local CLI can persist with save/take; remote/MCP callers are forced// read-only below before runThink/persistSynthesis sees those flags.@@ -245,6 +251,8 @@ const think: Operation = {modelExplicit: !!p.model,since: p.since ? String(p.since) : undefined,until: p.until ? String(p.until) : undefined,+ ...(typeof p.reference_date === 'string' ? { referenceDate: p.reference_date } : {}),+ ...(p.reading_notes === 'on' || p.reading_notes === 'off' || p.reading_notes === 'auto' ? { readingNotes: p.reading_notes } : {}),takesHoldersAllowList: readHolders(ctx),...thinkScope,excludePrivate: (await readPolicyOpts(ctx)).excludePrivate,diff --git a/src/core/search/hybrid/time-scope.ts b/src/core/search/hybrid/time-scope.tsnew file mode 100644index 0000000000..ae8d7e9f7c--- /dev/null+++ b/src/core/search/hybrid/time-scope.ts@@ -0,0 +1,62 @@+/**+ * Soft time scope: move results whose dates fall inside the question's time+ * range forward without dropping anything.+ *+ * `reserved` (shipping candidate) keeps the top ⌈k/2⌉ baseline results in+ * place, fills the rest of the first k slots with in-range results in their+ * baseline order, then continues with the remaining baseline order — so the+ * strongest unscoped evidence is never displaced. `partition` moves every+ * in-range result ahead of every other result (the published replication+ * arm). Both are permutations of the input; with no in-range result the+ * input order is returned unchanged.+ */++import { addDays, type DayRange } from '../../temporal-grammar.ts';++export type TimeScopeMode = 'reserved' | 'partition';++export interface TimeScopeOpts {+ mode: TimeScopeMode;+ /** Result slots the caller will deliver (the reserved contract is defined over these). */+ k: number;+ /** Days of slack on each side of the range (default 2). */+ slackDays?: number;+}++export interface TimeScopeOutcome<T> {+ results: T[];+ inRange: number;+ moved: number;+}++export function overlapsRange(dates: readonly DayRange[] | undefined, range: DayRange, slackDays: number): boolean {+ if (!dates || dates.length === 0) return false;+ const lo = addDays(range.start, -slackDays);+ const hi = addDays(range.end, slackDays);+ return dates.some(d => d.start <= hi && d.end >= lo);+}++export function applyTimeScope<T>(+ results: readonly T[],+ range: DayRange,+ datesOf: (r: T) => readonly DayRange[] | undefined,+ opts: TimeScopeOpts,+): TimeScopeOutcome<T> {+ const slack = opts.slackDays ?? 2;+ const flags = results.map(r => overlapsRange(datesOf(r), range, slack));+ const inRange = flags.filter(Boolean).length;+ if (inRange === 0) return { results: [...results], inRange: 0, moved: 0 };+ let ordered: T[];+ if (opts.mode === 'partition') {+ ordered = [...results.filter((_, i) => flags[i]), ...results.filter((_, i) => !flags[i])];+ } else {+ const keep = Math.ceil(Math.max(1, opts.k) / 2);+ const head = results.slice(0, keep);+ const restIdx = results.map((_, i) => i).slice(keep);+ const fill = restIdx.filter(i => flags[i]).slice(0, Math.max(0, opts.k - keep));+ const fillSet = new Set(fill);+ ordered = [...head, ...fill.map(i => results[i]), ...restIdx.filter(i => !fillSet.has(i)).map(i => results[i])];+ }+ const moved = ordered.reduce((n, r, i) => n + (r !== results[i] ? 1 : 0), 0);+ return { results: ordered, inRange, moved };+}diff --git a/src/core/search/time-range.ts b/src/core/search/time-range.tsnew file mode 100644index 0000000000..70ee910fb2--- /dev/null+++ b/src/core/search/time-range.ts@@ -0,0 +1,49 @@+/**+ * Deterministic query time-range parser: "what did I decide last month" →+ * the calendar range the question points at, resolved against a reference+ * day (today in brain.timezone, or a caller-supplied date).+ *+ * Fires only on explicit cues (temporal-grammar.ts) and abstains otherwise:+ * a question that asks for a duration ("how many days…", "how long…"), or+ * that names two separate times in different roles ("which June deadline did+ * we cancel in May"), returns null so retrieval stays unscoped. Joined+ * mentions ("in March and April", "between May 3 and May 9") are one range.+ */++import { findTimeMentions, asksForDuration, type DayRange, type TimeMention } from '../temporal-grammar.ts';++export interface QueryTimeRange extends DayRange {+ /** The phrase the range came from, e.g. "last month". */+ cue: string;+ /** The day the cue was resolved against. */+ reference_date: string;+}++export type TimeRangeAbstention = 'no_cue' | 'multi_role' | 'duration_question';++export interface TimeRangeParse {+ range: QueryTimeRange | null;+ reason: TimeRangeAbstention | 'applied';+}++/** Two mentions joined by "and/or/to/through/-" with nothing else between them are one span. */+function joined(text: string, a: TimeMention, b: TimeMention): boolean {+ const between = text.slice(a.index + a.cue.length, b.index).trim().toLowerCase();+ return /^(?:and|or|to|through|until|till|-|–|—)$/.test(between);+}++export function parseQueryTimeRange(query: string, referenceDate: string): TimeRangeParse {+ const mentions = findTimeMentions(query, referenceDate, 'past');+ if (mentions.length === 0) return { range: null, reason: 'no_cue' };+ if (asksForDuration(query)) return { range: null, reason: 'duration_question' };+ let start = mentions[0].start;+ let end = mentions[0].end;+ let cue = mentions[0].cue;+ for (let i = 1; i < mentions.length; i++) {+ if (!joined(query, mentions[i - 1], mentions[i])) return { range: null, reason: 'multi_role' };+ start = mentions[i].start < start ? mentions[i].start : start;+ end = mentions[i].end > end ? mentions[i].end : end;+ cue = query.slice(mentions[0].index, mentions[i].index + mentions[i].cue.length);+ }+ return { range: { start, end, cue, reference_date: referenceDate }, reason: 'applied' };+}diff --git a/src/core/temporal-grammar.ts b/src/core/temporal-grammar.tsnew file mode 100644index 0000000000..1fc9ff2cc2--- /dev/null+++ b/src/core/temporal-grammar.ts@@ -0,0 +1,327 @@+/**+ * Deterministic time-expression grammar shared by the query time-range+ * parser (search/time-range.ts) and content date extraction+ * (event-dates.ts). No LLM, no network: a fixed set of English patterns+ * resolved against a reference day.+ *+ * Precision over recall. A phrase resolves only when it names a time+ * explicitly ("last month", "two weeks ago", "in June", "March 15th",+ * "last Saturday", "in 2022"). Vague or question-shaped phrases ("how many+ * months ago", "how long", "recently", "currently") resolve to nothing, and+ * so do weekday or month words inside quotes or used as plurals+ * ("Turbocharged Tuesdays").+ *+ * All dates are calendar days (YYYY-MM-DD, UTC arithmetic on whole days);+ * ranges are inclusive. Weeks run Monday to Sunday.+ */++export interface DayRange {+ start: string;+ end: string;+}++export interface TimeMention extends DayRange {+ /** The matched text, as written. */+ cue: string;+ /** Character offset of the match in the input. */+ index: number;+ /** relative = resolved against the reference day; absolute = the text names the date. */+ kind: 'relative' | 'absolute';+ /** A bare month or weekday whose year/week was chosen by direction, not stated. */+ qualified: boolean;+}++export type Direction = 'past' | 'future' | 'either';++const MONTHS = ['january', 'february', 'march', 'april', 'may', 'june', 'july', 'august', 'september', 'october', 'november', 'december'];+const MONTH_ABBR: Record<string, number> = {};+MONTHS.forEach((m, i) => { MONTH_ABBR[m] = i; MONTH_ABBR[m.slice(0, 3)] = i; });+MONTH_ABBR.sept = 8;+const WEEKDAYS = ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday'];+const SEASONS: Record<string, [number, number]> = { spring: [2, 4], summer: [5, 7], fall: [8, 10], autumn: [8, 10], winter: [11, 1] };+const NUMBER_WORDS: Record<string, number> = {+ a: 1, an: 1, one: 1, two: 2, three: 3, four: 4, five: 5, six: 6, seven: 7, eight: 8, nine: 9, ten: 10,+ eleven: 11, twelve: 12, couple: 2, 'a couple of': 2, 'a few': 3, few: 3, several: 3,+};++const DAY_MS = 86_400_000;++export function toDay(d: Date): string {+ return d.toISOString().slice(0, 10);+}++export function parseDay(day: string): Date {+ return new Date(`${day}T00:00:00Z`);+}++export function addDays(day: string, n: number): string {+ return toDay(new Date(parseDay(day).getTime() + n * DAY_MS));+}++function ymd(y: number, m: number, d: number): string {+ return toDay(new Date(Date.UTC(y, m, d)));+}++function monthRange(y: number, m: number): DayRange {+ return { start: ymd(y, m, 1), end: ymd(y, m + 1, 0) };+}++function weekStart(day: string): string {+ const dow = parseDay(day).getUTCDay();+ return addDays(day, -((dow + 6) % 7));+}++function isRealDay(y: number, m: number, d: number): boolean {+ const t = new Date(Date.UTC(y, m, d));+ return t.getUTCFullYear() === y && t.getUTCMonth() === m && t.getUTCDate() === d;+}++/** Spans inside straight or curly quotes; mentions there are names, not times. */+function quotedSpans(text: string): Array<[number, number]> {+ const spans: Array<[number, number]> = [];+ const re = /(["“'‘])([^"”'’\n]{1,80})(["”'’])/g;+ for (const m of text.matchAll(re)) {+ const open = m[1];+ const close = m[3];+ const pair = (open === '"' && close === '"') || (open === '“' && close === '”') || (open === "'" && close === "'") || (open === '‘' && close === '’');+ if (!pair) continue;+ if (open === "'" && /\w/.test(text[(m.index ?? 0) - 1] ?? '')) continue;+ spans.push([m.index ?? 0, (m.index ?? 0) + m[0].length]);+ }+ return spans;+}++function inSpans(i: number, spans: Array<[number, number]>): boolean {+ return spans.some(([a, b]) => i >= a && i < b);+}++function numberValue(raw: string): number | null {+ const v = raw.toLowerCase().trim();+ if (/^\d{1,3}$/.test(v)) return parseInt(v, 10);+ return NUMBER_WORDS[v] ?? null;+}++const NUM = String.raw`(\d{1,3}|a couple of|a few|couple of|one|two|three|four|five|six|seven|eight|nine|ten|eleven|twelve|several|an?)`;+const MONTH_RE = String.raw`(january|february|march|april|may|june|july|august|september|sept|october|november|december|jan|feb|mar|apr|jun|jul|aug|sep|oct|nov|dec)\.?`;+const WEEKDAY_RE = String.raw`(monday|tuesday|wednesday|thursday|friday|saturday|sunday)`;++interface Rule {+ re: RegExp;+ resolve: (m: RegExpMatchArray, ref: string, dir: Direction) => (DayRange & { kind: 'relative' | 'absolute'; qualified?: boolean }) | null;+}++/** Most recent (past) / next (future) occurrence of month `m` relative to ref; `either` keeps past. */+function pickYearForMonth(m: number, ref: string, dir: Direction): { year: number; qualified: boolean } {+ const r = parseDay(ref);+ const y = r.getUTCFullYear();+ const rm = r.getUTCMonth();+ if (dir === 'future') return { year: m >= rm ? y : y + 1, qualified: true };+ return { year: m <= rm ? y : y - 1, qualified: true };+}++const RULES: Rule[] = [+ // ISO date 2023-05-20 / 2023/05/20+ { re: /\b(\d{4})[-/](\d{1,2})[-/](\d{1,2})\b/g, resolve: (m) => {+ const y = +m[1]; const mo = +m[2] - 1; const d = +m[3];+ if (!isRealDay(y, mo, d) || y < 1900 || y > 2199) return null;+ const day = ymd(y, mo, d);+ return { start: day, end: day, kind: 'absolute' };+ } },+ // March 15th, 2023 / March 15 / 15 March 2023 / the 15th of March+ { re: new RegExp(String.raw`\b${MONTH_RE}\s+(\d{1,2})(?:st|nd|rd|th)?(?:,?\s+(\d{4}))?\b`, 'gi'), resolve: (m, ref, dir) => {+ const mo = MONTH_ABBR[m[1].toLowerCase()]; const d = +m[2];+ if (mo === undefined || d < 1 || d > 31) return null;+ let year: number; let qualified = false;+ if (m[3]) year = +m[3];+ else { ({ year } = pickYearForMonth(mo, ref, dir)); qualified = true; }+ if (!isRealDay(year, mo, d)) return null;+ const day = ymd(year, mo, d);+ return { start: day, end: day, kind: m[3] ? 'absolute' : 'relative', qualified };+ } },+ { re: new RegExp(String.raw`\b(?:the\s+)?(\d{1,2})(?:st|nd|rd|th)?\s+(?:of\s+)?${MONTH_RE}(?:,?\s+(\d{4}))?\b`, 'gi'), resolve: (m, ref, dir) => {+ const d = +m[1]; const mo = MONTH_ABBR[m[2].toLowerCase()];+ if (mo === undefined || d < 1 || d > 31) return null;+ let year: number; let qualified = false;+ if (m[3]) year = +m[3];+ else { ({ year } = pickYearForMonth(mo, ref, dir)); qualified = true; }+ if (!isRealDay(year, mo, d)) return null;+ const day = ymd(year, mo, d);+ return { start: day, end: day, kind: m[3] ? 'absolute' : 'relative', qualified };+ } },+ // between March and April / in March and April / from March to April+ { re: new RegExp(String.raw`\b(?:between|in|during|from)\s+${MONTH_RE}\s+(?:and|to|through|-)\s+${MONTH_RE}(?:,?\s+(\d{4}))?\b`, 'gi'), resolve: (m, ref, dir) => {+ const a = MONTH_ABBR[m[1].toLowerCase()]; const b = MONTH_ABBR[m[2].toLowerCase()];+ if (a === undefined || b === undefined) return null;+ const yb = m[3] ? +m[3] : pickYearForMonth(b, ref, dir).year;+ const ya = a <= b ? yb : yb - 1;+ return { start: monthRange(ya, a).start, end: monthRange(yb, b).end, kind: m[3] ? 'absolute' : 'relative', qualified: !m[3] };+ } },+ // in/during/of/last/this <Month> [year]+ { re: new RegExp(String.raw`\b(in|during|of|since|by|last|this|early|mid|late)\s+(?:early\s+|mid\s+|late\s+)?${MONTH_RE}(?:,?\s+(\d{4}))?\b`, 'gi'), resolve: (m, ref, dir) => {+ const mo = MONTH_ABBR[m[2].toLowerCase()];+ if (mo === undefined) return null;+ if (m[1].toLowerCase() === 'since' || m[1].toLowerCase() === 'by') return null;+ if (m[3]) return { ...monthRange(+m[3], mo), kind: 'absolute' };+ const lead = m[1].toLowerCase();+ if (lead === 'this') return { ...monthRange(parseDay(ref).getUTCFullYear(), mo), kind: 'relative', qualified: true };+ const { year } = pickYearForMonth(mo, ref, lead === 'last' ? 'past' : dir);+ return { ...monthRange(year, mo), kind: 'relative', qualified: true };+ } },+ // Month YYYY (no preposition)+ { re: new RegExp(String.raw`\b${MONTH_RE}\s+(\d{4})\b`, 'gi'), resolve: (m) => {+ const mo = MONTH_ABBR[m[1].toLowerCase()];+ if (mo === undefined) return null;+ return { ...monthRange(+m[2], mo), kind: 'absolute' };+ } },+ // a capitalized bare month name ("the June deadline"); "May" needs a preposition (modal verb)+ { re: /\b(January|February|March|April|June|July|August|September|October|November|December)\b/g, resolve: (m, ref, dir) => {+ const mo = MONTH_ABBR[m[1].toLowerCase()];+ const { year } = pickYearForMonth(mo, ref, dir);+ return { ...monthRange(year, mo), kind: 'relative', qualified: true };+ } },+ // in 2022 / during 2022+ { re: /\b(?:in|during|throughout)\s+((?:19|20|21)\d{2})\b(?!\s*(?:%|kg|km|mi|\$))/gi, resolve: (m) => {+ const y = +m[1];+ return { start: ymd(y, 0, 1), end: ymd(y, 11, 31), kind: 'absolute' };+ } },+ // Q3 2022+ { re: /\bQ([1-4])\s*(?:of\s+)?((?:19|20|21)\d{2})\b/gi, resolve: (m) => {+ const q = +m[1] - 1; const y = +m[2];+ return { start: ymd(y, q * 3, 1), end: ymd(y, q * 3 + 3, 0), kind: 'absolute' };+ } },+ // yesterday / today / tonight / last night / tomorrow+ { re: /\b(yesterday|today|tonight|last night|this morning|this afternoon|this evening|tomorrow)\b/gi, resolve: (m, ref) => {+ const w = m[1].toLowerCase();+ const offset = w === 'yesterday' || w === 'last night' ? -1 : w === 'tomorrow' ? 1 : 0;+ const day = addDays(ref, offset);+ return { start: day, end: day, kind: 'relative' };+ } },+ // last/this/next week|weekend|month|year ; the past week|weekend|month|year+ { re: /\b(last|this|next|the past|this past|the last|in the past|over the past|during the past)\s+(week|weekend|month|year)\b/gi, resolve: (m, ref) => {+ const lead = m[1].toLowerCase(); const unit = m[2].toLowerCase();+ const r = parseDay(ref); const y = r.getUTCFullYear(); const mo = r.getUTCMonth();+ const rolling = /past|the last/.test(lead) && lead !== 'this past';+ if (unit === 'weekend') {+ const ws = weekStart(ref);+ const thisSat = addDays(ws, 5);+ if (lead === 'next') return { start: addDays(thisSat, 7), end: addDays(thisSat, 8), kind: 'relative' };+ if (lead === 'this') return { start: thisSat, end: addDays(thisSat, 1), kind: 'relative' };+ const dow = r.getUTCDay();+ const sat = dow === 6 || dow === 0 ? (dow === 6 ? addDays(ref, -7) : addDays(ref, -8)) : addDays(thisSat, -7);+ return { start: sat, end: addDays(sat, 1), kind: 'relative' };+ }+ if (rolling) {+ const days = unit === 'week' ? 7 : unit === 'month' ? 30 : 365;+ return { start: addDays(ref, -days), end: ref, kind: 'relative' };+ }+ if (unit === 'week') {+ const ws = weekStart(ref);+ if (lead === 'next') return { start: addDays(ws, 7), end: addDays(ws, 13), kind: 'relative' };+ if (lead === 'this') return { start: ws, end: addDays(ws, 6), kind: 'relative' };+ return { start: addDays(ws, -7), end: addDays(ws, -1), kind: 'relative' };+ }+ if (unit === 'month') {+ if (lead === 'next') return { ...monthRange(y, mo + 1), kind: 'relative' };+ if (lead === 'this') return { ...monthRange(y, mo), kind: 'relative' };+ return { ...monthRange(y, mo - 1), kind: 'relative' };+ }+ if (lead === 'next') return { start: ymd(y + 1, 0, 1), end: ymd(y + 1, 11, 31), kind: 'relative' };+ if (lead === 'this') return { start: ymd(y, 0, 1), end: ymd(y, 11, 31), kind: 'relative' };+ return { start: ymd(y - 1, 0, 1), end: ymd(y - 1, 11, 31), kind: 'relative' };+ } },+ // last/this/next <season>+ { re: /\b(last|this|next|in the|this past)\s+(spring|summer|fall|autumn|winter)\b/gi, resolve: (m, ref, dir) => {+ const lead = m[1].toLowerCase(); const [a, b] = SEASONS[m[2].toLowerCase()];+ const r = parseDay(ref); const y = r.getUTCFullYear(); const mo = r.getUTCMonth();+ const span = (startYear: number) => ({ start: ymd(startYear, a, 1), end: b < a ? ymd(startYear + 1, b + 1, 0) : ymd(startYear, b + 1, 0) });+ const containing = a <= b ? (mo >= a && mo <= b ? y : null) : (mo >= a ? y : mo <= b ? y - 1 : null);+ const lastCompleted = () => { let sy = a <= b ? y : y - 1; for (let i = 0; i < 3; i++) { const s = span(sy); if (s.end < ref) return s; sy -= 1; } return span(sy); };+ if (lead === 'this') return { ...(containing !== null ? span(containing) : lastCompleted()), kind: 'relative', qualified: true };+ if (lead === 'next') { let sy = a <= b ? y : y; for (let i = 0; i < 3; i++) { const s = span(sy); if (s.start > ref) return { ...s, kind: 'relative', qualified: true }; sy += 1; } return null; }+ if (lead === 'in the' && dir === 'future') return null;+ return { ...lastCompleted(), kind: 'relative', qualified: true };+ } },+ // last <weekday> / this past <weekday>+ { re: new RegExp(String.raw`\b(last|this past|this|next|on)\s+${WEEKDAY_RE}\b(?!s)`, 'gi'), resolve: (m, ref, dir) => {+ const lead = m[1].toLowerCase(); const target = WEEKDAYS.indexOf(m[2].toLowerCase());+ const dow = parseDay(ref).getUTCDay();+ if (lead === 'next') { const ahead = ((target - dow + 7) % 7) || 7; const day = addDays(ref, ahead); return { start: day, end: day, kind: 'relative' }; }+ if (lead === 'on' || lead === 'this') {+ if (dir === 'future') { const ahead = (target - dow + 7) % 7; const day = addDays(ref, ahead); return { start: day, end: day, kind: 'relative', qualified: true }; }+ const back = (dow - target + 7) % 7; const day = addDays(ref, -back); return { start: day, end: day, kind: 'relative', qualified: true };+ }+ const back = ((dow - target + 7) % 7) || 7;+ const day = addDays(ref, -back);+ return { start: day, end: day, kind: 'relative' };+ } },+ // N days/weeks/months/years ago ; (the <weekday>) N units ago+ { re: new RegExp(String.raw`\b(?:(?:the|a)\s+${WEEKDAY_RE}\s+)?${NUM}\s+(day|week|month|year)s?\s+ago\b`, 'gi'), resolve: (m, ref) => {+ const n = numberValue(m[2]); if (n === null || n <= 0) return null;+ const unit = m[3].toLowerCase();+ const fuzzy = /few|couple|several/i.test(m[2]);+ if (unit === 'day') { const c = addDays(ref, -n); const s = fuzzy ? 1 : 0; return { start: addDays(c, -s - 1), end: addDays(c, s + 1), kind: 'relative' }; }+ if (unit === 'week') { const c = addDays(ref, -7 * n); return { start: addDays(c, -3), end: addDays(c, 3), kind: 'relative' }; }+ if (unit === 'month') {+ const r = parseDay(ref);+ const c = toDay(new Date(Date.UTC(r.getUTCFullYear(), r.getUTCMonth() - n, Math.min(r.getUTCDate(), 28))));+ const w = m[1] ? 7 : 15;+ return { start: addDays(c, -w), end: addDays(c, w), kind: 'relative' };+ }+ const y = parseDay(ref).getUTCFullYear() - n;+ return { start: ymd(y, 0, 1), end: ymd(y, 11, 31), kind: 'relative' };+ } },+ // in N days/weeks (future)+ { re: new RegExp(String.raw`\bin\s+${NUM}\s+(day|week|month)s?\b(?!\s+ago)`, 'gi'), resolve: (m, ref, dir) => {+ if (dir === 'past') return null;+ const n = numberValue(m[1]); if (n === null || n <= 0) return null;+ const unit = m[2].toLowerCase();+ const c = addDays(ref, unit === 'day' ? n : unit === 'week' ? 7 * n : 30 * n);+ const s = unit === 'day' ? 1 : unit === 'week' ? 3 : 15;+ return { start: addDays(c, -s), end: addDays(c, s), kind: 'relative' };+ } },+];++/**+ * Question shapes that ask for the length of an interval ("how long…", "how many+ * days ago / passed / before…"), where a mentioned date is an endpoint, not the+ * evidence window. Counting inside a window ("how many days did I spend camping+ * this year") still resolves.+ */+const NON_RANGE_QUESTION = /\bhow\s+long\b|\bhow\s+(?:many|much)\s+(?:days?|weeks?|months?|years?|time)\s+(?:ago|passed|elapsed|before|after|since|between|until|had|have|has|were|was|is|are)\b/i;++/**+ * Every explicit time mention in `text`, resolved against `ref`. Overlapping+ * matches keep the longest (first on ties). `dir` resolves bare months and+ * weekdays toward the past (content written about what happened), the future,+ * or past by default for `either`.+ */+export function findTimeMentions(text: string, ref: string, dir: Direction = 'past'): TimeMention[] {+ const quotes = quotedSpans(text);+ const found: TimeMention[] = [];+ for (const rule of RULES) {+ rule.re.lastIndex = 0;+ for (const m of text.matchAll(rule.re)) {+ const index = m.index ?? 0;+ if (inSpans(index, quotes)) continue;+ const r = rule.resolve(m, ref, dir);+ if (!r || r.start > r.end) continue;+ found.push({ start: r.start, end: r.end, cue: m[0].trim(), index, kind: r.kind, qualified: r.qualified ?? false });+ }+ }+ found.sort((a, b) => a.index - b.index || b.cue.length - a.cue.length);+ const kept: TimeMention[] = [];+ for (const f of found) {+ const prev = kept[kept.length - 1];+ if (prev && f.index < prev.index + prev.cue.length) {+ if (f.cue.length > prev.cue.length) kept[kept.length - 1] = f;+ continue;+ }+ kept.push(f);+ }+ return kept;+}++/** True when the text asks "how long / how many days" — a duration, not a window. */+export function asksForDuration(text: string): boolean {+ return NON_RANGE_QUESTION.test(text);+}diff --git a/src/core/think/gather.ts b/src/core/think/gather.tsindex e908726d51..1073d7a61a 100644--- a/src/core/think/gather.ts+++ b/src/core/think/gather.ts@@ -21,6 +21,7 @@ import { INTERNAL_BREADTH_SEARCH_OPTS } from '../search/internal-breadth.ts';import { sanitizeRemoteBody } from '../remote-body.ts';import type { Page, SearchResult } from '../types.ts';import { filterPagesToWindow, type TemporalWindow } from './temporal-window.ts';+import { pageContentDate } from './temporal-context.ts';import { sanitizeQueryForPrompt } from '../search/expansion.ts';import { ensureWellFormed } from '../text-safe.ts';import { CJK_SLUG_CHARS } from '../cjk.ts';@@ -606,7 +607,8 @@ export const INJECTION_SUSPECTED_LINE = 'injection_suspected: this page contains/*** Render gather results into the per-block strings the prompt builder uses.- * Pages are rendered as `<page slug="..." score="...">excerpt</page>`;+ * Pages are rendered as `<page slug="..." rank="..." date="...">excerpt</page>`; `date` appears only+ * for content-dated pages (see temporal-context.ts) and renders in `opts.timeZone`;* takes are rendered via the renderTakesBlock helper from sanitize.ts.* `excerptLen` is exact per page — callers wanting budget-aware sizing pass* `pagesBlockExcerptLen(pages.length)` (the think pipeline does).@@ -615,9 +617,11 @@ export function renderPagesBlock(pages: SearchResult[],excerptLen = 600,query = '',- opts: { verbatim?: boolean | ((p: SearchResult) => boolean); verbatimLen?: number } = {},+ opts: { verbatim?: boolean | ((p: SearchResult) => boolean); verbatimLen?: number; timeZone?: string } = {},): string {return pages.map((p, idx) => {+ const day = pageContentDate(p, opts.timeZone ?? 'UTC');+ const dateAttr = day ? ` date="${day}"` : '';const page = p as unknown as {slug?: string;title?: string;@@ -633,7 +637,7 @@ export function renderPagesBlock(// Evidence delivery: the block was already budgeted and cut around its// hits; render it whole (capped only by excerptLen).if (typeof opts.verbatim === 'function' ? opts.verbatim(p) : opts.verbatim) {- return `<page slug="${slug}" rank="${idx + 1}">\n${flag}${content.slice(0, opts.verbatimLen ?? excerptLen)}\n</page>`;+ return `<page slug="${slug}" rank="${idx + 1}"${dateAttr}>\n${flag}${content.slice(0, opts.verbatimLen ?? excerptLen)}\n</page>`;}const excerpt = selectRelevantExcerptDetailed(content,@@ -645,7 +649,7 @@ export function renderPagesBlock((excerpt.truncatedStart ? `${EXCERPT_CUT_START_MARKER}\n` : '') +excerpt.text +(excerpt.truncatedEnd ? `\n${EXCERPT_CUT_END_MARKER}` : '');- return `<page slug="${slug}" rank="${idx + 1}">\n${flag}${body}\n</page>`;+ return `<page slug="${slug}" rank="${idx + 1}"${dateAttr}>\n${flag}${body}\n</page>`;}).join('\n\n');}diff --git a/src/core/think/index.ts b/src/core/think/index.tsindex 44541d92c9..6c358031da 100644--- a/src/core/think/index.ts+++ b/src/core/think/index.ts@@ -32,6 +32,7 @@ import { AIConfigError } from '../ai/errors.ts';import { normalizeModelId } from '../model-id.ts';import { hasAnthropicKey } from '../ai/anthropic-key.ts';import { parseTemporalWindow } from './temporal-window.ts';+import { resolveThinkTemporalContext } from './temporal-context.ts';import { resolveExcludePrivatePages } from '../search/private-visibility.ts';import { deliverEvidence, effectivePlan, resolveEvidencePlan, EVIDENCE_BLOCK_CHAR_CAP, THINK_RETURN_UNIT_CONFIG_KEY, type DeliveryMeta } from '../search/evidence-delivery.ts';import { startThinkDecide, thinkAbstainResult, type ThinkAbstention } from './decide.ts';@@ -140,10 +141,27 @@ export interface RunThinkOpts {* to world-only rows.*/remote?: boolean;+ /**+ * Reference date (YYYY-MM-DD) the question's relative time words resolve+ * against; default today in `brain.timezone`. Evals pass the dataset's+ * question date. Invalid or future values throw ReferenceDateError.+ */+ referenceDate?: string;+ /** Per-call notes-first reading override; default `think.reading_notes`. */+ readingNotes?: ThinkReadingNotesMode;}+export type ThinkReadingNotesMode = 'on' | 'off' | 'auto';+const THINK_READING_NOTES_CONFIG_KEY = 'think.reading_notes';+/** Shipped default until the held-out think-lane verdict sets it. */+const DEFAULT_THINK_READING_NOTES: ThinkReadingNotesMode = 'off';+/** Output-token allowance added when notes are on, so notes never crowd out the answer. */+const READING_NOTES_OUTPUT_ALLOWANCE = 512;+/** Structured response from the LLM (matches the schema declared in prompt.ts). */export interface ThinkResponse {+ /** Notes-first reading scratch work; never part of the answer or persisted. */+ notes?: string;answer: string;citations: Array<{ page_slug: string; row_num: number | null; citation_index?: number }>;gaps: string[];@@ -219,6 +237,10 @@ export interface ThinkResult {cost_usd?: number;/** System One S4 (on): the brain holds no evidence; synthesis was skipped (think/decide.ts). */abstained?: ThinkAbstention;+ /** The date frame the synthesis read in (reference date + brain timezone). */+ temporal?: { reference_date: string; time_zone: string };+ /** Reading mode applied and the model's notes (null when off or absent). Never persisted. */+ reading_notes?: { mode: 'on' | 'off'; notes: string | null };}const DEFAULT_MAX_OUTPUT_TOKENS = 4000;@@ -497,13 +519,13 @@ async function persistCitations(* the renderer passes through whole instead of cutting its own excerpts;* auto's unchanged chunks keep the usual excerpts.*/-async function renderThinkPages(engine: BrainEngine, opts: RunThinkOpts, pages: SearchResult[]): Promise<{ pagesBlock: string; evidenceDelivery?: DeliveryMeta }> {+async function renderThinkPages(engine: BrainEngine, opts: RunThinkOpts, pages: SearchResult[], timeZone: string): Promise<{ pagesBlock: string; evidenceDelivery?: DeliveryMeta }> {const plan = await resolveEvidencePlan(engine, {remote: opts.remote, returnUnit: undefined, returnWindow: undefined, budget: undefined,snippetChars: undefined, snippetCap: 0, configKey: THINK_RETURN_UNIT_CONFIG_KEY, op: 'think',});const applied = effectivePlan(plan, pages);- if (!applied) return { pagesBlock: renderPagesBlock(pages, pagesBlockExcerptLen(pages.length), opts.question) };+ if (!applied) return { pagesBlock: renderPagesBlock(pages, pagesBlockExcerptLen(pages.length), opts.question, { timeZone }) };const delivered = await deliverEvidence(engine, pages, applied, {...(opts.allowedSources !== undefined && opts.allowedSources.length > 0 ? { sourceIds: opts.allowedSources } : opts.sourceId !== undefined ? { sourceId: opts.sourceId } : {}),excludePrivate: opts.excludePrivate ?? await resolveExcludePrivatePages(engine, opts.remote),@@ -511,8 +533,8 @@ async function renderThinkPages(engine: BrainEngine, opts: RunThinkOpts, pages:});const pagesBlock = applied.unit === 'auto'? renderPagesBlock(delivered.results, pagesBlockExcerptLen(pages.length), opts.question,- { verbatim: r => r.delivered?.reason !== 'not_conversation' && r.delivered?.reason !== 'conversation_over_budget', verbatimLen: EVIDENCE_BLOCK_CHAR_CAP })- : renderPagesBlock(delivered.results, EVIDENCE_BLOCK_CHAR_CAP, opts.question, { verbatim: true });+ { verbatim: r => r.delivered?.reason !== 'not_conversation' && r.delivered?.reason !== 'conversation_over_budget', verbatimLen: EVIDENCE_BLOCK_CHAR_CAP, timeZone })+ : renderPagesBlock(delivered.results, EVIDENCE_BLOCK_CHAR_CAP, opts.question, { verbatim: true, timeZone });return { pagesBlock, evidenceDelivery: delivered.delivery };}@@ -527,6 +549,7 @@ export async function runThink(const rounds = Math.max(1, opts.rounds ?? 1);const warnings: string[] = [];const window = parseTemporalWindow(opts.since, opts.until);+ const temporal = await resolveThinkTemporalContext(engine, { referenceDate: opts.referenceDate });// Resolve the model through the 6-tier chain.const modelUsed = await resolveModel(engine, {@@ -588,7 +611,7 @@ export async function runThink(// budget-aware — 600 chars is the FLOOR (a big gather never collapses each// page below it) and a small gather spreads the block budget into much// larger, often complete, per-page windows.- const { pagesBlock, evidenceDelivery } = await renderThinkPages(engine, opts, gather.pages);+ const { pagesBlock, evidenceDelivery } = await renderThinkPages(engine, opts, gather.pages, temporal.timeZone);const takesForPrompt = gather.takes.map(takesHitToTakeForPrompt);const { rendered: takesBlock, sanitizedCount } = renderTakesBlock(takesForPrompt);if (sanitizedCount > 0) {@@ -727,18 +750,15 @@ export async function runThink(// SYNTHESIZEconst intent = inferIntent(opts.question, opts.anchor);+ const readingNotes = await resolveReadingNotes(engine, opts, gather.pages.length);const systemPrompt = buildThinkSystemPrompt({- intent,+ currentDate: true, readingNotes, intent, willSave: opts.save, withCalibration: !!calibrationBlockOpts,...(opts.anchor !== undefined ? { anchor: opts.anchor } : {}),...(opts.since !== undefined ? { since: opts.since } : {}),...(opts.until !== undefined ? { until: opts.until } : {}),- willSave: opts.save,- withCalibration: !!calibrationBlockOpts,});const userMessage = buildThinkUserMessage({- question: opts.question,- pagesBlock,- takesBlock,+ question: opts.question, pagesBlock, takesBlock, currentDate: `${temporal.referenceDate} (${temporal.timeZone})`,...(graphBlock !== undefined ? { graphBlock } : {}),...(calibrationBlockOpts !== undefined ? { calibration: calibrationBlockOpts } : {}),...(trajectoryBlock.length > 0 ? { trajectoryBlock } : {}),@@ -826,7 +846,7 @@ export async function runThink(try {created = await client.create({model: modelUsed,- max_tokens: maxOutputTokensFor(normalizeModelId(modelUsed)),+ max_tokens: maxOutputTokensFor(normalizeModelId(modelUsed)) + (readingNotes ? READING_NOTES_OUTPUT_ALLOWANCE : 0),system: systemPrompt,messages: [{ role: 'user', content: userMessage }],});@@ -872,6 +892,7 @@ export async function runThink(const stop = (created as { stop_reason?: string }).stop_reason;if (stop === 'max_tokens') {warnings.push('LLM_OUTPUT_TRUNCATED');+ if (readingNotes) warnings.push('READING_NOTES_TRUNCATED');synthesisStatus = 'output_truncated';} else {warnings.push('LLM_OUTPUT_NOT_JSON');@@ -897,12 +918,7 @@ export async function runThink(response = { answer: text, citations: [], gaps: [] };}} else {- const r = parsed as Partial<ThinkResponse>;- response = {- answer: typeof r.answer === 'string' ? r.answer : '',- citations: Array.isArray(r.citations) ? (r.citations as ThinkResponse['citations']) : [],- gaps: Array.isArray(r.gaps) ? (r.gaps as string[]).filter(g => typeof g === 'string') : [],- };+ response = toThinkResponse(parsed as Partial<ThinkResponse>);}}}@@ -967,9 +983,37 @@ export async function runThink(takesFromVector: gather.diagnostics.takesFromVector,graphHits: gather.diagnostics.graphHits,},+ temporal: { reference_date: temporal.referenceDate, time_zone: temporal.timeZone },+ reading_notes: { mode: readingNotes ? 'on' : 'off', notes: readingNotes ? response.notes ?? null : null },+ };+}++/** Normalizes the model's parsed JSON envelope; `notes` survives only as a non-empty string. */+function toThinkResponse(r: Partial<ThinkResponse>): ThinkResponse {+ return {+ ...(typeof r.notes === 'string' && r.notes.trim() ? { notes: r.notes.trim() } : {}),+ answer: typeof r.answer === 'string' ? r.answer : '',+ citations: Array.isArray(r.citations) ? (r.citations as ThinkResponse['citations']) : [],+ gaps: Array.isArray(r.gaps) ? (r.gaps as string[]).filter(g => typeof g === 'string') : [],};}+/**+ * Notes-first reading for this call: per-call override, then+ * `think.reading_notes`, then the shipped default. `auto` turns notes on for+ * temporal / knowledge-update questions and for large gathers, where reading+ * across many pages is the hard part.+ */+async function resolveReadingNotes(engine: BrainEngine, opts: RunThinkOpts, pagesGathered: number): Promise<boolean> {+ const configured = (await engine.getConfig(THINK_READING_NOTES_CONFIG_KEY).catch(() => null))?.trim().toLowerCase();+ const mode = opts.readingNotes+ ?? (configured === 'on' || configured === 'off' || configured === 'auto' ? configured : DEFAULT_THINK_READING_NOTES);+ if (mode === 'auto') return classifyIntent(opts.question) !== 'other' || pagesGathered >= READING_NOTES_AUTO_MIN_PAGES;+ return mode === 'on';+}++const READING_NOTES_AUTO_MIN_PAGES = 8;+/*** Strip a "## Gaps" section from an answer body.*diff --git a/src/core/think/prompt.ts b/src/core/think/prompt.tsindex 06a16f84af..b2cb554bd7 100644--- a/src/core/think/prompt.ts+++ b/src/core/think/prompt.ts@@ -35,8 +35,19 @@ export interface ThinkSystemPromptOpts {* message via buildThinkUserMessage.calibration.*/withCalibration?: boolean;+ /**+ * True when the user message carries a `Current date:` line. Adds the+ * date-reading rules; the date itself stays out of the system prompt so+ * the system text is stable across days (prompt caching).+ */+ currentDate?: boolean;+ /** Notes-first reading: the model writes brief per-page notes before the answer. */+ readingNotes?: boolean;}+/** The notes-first output contract appended when reading notes are on. */+export const THINK_READING_NOTES_INSTRUCTION = `Reading notes: before answering, write brief notes in a "notes" string field placed FIRST in the JSON object, before "answer". For each page that bears on the question, note the facts and dates it gives (with its [slug]); skip pages that do not. Keep the notes under 150 words total, then reason from them to the answer. The notes are scratch work: they are never shown as the answer, so the "answer" field must stand on its own.`;+export const THINK_SYSTEM_PROMPT_BASE = `You are gbrain's synthesis engine. You answer questions by reasoning across the user's personal knowledge brain. Your inputs are wrapped in structural tags:<pages>...</pages> Page-level retrieval hits. Each <page slug="..."> contains an excerpt.@@ -85,6 +96,12 @@ export function buildThinkSystemPrompt(opts: ThinkSystemPromptOpts = {}): stringif (opts.willSave) {lines.push(`\nThis synthesis will be persisted as a brain page. Aim for completeness — cover the Answer and any Conflicts thoroughly, and list every missing piece in the structured "gaps" array.`);}+ if (opts.currentDate) {+ lines.push(`\nDates: the user message gives the current date. A <page date="YYYY-MM-DD"> attribute is the date that page's content is about or was written. Resolve relative time words in a page ("yesterday", "last week", "two months ago") against that page's date, and relative time words in the question against the current date. A page without a date attribute has no known content date.`);+ }+ if (opts.readingNotes) {+ lines.push(`\n${THINK_READING_NOTES_INSTRUCTION}`);+ }if (opts.withCalibration) {lines.push(`\nCalibration-aware mode (v0.36.1.0): the user's calibration profile is included as <calibration> below the retrieval blocks. Apply it to the QUESTION FRAMING, not the evidence:`,@@ -165,8 +182,13 @@ export function buildThinkUserMessage(opts: {* (so we don't cue the model that we tried).*/trajectoryBlock?: string;+ /** `Current date: …` line placed immediately before the question. */+ currentDate?: string;}): string {const parts: string[] = [];+ const questionLines = opts.currentDate+ ? [`Current date: ${opts.currentDate}`, `Question: ${opts.question}`]+ : [`Question: ${opts.question}`];const hasTrajectory = typeof opts.trajectoryBlock === 'string' && opts.trajectoryBlock.length > 0;if (opts.calibration) {@@ -192,7 +214,7 @@ export function buildThinkUserMessage(opts: {parts.push(opts.trajectoryBlock as string);}parts.push('');- parts.push(`Question: ${opts.question}`);+ parts.push(...questionLines);parts.push('');parts.push('Respond with a single JSON object matching the schema. No prose outside JSON.');return parts.join('\n');@@ -200,7 +222,7 @@ export function buildThinkUserMessage(opts: {// Default path (v0.28-vintage with v0.40.2.0 trajectory slot between// retrieval and the output instruction).- parts.push(`Question: ${opts.question}`);+ parts.push(...questionLines);parts.push('');parts.push('<pages>');parts.push(opts.pagesBlock || '(no page hits)');diff --git a/src/core/think/temporal-context.ts b/src/core/think/temporal-context.tsnew file mode 100644index 0000000000..587ae02541--- /dev/null+++ b/src/core/think/temporal-context.ts@@ -0,0 +1,94 @@+/**+ * The time frame `think` reads in: today's date (or a caller-supplied+ * reference date) in the brain's timezone, and the content date of each+ * gathered page. Relative time words in the question ("last month") resolve+ * against the reference date; relative words inside a page resolve against+ * that page's date.+ *+ * Only content dates are shown to the reader. A page whose effective date+ * fell back to its creation or update time carries no date, because that+ * time says when the row was written, not when the content happened.+ *+ * Pure apart from the one config read in `resolveThinkTemporalContext`.+ */++import type { BrainEngine } from '../engine.ts';+import { isValidTimeZone } from '../effective-date.ts';++export interface ThinkTemporalContext {+ /** YYYY-MM-DD in `timeZone`. */+ referenceDate: string;+ /** IANA zone (`brain.timezone`), or 'UTC' when unset or invalid. */+ timeZone: string;+ /** True when the caller supplied the reference date. */+ explicitReference: boolean;+}++export class ReferenceDateError extends Error {+ constructor(message: string) {+ super(message);+ this.name = 'ReferenceDateError';+ }+}++/** Effective-date sources that describe the content rather than the row. */+const CONTENT_DATE_SOURCES = new Set(['event_date', 'date', 'published', 'filename']);++const ISO_DAY = /^(\d{4})-(\d{2})-(\d{2})$/;++/** The calendar day an instant falls on in `timeZone`, as YYYY-MM-DD. */+export function dayInZone(instant: Date, timeZone: string): string {+ return new Intl.DateTimeFormat('en-CA', { timeZone, year: 'numeric', month: '2-digit', day: '2-digit' }).format(instant);+}++/**+ * Validates a caller-supplied reference date: a real YYYY-MM-DD calendar day,+ * no later than tomorrow in the brain's timezone (one day of slack covers a+ * caller whose clock is ahead of the brain's zone).+ */+export function parseReferenceDate(raw: string, timeZone: string, now: Date = new Date()): string {+ const value = raw.trim();+ const m = ISO_DAY.exec(value);+ if (!m) throw new ReferenceDateError(`reference_date must be YYYY-MM-DD (got "${value.slice(0, 40)}").`);+ const day = new Date(Date.UTC(+m[1], +m[2] - 1, +m[3]));+ if (day.getUTCFullYear() !== +m[1] || day.getUTCMonth() !== +m[2] - 1 || day.getUTCDate() !== +m[3]) {+ throw new ReferenceDateError(`reference_date is not a real calendar date: "${value}".`);+ }+ const tomorrow = dayInZone(new Date(now.getTime() + 86_400_000), timeZone);+ if (value > tomorrow) throw new ReferenceDateError(`reference_date ${value} is in the future (today is ${dayInZone(now, timeZone)} in ${timeZone}).`);+ return value;+}++export async function resolveThinkTemporalContext(+ engine: BrainEngine,+ opts: { referenceDate?: string; now?: Date } = {},+): Promise<ThinkTemporalContext> {+ const configured = (await engine.getConfig('brain.timezone').catch(() => null))?.trim();+ const timeZone = configured && isValidTimeZone(configured) ? configured : 'UTC';+ const now = opts.now ?? new Date();+ if (opts.referenceDate !== undefined) {+ return { referenceDate: parseReferenceDate(opts.referenceDate, timeZone, now), timeZone, explicitReference: true };+ }+ return { referenceDate: dayInZone(now, timeZone), timeZone, explicitReference: false };+}++/**+ * The content date of a gathered page as YYYY-MM-DD, or null. A value stored+ * at exactly midnight UTC is a day-only frontmatter date and renders as+ * written; any other instant renders in the brain's timezone.+ */+export function pageContentDate(+ page: { effective_date?: string | Date | null; effective_date_source?: string | null },+ timeZone: string,+): string | null {+ if (!page.effective_date_source || !CONTENT_DATE_SOURCES.has(page.effective_date_source)) return null;+ const raw = page.effective_date;+ if (raw === null || raw === undefined || raw === '') return null;+ if (typeof raw === 'string' && ISO_DAY.test(raw.trim())) return raw.trim();+ const instant = raw instanceof Date ? raw : new Date(raw);+ if (!Number.isFinite(instant.getTime())) return null;+ if (instant.getUTCHours() === 0 && instant.getUTCMinutes() === 0 && instant.getUTCSeconds() === 0 && instant.getUTCMilliseconds() === 0) {+ return instant.toISOString().slice(0, 10);+ }+ return dayInZone(instant, timeZone);+}diff --git a/src/eval/longmemeval/retrieval-arms.ts b/src/eval/longmemeval/retrieval-arms.tsnew file mode 100644index 0000000000..d3d83727a2--- /dev/null+++ b/src/eval/longmemeval/retrieval-arms.ts@@ -0,0 +1,300 @@+/**+ * retrieval-arms.ts — eval-only retrieval arms for `gbrain eval longmemeval`:+ * fact keys and time scope. Nothing here runs in production; the arms let+ * a dev-split run measure a mechanism before any product code depends on it.+ *+ * Fact keys (`--fact-keys chunk|page`): after a question's sessions are+ * imported, each session's facts are extracted (`--fact-extractor paper` —+ * the benchmark's published user-turn fact prompt; `production` — gbrain's+ * own facts extractor, 8,000-char input as shipped), merged into the+ * embedding input of that session's chunks (src/core/fact-keys.ts), and the+ * chunks are re-embedded in place. `chunk_text` is untouched, so retrieval+ * still returns the raw session. Extractions are cached on disk by+ * content hash so arms and reruns never pay twice.+ *+ * Time scope (`--time-scope reserved|partition`): the question's explicit+ * time range (src/core/search/time-range.ts, resolved against the dataset's+ * question date) re-orders a widened candidate pool by the sessions' dates+ * (observation date + dates the session mentions). The unscoped top-k from+ * the same pool rides on the row, so each run is its own paired control.+ */++import { createHash } from 'node:crypto';+import { appendFileSync, existsSync, mkdirSync, readFileSync } from 'node:fs';+import { dirname, join } from 'node:path';+import { homedir } from 'node:os';+import type { BrainEngine } from '../../core/engine.ts';+import type { ThinkLLMClient } from '../../core/think/index.ts';+import type { SearchResult } from '../../core/types.ts';+import { assignFactKeys, factKeyedEmbeddingInput, type FactKeyAssignment } from '../../core/fact-keys.ts';+import { embedBatch } from '../../core/embedding.ts';+import { quoteIdentifier, resolveActiveEmbeddingColumnFromEngine, vectorCastSuffix } from '../../core/search/embedding-column.ts';+import { canonicalLookup } from '../../core/model-pricing.ts';+import { extractFactsFromTurnWithOutcome } from '../../core/facts/extract.ts';+import { parseQueryTimeRange, type TimeRangeParse } from '../../core/search/time-range.ts';+import { applyTimeScope, type TimeScopeMode } from '../../core/search/hybrid/time-scope.ts';+import { extractEventDates } from '../../core/event-dates.ts';+import type { DayRange } from '../../core/temporal-grammar.ts';+import { resolveModel } from '../../core/model-config.ts';+import { rawSessionId, scoreRecall, type SlugToRawMap } from './metrics.ts';++export type FactExtractor = 'paper' | 'production';++export interface FactKeyArm {+ assignment: FactKeyAssignment;+ extractor: FactExtractor;+ model: string;+ client: ThinkLLMClient;+ maxUsd: number;+ cachePath?: string;+}++/** The benchmark's published user-fact extraction instruction (zero-shot form). */+export const PAPER_USER_FACT_SYSTEM = 'You will be given a list of messages from a human user to an AI assistant. Extract all the personal information, life events, experience, and preferences related to the user. Make sure you include all details such as life events, personal experience, preferences, specific numbers, locations, or dates. State each piece of information in a simple sentence. Put these sentences in a json list, each element being a standalone personal fact about the user. Minimize the coreference across the facts, e.g., replace pronouns with actual entities. If there is no specific events, personal information, or preference mentioned, just generate an empty list.';++export function defaultFactCachePath(extractor: FactExtractor, model: string): string {+ return join(homedir(), '.cache', 'gbrain-eval', `fact-keys-${extractor}-${model.replace(/[^a-z0-9.-]+/gi, '_')}.jsonl`);+}++export class FactKeySpend {+ usd = 0;+ calls = 0;+ cacheHits = 0;+ constructor(readonly maxUsd: number) {}+ add(model: string, usage: { input_tokens?: number; output_tokens?: number } | undefined): void {+ this.calls++;+ const p = canonicalLookup(model);+ if (!p || !usage) return;+ this.usd += ((usage.input_tokens ?? 0) * p.input + (usage.output_tokens ?? 0) * p.output) / 1_000_000;+ }+ exhausted(): boolean {+ return this.usd >= this.maxUsd;+ }+}++class FactCache {+ private readonly map = new Map<string, string[]>();+ constructor(private readonly path: string) {+ if (!existsSync(path)) return;+ for (const line of readFileSync(path, 'utf8').split('\n')) {+ if (!line.trim()) continue;+ try {+ const row = JSON.parse(line) as { key: string; items: string[] };+ if (row && typeof row.key === 'string' && Array.isArray(row.items)) this.map.set(row.key, row.items);+ } catch { /* a torn final line is skipped */ }+ }+ }+ get(key: string): string[] | undefined { return this.map.get(key); }+ set(key: string, items: string[]): void {+ this.map.set(key, items);+ mkdirSync(dirname(this.path), { recursive: true });+ appendFileSync(this.path, `${JSON.stringify({ key, items })}\n`);+ }+}++const caches = new Map<string, FactCache>();+function cacheFor(path: string): FactCache {+ let c = caches.get(path);+ if (!c) { c = new FactCache(path); caches.set(path, c); }+ return c;+}++/** Session body without frontmatter. */+function bodyOf(content: string): string {+ return content.replace(/^---\n[\s\S]*?\n---\n/, '').trim();+}++function userTurns(body: string): string {+ return body.split(/\n\n(?=\*\*(?:user|assistant):\*\*)/)+ .filter(t => t.startsWith('**user:**'))+ .map(t => `user: ${t.slice('**user:**'.length).trim()}`)+ .join('\n');+}++function parseJsonList(text: string): string[] {+ const cleaned = text.replace(/```(?:json)?/gi, '').trim();+ const match = cleaned.match(/\[[\s\S]*\]/);+ if (!match) return [];+ try {+ const parsed = JSON.parse(match[0]);+ return Array.isArray(parsed) ? parsed.filter((x): x is string => typeof x === 'string' && x.trim().length > 0) : [];+ } catch {+ return [];+ }+}++async function extractItems(engine: BrainEngine, arm: FactKeyArm, body: string, spend: FactKeySpend): Promise<string[]> {+ const cache = cacheFor(arm.cachePath ?? defaultFactCachePath(arm.extractor, arm.model));+ const key = createHash('sha256').update(`${arm.extractor}\n${arm.model}\n${body}`).digest('hex');+ const hit = cache.get(key);+ if (hit) { spend.cacheHits++; return hit; }+ if (spend.exhausted()) throw new Error(`fact-key extraction spend reached its cap ($${spend.maxUsd.toFixed(2)}); raise --fact-keys-max-usd or reuse the cache at ${arm.cachePath ?? defaultFactCachePath(arm.extractor, arm.model)}`);+ let items: string[];+ if (arm.extractor === 'paper') {+ const turns = userTurns(body);+ if (!turns) { cache.set(key, []); return []; }+ const res = await arm.client.create({+ model: arm.model, max_tokens: 2000, system: PAPER_USER_FACT_SYSTEM,+ messages: [{ role: 'user', content: `Human user messages:\n${turns}\n\nPersonal facts about the user (a list of strings in json format; do not generate anything else):` }],+ });+ spend.add(arm.model, (res as { usage?: { input_tokens?: number; output_tokens?: number } }).usage);+ const block = res.content.find(b => b.type === 'text');+ items = parseJsonList(block && 'text' in block ? block.text : '');+ } else {+ const outcome = await extractFactsFromTurnWithOutcome({ turnText: body, source: 'longmemeval:fact-keys', model: arm.model, engine });+ spend.calls++;+ if (!outcome.ok) throw new Error(`production fact extractor unavailable (${outcome.reason}) for ${arm.model}`);+ items = outcome.facts.map(f => f.fact).filter(f => typeof f === 'string' && f.trim().length > 0);+ }+ cache.set(key, items);+ return items;+}++export interface FactKeyArmResult {+ pages_keyed: number;+ chunks_keyed: number;+ items: number;+}++/**+ * Extract facts for every imported session and re-embed its chunks with the+ * fact keys merged into the embedding input. Runs inside the harness's+ * embed-cache transaction, so identical inputs reuse cached vectors.+ */+export async function applyFactKeyArm(+ engine: BrainEngine,+ pages: ReadonlyArray<{ slug: string; content: string }>,+ arm: FactKeyArm,+ spend: FactKeySpend,+): Promise<FactKeyArmResult> {+ const col = await resolveActiveEmbeddingColumnFromEngine(engine);+ const column = quoteIdentifier(col.name);+ const cast = vectorCastSuffix(col);+ const out: FactKeyArmResult = { pages_keyed: 0, chunks_keyed: 0, items: 0 };+ for (const page of pages) {+ const items = await extractItems(engine, arm, bodyOf(page.content), spend);+ if (items.length === 0) continue;+ const chunks = await engine.executeRaw<{ id: number; chunk_text: string; chunk_source: string | null; title: string | null }>(+ `SELECT c.id, c.chunk_text, c.chunk_source, p.title FROM content_chunks c JOIN pages p ON p.id = c.page_id+ WHERE p.slug = $1 ORDER BY c.chunk_index`, [page.slug]);+ if (chunks.length === 0) continue;+ const keys = assignFactKeys(items, chunks, arm.assignment);+ const targets = chunks.map((c, i) => ({ c, k: keys[i] })).filter(t => t.k);+ if (targets.length === 0) continue;+ const vectors = await embedBatch(targets.map(t => factKeyedEmbeddingInput(t.c.chunk_text, t.c.title, t.k)));+ for (let i = 0; i < targets.length; i++) {+ await engine.executeRaw(`UPDATE content_chunks SET ${column} = $1${cast} WHERE id = $2`, [`[${Array.from(vectors[i]).join(',')}]`, targets[i].c.id]);+ }+ out.pages_keyed++;+ out.chunks_keyed += targets.length;+ out.items += items.length;+ }+ return out;+}++/** '2023/05/20 (Sat) 02:21' → '2023-05-20'; anything else → null. */+export function datasetDay(raw: string | undefined): string | null {+ const m = raw ? /^(\d{4})[/-](\d{2})[/-](\d{2})/.exec(raw.trim()) : null;+ return m ? `${m[1]}-${m[2]}-${m[3]}` : null;+}++export interface TimeScopeArmRow {+ time_scope: { mode: TimeScopeMode; reason: TimeRangeParse['reason']; range: DayRange | null; cue: string | null; in_range: number; moved: number };+ unscoped_slugs: string[];+}++/**+ * Re-order a widened pool by the question's explicit time range. Returns the+ * scoped top-k plus the unscoped top-k from the same pool for pairing.+ */+export function applyTimeScopeArm(+ pool: readonly SearchResult[],+ question: { question: string; question_date?: string },+ pageMeta: ReadonlyArray<{ slug: string; content: string; date?: string }>,+ mode: TimeScopeMode,+ k: number,+): { results: SearchResult[]; row: TimeScopeArmRow } {+ const distinct = (rs: readonly SearchResult[]) => {+ const seen = new Set<string>();+ return rs.filter(r => (seen.has(r.slug) ? false : (seen.add(r.slug), true)));+ };+ const unscoped = distinct(pool).slice(0, k);+ const ref = datasetDay(question.question_date);+ const parsed: TimeRangeParse = ref ? parseQueryTimeRange(question.question, ref) : { range: null, reason: 'no_cue' };+ const row: TimeScopeArmRow = {+ time_scope: { mode, reason: parsed.reason, range: parsed.range ? { start: parsed.range.start, end: parsed.range.end } : null, cue: parsed.range?.cue ?? null, in_range: 0, moved: 0 },+ unscoped_slugs: unscoped.map(r => r.slug),+ };+ if (!parsed.range) return { results: unscoped, row };+ const datesBySlug = new Map<string, DayRange[]>();+ for (const p of pageMeta) datesBySlug.set(p.slug, extractEventDates(bodyOf(p.content), datasetDay(p.date)));+ const scoped = applyTimeScope(distinct(pool), parsed.range, r => datesBySlug.get(r.slug), { mode, k });+ row.time_scope.in_range = scoped.inRange;+ row.time_scope.moved = scoped.moved;+ return { results: scoped.results.slice(0, k), row };+}++/** Parsed `--fact-keys*` / `--time-scope*` options (eval-only arms). */+export interface RetrievalArmOptions {+ factKeys?: FactKeyAssignment;+ factExtractor: FactExtractor;+ factKeysModel?: string;+ factKeysMaxUsd: number;+ timeScope?: TimeScopeMode;+ timeScopePool: number;+}++export function newRetrievalArmOptions(): RetrievalArmOptions {+ return { factExtractor: 'paper', factKeysMaxUsd: 20, timeScopePool: 50 };+}++export const LME_RETRIEVAL_ARM_FLAGS: Array<{ name: string; arg?: string; help: string[]; apply: (o: { arms: RetrievalArmOptions }, value: string) => void }> = [+ { name: '--fact-keys', arg: 'chunk|page', help: [+ 'Eval-only arm: merge each session\'s extracted facts into the embedding',+ 'input of its chunks (chunk = each fact on its best-matching chunk; page =',+ 'all facts on every chunk) and re-embed. Retrieval still returns raw sessions.'],+ apply: (o, v) => { if (v !== 'chunk' && v !== 'page') throw new Error(`--fact-keys must be chunk|page (got: ${v})`); o.arms.factKeys = v; } },+ { name: '--fact-extractor', arg: 'paper|production', help: [+ 'Fact source for --fact-keys: paper = the benchmark\'s published user-turn',+ 'fact prompt; production = gbrain\'s facts extractor as shipped (default: paper).'],+ apply: (o, v) => { if (v !== 'paper' && v !== 'production') throw new Error(`--fact-extractor must be paper|production (got: ${v})`); o.arms.factExtractor = v; } },+ { name: '--fact-keys-model', arg: 'MODEL', help: ['Extraction model for --fact-keys (default: the utility tier, haiku).'],+ apply: (o, v) => { o.arms.factKeysModel = v; } },+ { name: '--fact-keys-max-usd', arg: 'N', help: ['Spend cap for uncached fact extraction (default 20). Cached extractions are free.'],+ apply: (o, v) => { const n = Number(v); if (!Number.isFinite(n) || n <= 0) throw new Error(`--fact-keys-max-usd must be a positive number (got: ${v})`); o.arms.factKeysMaxUsd = n; } },+ { name: '--time-scope', arg: 'reserved|partition', help: [+ 'Eval-only arm: re-order a widened pool by the question\'s explicit time range',+ '(resolved against question_date) using each session\'s observation and',+ 'mentioned dates. reserved keeps the top half of k in place; partition',+ 'moves every in-range session first. Rows also carry the unscoped top-k.'],+ apply: (o, v) => { if (v !== 'reserved' && v !== 'partition') throw new Error(`--time-scope must be reserved|partition (got: ${v})`); o.arms.timeScope = v; } },+ { name: '--time-scope-pool', arg: 'N', help: ['Candidate pool depth for --time-scope (default 50).'],+ apply: (o, v) => { const n = Number(v); if (!Number.isInteger(n) || n < 1 || n > 300) throw new Error(`--time-scope-pool must be an integer from 1 to 300 (got: ${v})`); o.arms.timeScopePool = n; } },+];++/** Folds active arms into retrieval_config_hash; empty when no arm is on (existing receipts keep their hash). */+export function armPins(o: RetrievalArmOptions): { retrieval_arms?: Record<string, unknown> } {+ const pins: Record<string, unknown> = {};+ if (o.factKeys) Object.assign(pins, { fact_keys: o.factKeys, fact_extractor: o.factExtractor, fact_keys_model: o.factKeysModel ?? 'utility-tier' });+ if (o.timeScope) Object.assign(pins, { time_scope: o.timeScope, time_scope_pool: o.timeScopePool });+ return Object.keys(pins).length > 0 ? { retrieval_arms: pins } : {};+}++export async function resolveFactKeyArm(o: RetrievalArmOptions, client: ThinkLLMClient): Promise<{ arm: FactKeyArm; spend: FactKeySpend } | null> {+ if (!o.factKeys) return null;+ const model = o.factExtractor === 'production' && !o.factKeysModel+ ? await resolveModel(null, { configKey: 'facts.extraction_model', tier: 'reasoning', fallback: 'anthropic:claude-sonnet-4-6' })+ : await resolveModel(null, { cliFlag: o.factKeysModel, tier: 'utility', fallback: 'haiku' });+ return { arm: { assignment: o.factKeys, extractor: o.factExtractor, model, client, maxUsd: o.factKeysMaxUsd }, spend: new FactKeySpend(o.factKeysMaxUsd) };+}++/** Row fields for a time-scope run: the decision, plus the unscoped top-k's recall from the same pool. */+export function timeScopeRowExtras(row: TimeScopeArmRow, slugToRaw: SlugToRawMap, gold: readonly string[], k: number): Record<string, unknown> {+ const unscopedRaw = row.unscoped_slugs.map(s => rawSessionId(s, slugToRaw));+ const score = gold.length > 0 ? scoreRecall(unscopedRaw, gold, k) : null;+ return {+ time_scope: row.time_scope,+ unscoped_retrieved_session_ids: unscopedRaw,+ ...(score ? { unscoped_recall_all_hit: score.recall_all_hit, unscoped_recall_any_hit: score.recall_any_hit } : {}),+ };+}diff --git a/src/eval/longmemeval/run-config.ts b/src/eval/longmemeval/run-config.tsindex 9ca366808b..3938f2a4e6 100644--- a/src/eval/longmemeval/run-config.ts+++ b/src/eval/longmemeval/run-config.ts@@ -52,6 +52,8 @@ export interface RetrievalPins {eval_pool_depth?: number;/** System One arm (`--decide`): slots, provider, calibrations, thresholds, force_on, split. Present only when a slot is on or shadow. */decide?: Record<string, unknown>;+ /** Eval-only fact-key / time-scope arms (retrieval-arms.ts). Present only when an arm is on. */+ retrieval_arms?: Record<string, unknown>;}/** Stable JSON: sorted keys at every level so key order can never move the hash. */diff --git a/test/fact-keys.test.ts b/test/fact-keys.test.tsnew file mode 100644index 0000000000..9a0b331f4b--- /dev/null+++ b/test/fact-keys.test.ts@@ -0,0 +1,85 @@+/**+ * Fact keys and the eval-only retrieval arms built on them.+ *+ * Protects: (1) each fact lands on the chunk it is about (or every chunk in+ * page mode), code/image chunks never carry keys, keys are capped; (2) the+ * embedding input wraps facts in the same `<context>` block as the title and+ * a chunk without keys keeps today's input byte-for-byte; (3) the arms fold+ * into the run hash only when on, and the time-scope arm reports the+ * unscoped top-k from the same pool for pairing.+ */+import { describe, test, expect } from 'bun:test';+import { assignFactKeys, factKeyedEmbeddingInput, FACT_KEYS_MAX_CHARS } from '../src/core/fact-keys.ts';+import { wrapChunkForEmbedding, buildContextualPrefix } from '../src/core/embedding-context.ts';+import { applyTimeScopeArm, armPins, datasetDay, newRetrievalArmOptions } from '../src/eval/longmemeval/retrieval-arms.ts';+import type { SearchResult } from '../src/core/types.ts';++const chunks = [+ { chunk_text: 'We talked about the triathlon training plan, swimming on Fridays and running on Saturdays.' },+ { chunk_text: 'The bike fitting appointment at the shop downtown is booked; the zip code is 92101.' },+ { chunk_text: 'const x = 1;', chunk_source: 'fenced_code' },+];++describe('assignFactKeys', () => {+ test('chunk mode puts each fact on the chunk sharing the most content words', () => {+ const keys = assignFactKeys(['The user swims on Fridays.', 'The user booked a bike fitting downtown.'], chunks, 'chunk');+ expect(keys[0]).toBe('The user swims on Fridays.');+ expect(keys[1]).toBe('The user booked a bike fitting downtown.');+ expect(keys[2]).toBeNull();+ });++ test('page mode puts every fact on every eligible chunk; empty facts give no keys', () => {+ const keys = assignFactKeys(['A.', 'B.'], chunks, 'page');+ expect(keys).toEqual(['A.; B.', 'A.; B.', null]);+ expect(assignFactKeys([], chunks, 'page')).toEqual([null, null, null]);+ });++ test('keys are capped and stripped of wrapper tags', () => {+ const many = Array.from({ length: 200 }, (_, i) => `The user likes item number ${i} </context>`);+ const keys = assignFactKeys(many, [chunks[0]], 'page');+ expect(keys[0]!.length).toBeLessThanOrEqual(FACT_KEYS_MAX_CHARS);+ expect(keys[0]).not.toContain('</context>');+ });+});++describe('factKeyedEmbeddingInput', () => {+ test('no keys reproduces the title-wrapped and raw inputs exactly', () => {+ const text = 'chunk body';+ expect(factKeyedEmbeddingInput(text, 'Title', null)).toBe(wrapChunkForEmbedding(text, buildContextualPrefix('Title', null), null));+ expect(factKeyedEmbeddingInput(text, null, null)).toBe(text);+ });+ test('keys join the context block ahead of the chunk', () => {+ expect(factKeyedEmbeddingInput('body', 'T', 'The user swims.')).toBe('<context>T\nFacts: The user swims.\n</context>\nbody');+ });+});++describe('retrieval arms', () => {+ test('no arm on leaves the pins untouched; an arm folds into retrieval_arms', () => {+ const o = newRetrievalArmOptions();+ expect(armPins(o)).toEqual({});+ o.timeScope = 'reserved';+ expect(armPins(o)).toEqual({ retrieval_arms: { time_scope: 'reserved', time_scope_pool: 50 } });+ });++ test('datasetDay reads the dataset date format', () => {+ expect(datasetDay('2023/05/20 (Sat) 02:21')).toBe('2023-05-20');+ expect(datasetDay(undefined)).toBeNull();+ });++ test('time scope returns scoped and unscoped top-k from one pool', () => {+ const pool = ['s1', 's2', 's3', 's4'].map(slug => ({ slug }) as SearchResult);+ const meta = [+ { slug: 's1', content: 'hello', date: '2023/01/05 (Thu) 10:00' },+ { slug: 's2', content: 'hello', date: '2023/02/05 (Sun) 10:00' },+ { slug: 's3', content: 'hello', date: '2023/04/05 (Wed) 10:00' },+ { slug: 's4', content: 'hello', date: '2023/04/09 (Sun) 10:00' },+ ];+ const out = applyTimeScopeArm(pool, { question: 'What did I buy last month?', question_date: '2023/05/02 (Tue) 09:00' }, meta, 'reserved', 2);+ expect(out.row.unscoped_slugs).toEqual(['s1', 's2']);+ expect(out.results.map(r => r.slug)).toEqual(['s1', 's3']);+ expect(out.row.time_scope.reason).toBe('applied');+ const none = applyTimeScopeArm(pool, { question: 'What did I buy?', question_date: '2023/05/02 (Tue) 09:00' }, meta, 'reserved', 2);+ expect(none.results.map(r => r.slug)).toEqual(['s1', 's2']);+ expect(none.row.time_scope.reason).toBe('no_cue');+ });+});diff --git a/test/fixtures/goldens/cli/tools-json.json b/test/fixtures/goldens/cli/tools-json.jsonindex 8c613f7b27..b309d84b35 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": 196835,- "stdoutSha256": "7c6a8f58d1ecf9152a0bef45fe6b85d84ea6bc81c4610fc65b2a65eeec68370a",+ "stdoutBytes": 197396,+ "stdoutSha256": "bab9dd03319eebafdc9dad4120ae80519e7d200b71f661e14b1811ad280fabdc","toolNames": ["remember","entity",@@ -3608,6 +3608,8 @@"anchor": "string?","model": "string?","question": "string",+ "reading_notes": "string?",+ "reference_date": "string?","rounds": "number?","save": "boolean?","since": "string?",@@ -3629,6 +3631,19 @@"description": "The question to think about","type": "string"},+ "reading_notes": {+ "description": "Notes-first reading for this call (default: think.reading_notes). Notes return in reading_notes, never in the answer.",+ "enum": [+ "on",+ "off",+ "auto"+ ],+ "type": "string"+ },+ "reference_date": {+ "description": "YYYY-MM-DD the question's relative time words resolve against (default: today in brain.timezone).",+ "type": "string"+ },"rounds": {"description": "Multi-pass: 1 (default). Round-loop scaffolding is in place; gap-driven retrieval ships in v0.29.","type": "number"diff --git a/test/fixtures/goldens/exports/types.json b/test/fixtures/goldens/exports/types.jsonindex fb4aa5732c..84009dc47d 100644--- a/test/fixtures/goldens/exports/types.json+++ b/test/fixtures/goldens/exports/types.json@@ -7104,6 +7104,8 @@"model?: string | undefined","modelExplicit?: boolean | undefined","question: string",+ "readingNotes?: ThinkReadingNotesMode | undefined",+ "referenceDate?: string | undefined","remote?: boolean | undefined","rounds?: number | undefined","save?: boolean | undefined",@@ -7125,12 +7127,20 @@],"name": "ThinkLLMClient"},+ {+ "kind": "type",+ "name": "ThinkReadingNotesMode",+ "signature": [+ "\"on\" | \"off\" | \"auto\""+ ]+ },{"kind": "interface","members": ["answer: string","citations: { page_slug: string; row_num: number | null; citation_index?: number; }[]",- "gaps: string[]"+ "gaps: string[]",+ "notes?: string | undefined"],"name": "ThinkResponse"},@@ -7149,11 +7159,13 @@"modelUsed: string","pagesGathered: number","question: string",+ "reading_notes?: { mode: \"on\" | \"off\"; notes: string | null; } | undefined","rounds: number","savedSlug?: string | undefined","synthesisOk?: boolean | undefined","synthesis_status?: ThinkSynthesisStatus | undefined","takesGathered: number",+ "temporal?: { reference_date: string; time_zone: string; } | undefined","usage?: { input_tokens: number; output_tokens: number; } | null | undefined","warnings: string[]"],diff --git a/test/think-reading.test.ts b/test/think-reading.test.tsnew file mode 100644index 0000000000..5687b3da47--- /dev/null+++ b/test/think-reading.test.ts@@ -0,0 +1,184 @@+/**+ * think reads in a date frame and can take notes before answering.+ *+ * Protects: (1) the reader sees the current/reference date and each page's+ * content date, never a fallback row timestamp; (2) relative dates in a page+ * render in the brain's timezone; (3) notes-first reading puts its notes in+ * `reading_notes`, never in the answer or the persisted body, and raises the+ * output allowance; (4) invalid reference dates are refused.+ * Regression it catches: a reader answering "last month" questions with no+ * idea what today is, or notes leaking into saved syntheses.+ * Existing coverage: think-pipeline/think-pages-block tests never assert dates+ * or a notes field.+ */+import { describe, test, expect, beforeAll, afterAll } from 'bun:test';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { importFromContent } from '../src/core/import-file.ts';+import { runThink, type ThinkLLMClient } from '../src/core/think/index.ts';+import { renderPagesBlock } from '../src/core/think/gather.ts';+import { buildThinkSystemPrompt, buildThinkUserMessage, THINK_READING_NOTES_INSTRUCTION } from '../src/core/think/prompt.ts';+import { pageContentDate, parseReferenceDate, ReferenceDateError } from '../src/core/think/temporal-context.ts';+import type { SearchResult } from '../src/core/types.ts';++let engine: PGLiteEngine;++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ const imported = await importFromContent(engine, 'meetings/acme-example-pricing',+ '---\ntitle: Acme pricing review\ntype: meeting\ndate: 2026-09-15\n---\n\nWe agreed the enterprise plan costs 125 credits per month. Yesterday the team shipped the new invoice flow.',+ { noEmbed: true, sourceId: 'default' });+ expect(imported.status).toBe('imported');+});++afterAll(async () => {+ await engine.disconnect();+});++function stub(text: string, capture: { system?: string; user?: string; maxTokens?: number }, stopReason = 'end_turn'): ThinkLLMClient {+ return {+ create: async (params) => {+ capture.system = typeof params.system === 'string' ? params.system : JSON.stringify(params.system);+ const content = params.messages[0]?.content;+ capture.user = typeof content === 'string' ? content : JSON.stringify(content);+ capture.maxTokens = params.max_tokens;+ return {+ id: 'msg_reading', type: 'message', role: 'assistant', model: 'stub',+ stop_reason: stopReason, stop_sequence: null,+ usage: { input_tokens: 1, output_tokens: 1, cache_creation_input_tokens: 0, cache_read_input_tokens: 0, server_tool_use: null, service_tier: null },+ content: [{ type: 'text', text }],+ } as never;+ },+ };+}++describe('pageContentDate', () => {+ test('content-date sources render; fallback and created sources do not', () => {+ expect(pageContentDate({ effective_date: '2026-09-15T00:00:00.000Z', effective_date_source: 'date' }, 'UTC')).toBe('2026-09-15');+ expect(pageContentDate({ effective_date: '2026-09-15T00:00:00.000Z', effective_date_source: 'fallback' }, 'UTC')).toBeNull();+ expect(pageContentDate({ effective_date: '2026-09-15T00:00:00.000Z', effective_date_source: 'created' }, 'UTC')).toBeNull();+ expect(pageContentDate({ effective_date: null, effective_date_source: 'date' }, 'UTC')).toBeNull();+ });++ test('a timestamped date renders in the brain timezone; a day-only date renders as written', () => {+ expect(pageContentDate({ effective_date: new Date('2023-05-20T02:21:00Z'), effective_date_source: 'date' }, 'America/Los_Angeles')).toBe('2023-05-19');+ expect(pageContentDate({ effective_date: new Date('2023-05-20T00:00:00Z'), effective_date_source: 'date' }, 'America/Los_Angeles')).toBe('2023-05-20');+ });+});++describe('parseReferenceDate', () => {+ const now = new Date('2026-10-04T12:00:00Z');+ test('accepts a past or current calendar day', () => {+ expect(parseReferenceDate('2023-05-30', 'UTC', now)).toBe('2023-05-30');+ expect(parseReferenceDate('2026-10-05', 'UTC', now)).toBe('2026-10-05');+ });+ test('refuses malformed, impossible and future dates', () => {+ expect(() => parseReferenceDate('2023/05/30', 'UTC', now)).toThrow(ReferenceDateError);+ expect(() => parseReferenceDate('2023-02-30', 'UTC', now)).toThrow(ReferenceDateError);+ expect(() => parseReferenceDate('2027-01-01', 'UTC', now)).toThrow(ReferenceDateError);+ });+});++describe('prompt shape', () => {+ test('page blocks carry content dates only', () => {+ const pages = [+ { slug: 'meetings/a', chunk_text: 'x', effective_date: '2026-09-15T00:00:00.000Z', effective_date_source: 'date' },+ { slug: 'notes/b', chunk_text: 'y', effective_date: '2026-09-20T10:00:00.000Z', effective_date_source: 'fallback' },+ ] as unknown as SearchResult[];+ const block = renderPagesBlock(pages, 100, '', { verbatim: true, timeZone: 'UTC' });+ expect(block).toContain('<page slug="meetings/a" rank="1" date="2026-09-15">');+ expect(block).toContain('<page slug="notes/b" rank="2">');+ });++ test('the current date sits just before the question in both message shapes; the system text stays date-free', () => {+ const plain = buildThinkUserMessage({ question: 'q?', pagesBlock: 'p', takesBlock: 't', currentDate: '2026-10-04 (UTC)' });+ expect(plain).toContain('Current date: 2026-10-04 (UTC)\nQuestion: q?');+ const calibrated = buildThinkUserMessage({+ question: 'q?', pagesBlock: 'p', takesBlock: 't', currentDate: '2026-10-04 (UTC)',+ calibration: { holder: 'garry', patternStatements: [], activeBiasTags: [] },+ });+ expect(calibrated).toContain('Current date: 2026-10-04 (UTC)\nQuestion: q?');+ const system = buildThinkSystemPrompt({ currentDate: true, readingNotes: true });+ expect(system).toContain('date="YYYY-MM-DD"');+ expect(system).toContain(THINK_READING_NOTES_INSTRUCTION);+ expect(system).not.toMatch(/\d{4}-\d{2}-\d{2}/);+ });+});++describe('runThink reading', () => {+ test('reference date and page date reach the reader; notes stay off by default', async () => {+ const cap: { system?: string; user?: string; maxTokens?: number } = {};+ const result = await runThink(engine, {+ question: 'What does the enterprise plan cost at acme-example?',+ client: stub(JSON.stringify({ answer: '125 credits per month [meetings/acme-example-pricing]', citations: [], gaps: [] }), cap),+ withTrajectory: false, remote: false, referenceDate: '2026-10-01',+ });+ expect(cap.user).toContain('Current date: 2026-10-01 (UTC)');+ expect(cap.user).toContain('date="2026-09-15"');+ expect(cap.system).not.toContain(THINK_READING_NOTES_INSTRUCTION);+ expect(result.temporal).toEqual({ reference_date: '2026-10-01', time_zone: 'UTC' });+ expect(result.reading_notes).toEqual({ mode: 'off', notes: null });+ });++ test('notes-first reading: notes come back separately, never in the answer, with extra output allowance', async () => {+ const offCap: { maxTokens?: number } = {};+ await runThink(engine, {+ question: 'What does the enterprise plan cost at acme-example?',+ client: stub(JSON.stringify({ answer: 'a', citations: [], gaps: [] }), offCap),+ withTrajectory: false, remote: false, readingNotes: 'off',+ });+ const cap: { system?: string; maxTokens?: number } = {};+ const result = await runThink(engine, {+ question: 'What does the enterprise plan cost at acme-example?',+ client: stub(JSON.stringify({ notes: '[meetings/acme-example-pricing] 2026-09-15: enterprise = 125 credits/month', answer: '125 credits per month.', citations: [], gaps: [] }), cap),+ withTrajectory: false, remote: false, readingNotes: 'on',+ });+ expect(cap.system).toContain(THINK_READING_NOTES_INSTRUCTION);+ expect(cap.maxTokens).toBe((offCap.maxTokens ?? 0) + 512);+ expect(result.answer).toBe('125 credits per month.');+ expect(result.answer).not.toContain('2026-09-15');+ expect(result.reading_notes?.mode).toBe('on');+ expect(result.reading_notes?.notes).toContain('125 credits/month');+ });++ test('think.reading_notes=auto turns notes on for temporal questions only', async () => {+ await engine.setConfig('think.reading_notes', 'auto');+ try {+ const temporalCap: { system?: string } = {};+ await runThink(engine, {+ question: 'When did the team ship the invoice flow?',+ client: stub(JSON.stringify({ answer: 'a', citations: [], gaps: [] }), temporalCap),+ withTrajectory: false, remote: false,+ });+ expect(temporalCap.system).toContain(THINK_READING_NOTES_INSTRUCTION);+ const plainCap: { system?: string } = {};+ await runThink(engine, {+ question: 'What does the enterprise plan cost at acme-example?',+ client: stub(JSON.stringify({ answer: 'a', citations: [], gaps: [] }), plainCap),+ withTrajectory: false, remote: false,+ });+ expect(plainCap.system).not.toContain(THINK_READING_NOTES_INSTRUCTION);+ } finally {+ await engine.setConfig('think.reading_notes', 'off');+ }+ });++ test('a truncated notes-first response is not a successful synthesis', async () => {+ const result = await runThink(engine, {+ question: 'What does the enterprise plan cost at acme-example?',+ client: stub('{"notes": "[meetings/acme-example-pricing] enterprise plan costs 125 cre', {}, 'max_tokens'),+ withTrajectory: false, remote: false, readingNotes: 'on',+ });+ expect(result.synthesisOk).toBe(false);+ expect(result.warnings).toContain('READING_NOTES_TRUNCATED');+ expect(result.answer).not.toContain('enterprise plan costs');+ });++ test('a future reference date is refused before any model call', async () => {+ let called = false;+ const client: ThinkLLMClient = { create: async () => { called = true; throw new Error('unreachable'); } };+ await expect(runThink(engine, { question: 'q', client, remote: false, referenceDate: '2999-01-01' })).rejects.toThrow(ReferenceDateError);+ expect(called).toBe(false);+ });+});diff --git a/test/time-range-parse.test.ts b/test/time-range-parse.test.tsnew file mode 100644index 0000000000..5a890b3b25--- /dev/null+++ b/test/time-range-parse.test.ts@@ -0,0 +1,93 @@+/**+ * The query time-range grammar, frozen before any dev-split scoring. Golden+ * cases are the published LongMemEval time-range examples (question date →+ * expected range, or no range) plus generic English expressions; they were+ * not drawn from benchmark questions.+ *+ * Protects: explicit time cues resolve to the right calendar range against+ * the reference day, and questions without an explicit cue (or asking for a+ * duration, or naming two times in different roles) produce no range — a+ * false range would hide the right evidence.+ */+import { describe, test, expect } from 'bun:test';+import { parseQueryTimeRange } from '../src/core/search/time-range.ts';+import { findTimeMentions } from '../src/core/temporal-grammar.ts';++function range(q: string, ref: string) {+ const r = parseQueryTimeRange(q, ref);+ return r.range ? [r.range.start, r.range.end] : r.reason;+}++describe('published time-range examples', () => {+ test('ranges the examples expect', () => {+ expect(range('What was the date on which I attended the first BBQ event in June?', '2023-07-01')).toEqual(['2023-06-01', '2023-06-30']);+ expect(range('Where did I attend the religious activity last week?', '2023-04-10')).toEqual(['2023-04-03', '2023-04-09']);+ expect(range('Which pair of shoes did I clean last month?', '2023-05-30')).toEqual(['2023-04-01', '2023-04-30']);+ expect(range('Which airline did I fly with the most in March and April?', '2023-04-27')).toEqual(['2023-03-01', '2023-04-30']);+ const twoMonths = parseQueryTimeRange('What did I do with Rachel on the Wednesday two months ago?', '2023-04-01').range!;+ expect(twoMonths.start <= '2023-02-01' && twoMonths.end >= '2023-02-01').toBe(true);+ expect(twoMonths.start >= '2023-01-20' && twoMonths.end <= '2023-02-10').toBe(true);+ const lastTue = parseQueryTimeRange('Who did I meet with during the lunch last Tuesday?', '2023-04-18').range!;+ expect([lastTue.start, lastTue.end]).toEqual(['2023-04-11', '2023-04-11']);+ });++ test('questions the examples mark as having no time range', () => {+ expect(range('How many months ago did I book the Airbnb in San Francisco?', '2023-05-27')).toBe('no_cue');+ expect(range('How long have I been using my Fitbit Charge 3?', '2023-09-04')).toBe('no_cue');+ expect(range('How many bikes do I currently own?', '2023-10-27')).toBe('no_cue');+ expect(range('What was the amount I was pre-approved for when I got my mortgage from Wells Fargo?', '2023-12-18')).toBe('no_cue');+ expect(range('How many engineers do I lead when I just started my new role as Senior Software Engineer? How many engineers do I lead now?', '2023-11-10')).toBe('no_cue');+ expect(range('How long had I been taking guitar lessons when I bought the new guitar amp?', '2023-05-28')).toBe('no_cue');+ expect(range("How many days before the 'Rack Fest' did I participate in the 'Turbocharged Tuesdays' event?", '2023-06-28')).toBe('no_cue');+ });+});++describe('generic English', () => {+ const ref = '2026-10-04'; // a Sunday+ test.each([+ ['what happened yesterday', ['2026-10-03', '2026-10-03']],+ ['notes from this week', ['2026-09-28', '2026-10-04']],+ ['what did we decide last weekend', ['2026-09-26', '2026-09-27']],+ ['what did I read last year', ['2025-01-01', '2025-12-31']],+ ['plans for next month', ['2026-11-01', '2026-11-30']],+ ['the call last Friday', ['2026-10-02', '2026-10-02']],+ ['what changed in the past month', ['2026-09-04', '2026-10-04']],+ ['revenue in Q3 2022', ['2022-07-01', '2022-09-30']],+ ['the offsite in 2022', ['2022-01-01', '2022-12-31']],+ ['the launch on March 15th', ['2026-03-15', '2026-03-15']],+ ['the dinner on 2 May 2024', ['2024-05-02', '2024-05-02']],+ ['the board meeting in December', ['2025-12-01', '2025-12-31']],+ ['what we shipped last summer', ['2026-06-01', '2026-08-31']],+ ['between May and July 2025', ['2025-05-01', '2025-07-31']],+ ])('%s', (q, want) => {+ expect(range(q, ref)).toEqual(want);+ });++ test('a weekday-named day resolves to the most recent one strictly before the reference day', () => {+ expect(range('the lunch last Sunday', '2026-10-04')).toEqual(['2026-09-27', '2026-09-27']);+ });++ test('two separate times in different roles abstain; duration questions abstain', () => {+ expect(range('Which June deadline did we cancel in May?', ref)).toBe('multi_role');+ expect(range('How many days ago did I read the March 15th issue?', ref)).toBe('duration_question');+ expect(range('How many weeks passed between the fair in May and the trip?', ref)).toBe('duration_question');+ expect(range('How many days did I spend hiking this year?', ref)).toEqual(['2026-01-01', '2026-12-31']);+ });++ test('modal "may", plurals and quoted names are not dates', () => {+ expect(range('What may I bring to the party?', ref)).toBe('no_cue');+ expect(range('I go to yoga on Tuesdays', ref)).toBe('no_cue');+ expect(range('Did I like "Last Summer" the movie?', ref)).toBe('no_cue');+ });+});++describe('content mentions resolve against the page date', () => {+ test('relative phrases in a dated page', () => {+ const m = findTimeMentions('I missed a 5K fun run on March 26th. Yesterday I booked a bike fitting for next week.', '2023-04-02', 'past');+ expect(m.map(x => [x.cue, x.start, x.end])).toEqual([+ ['March 26th', '2023-03-26', '2023-03-26'],+ ['Yesterday', '2023-04-01', '2023-04-01'],+ ['next week', '2023-04-03', '2023-04-09'],+ ]);+ });+});diff --git a/test/time-scope-stage.test.ts b/test/time-scope-stage.test.tsnew file mode 100644index 0000000000..2bf040f2af--- /dev/null+++ b/test/time-scope-stage.test.ts@@ -0,0 +1,69 @@+/**+ * Soft time scope and content date extraction.+ *+ * Protects: (1) the reserved contract never displaces the top ⌈k/2⌉ baseline+ * results and never drops a result; (2) partition is the paper's full+ * reorder; (3) no in-range result leaves the order untouched; (4) relative+ * content dates need a known observation date, and code/URLs never yield+ * dates. Regression it catches: a time scope that evicts the best unscoped+ * evidence, or version strings indexed as event dates.+ */+import { describe, test, expect } from 'bun:test';+import { applyTimeScope } from '../src/core/search/hybrid/time-scope.ts';+import { extractEventDates } from '../src/core/event-dates.ts';++type R = { id: string; dates: Array<{ start: string; end: string }> };+const day = (d: string) => [{ start: d, end: d }];+const pool: R[] = [+ { id: 'a', dates: day('2023-01-10') },+ { id: 'b', dates: day('2023-02-10') },+ { id: 'c', dates: day('2023-04-05') },+ { id: 'd', dates: day('2023-01-11') },+ { id: 'e', dates: day('2023-04-02') },+ { id: 'f', dates: [] },+];+const april = { start: '2023-04-01', end: '2023-04-30' };++describe('applyTimeScope', () => {+ test('reserved keeps the top ⌈k/2⌉ in place and fills the rest of k with in-range results', () => {+ const out = applyTimeScope(pool, april, r => r.dates, { mode: 'reserved', k: 4 });+ expect(out.results.map(r => r.id)).toEqual(['a', 'b', 'c', 'e', 'd', 'f']);+ expect(out.inRange).toBe(2);+ });++ test('partition moves every in-range result first', () => {+ const out = applyTimeScope(pool, april, r => r.dates, { mode: 'partition', k: 4 });+ expect(out.results.map(r => r.id)).toEqual(['c', 'e', 'a', 'b', 'd', 'f']);+ });++ test('slack widens the range by two days on each side by default', () => {+ const out = applyTimeScope(pool, { start: '2023-02-12', end: '2023-02-20' }, r => r.dates, { mode: 'partition', k: 4 });+ expect(out.results[0].id).toBe('b');+ const tight = applyTimeScope(pool, { start: '2023-02-12', end: '2023-02-20' }, r => r.dates, { mode: 'partition', k: 4, slackDays: 0 });+ expect(tight.inRange).toBe(0);+ });++ test('no in-range result returns the input order, and every mode is a permutation', () => {+ const none = applyTimeScope(pool, { start: '2020-01-01', end: '2020-01-31' }, r => r.dates, { mode: 'reserved', k: 4 });+ expect(none.results.map(r => r.id)).toEqual(pool.map(r => r.id));+ expect(none.moved).toBe(0);+ for (const mode of ['reserved', 'partition'] as const) {+ const out = applyTimeScope(pool, april, r => r.dates, { mode, k: 3 });+ expect([...out.results].map(r => r.id).sort()).toEqual(pool.map(r => r.id).sort());+ }+ });+});++describe('extractEventDates', () => {+ test('relative phrases resolve against the observation date; absolute dates always resolve', () => {+ const dated = extractEventDates('Yesterday I finished the book. The launch was on 2023-03-01.', '2023-04-02');+ expect(dated.map(d => [d.origin, d.start])).toEqual([['observation', '2023-04-02'], ['relative', '2023-04-01'], ['mention', '2023-03-01']]);+ const undated = extractEventDates('Yesterday I finished the book. The launch was on 2023-03-01.', null);+ expect(undated.map(d => [d.origin, d.start])).toEqual([['mention', '2023-03-01']]);+ });++ test('code and URLs yield no dates', () => {+ const out = extractEventDates('Run `migrate --since 2021-01-01` and see https://example.com/2020/05/01/post\n```\nreleased 2019-02-03\n```', null);+ expect(out).toEqual([]);+ });+});