Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
Merge origin/master (43b0adb69: #6112 P6 time-aware reading) into capy/mpw-integration; one date rule
garrytanf72efd18c44a
diff --cc docs/architecture/key-files/core-search-2.mdindex 6d9d3db8dd,69558540ec..d20a1cfe34--- a/docs/architecture/key-files/core-search-2.md+++ b/docs/architecture/key-files/core-search-2.md@@@ -3,13 -3,7 +3,13 @@@[Subsystem index](../KEY_FILES.md). Read only the entries relevant to your change.Current behavior and load-bearing invariants; history belongs in Git and CHANGELOG.-- `src/core/search/evidence-delivery.ts` — the `return_unit` evidence assembler (default `auto`: conversation pages by type or `chat/`/`conversations/` slug come back whole under `search.return_budget_conversation` (24,000), every other hit is its unchanged chunk; `effectivePlan` skips the stage when an implied `auto` sees no conversation hit, so that path and `chunk` stay byte-identical). `resolveEvidencePlan` validates `return_unit` / `return_window` (invalid_params naming the allowed values and an example), reads `search.return_unit` / `think.return_unit`, `search.return_window`, `search.return_budget_default` (6,000), `search.return_budget_conversation` (24,000) and clamps remote budgets to `search.return_budget_max_remote` (32,000, reported). Snippet precedence: explicit `snippet_chars` > explicit `return_unit` > subagent default cap > config unit. `deliverEvidence` groups hits by page_id (one block per page at its best rank), makes ONE `engine.getChunkWindows` call (re-authorizes every page; unauthorized pages are dropped, never served from hit text), builds the page text from the stored body sanitized whole and passed through `credentialSafeProjection` before slicing (`pageEvidenceText`: compiled truth + serializer timeline sentinel + timeline; frontmatter excluded; private-key spans become newline-padded `<REDACTED:private_key_pem>` tokens, the same text the chunkers cut from), locates the hit chunks in it (`locateChunks`: exact, then whitespace-insensitive, since the chunker trims and folds whitespace), cuts `window` / `section` (ATX headings outside code fences, or conversation rounds detected structurally, never by page type) / `page` / `auto` (fenced-code hits are placed by their code minus the chunker's synthesized header), counts tokens as the sum of per-line cl100k counts, reserves each page's matching span before enriching by rank, caps blocks at 60,000 characters, redacts secrets before final accounting, and returns NEW rows with `delivered` plus a `delivery` meta. Fetch failure/timeout (5 s) falls back to the hit chunk only for live hits. `assembleEvidenceForHits` / op `assemble_evidence` deliver the exact evidence `query` returns for a frozen `(source_id, slug, chunk_id)` list; `evidenceFingerprint` hashes it (gbrain-evals E1/E3 parity). Normative spec: `docs/evidence-delivery.md`. Tests: `test/evidence-delivery.test.ts`, `test/evidence-delivery-golden.test.ts`, `test/e2e/evidence-delivery-leak.test.ts`, `test/e2e/evidence-delivery-parity.test.ts`; bench `scripts/bench-evidence-delivery.ts`.+- `src/core/search/evidence-delivery.ts` — the `return_unit` evidence assembler (default `auto`: conversation pages by type or `chat/`/`conversations/` slug come back whole under `search.return_budget_conversation` (24,000), every other hit is its unchanged chunk; `effectivePlan` skips the stage when an implied `auto` sees no conversation hit, so that path and `chunk` stay byte-identical). `resolveEvidencePlan` validates `return_unit` / `return_window` (invalid_params naming the allowed values and an example), reads `search.return_unit` / `think.return_unit`, `search.return_window`, `search.return_budget_default` (6,000), `search.return_budget_conversation` (24,000) and clamps remote budgets to `search.return_budget_max_remote` (32,000, reported). Snippet precedence: explicit `snippet_chars` > explicit `return_unit` > subagent default cap > config unit. `deliverEvidence` groups hits by page_id (one block per page at its best rank), makes ONE `engine.getChunkWindows` call (re-authorizes every page; unauthorized pages are dropped, never served from hit text), builds the page text from the stored body sanitized whole and passed through `credentialSafeProjection` before slicing (`pageEvidenceText`: compiled truth + serializer timeline sentinel + timeline; frontmatter excluded; private-key spans become newline-padded `<REDACTED:private_key_pem>` tokens, the same text the chunkers cut from), locates the hit chunks in it (`locateChunks`: exact, then whitespace-insensitive, since the chunker trims and folds whitespace), cuts `window` / `section` (ATX headings outside code fences, or conversation rounds detected structurally, never by page type) / `page` / `auto` (fenced-code hits are placed by their code minus the chunker's synthesized header), counts tokens as the sum of per-line cl100k counts, reserves each page's matching span before enriching by rank, caps blocks at 60,000 characters, redacts secrets before final accounting, and returns NEW rows with `delivered` plus a `delivery` meta. Fetch failure/timeout (5 s) falls back to the hit chunk only for live hits. `assembleEvidenceForHits` / op `assemble_evidence` deliver the exact evidence `query` returns for a frozen `(source_id, slug, chunk_id)` list; `evidenceFingerprint` hashes it (gbrain-evals E1/E3 parity). With `search.evidence_date_header` on (`plan.dateHeader`), each block (including `auto` passthrough chunks) starts with its one-line date header from `evidence-date.ts`, reserved in the block floor like the title, counted in `delivered.tokens`, with spans shifted past it and `delivery.date_header: true`; a failed date read renders `unknown` and adds `date_header_unavailable`. Normative spec: `docs/evidence-delivery.md`. Tests: `test/evidence-delivery.test.ts`, `test/evidence-delivery-golden.test.ts`, `test/e2e/evidence-delivery-leak.test.ts`, `test/e2e/evidence-delivery-parity.test.ts`; bench `scripts/bench-evidence-delivery.ts`.+- - `src/core/search/evidence-date.ts` — C1 dated evidence blocks: the fixed header grammar (`[observed YYYY-MM-DD|unknown]` for page blocks; `[observed unknown; valid FROM to UNTIL]` for `recall` facts), `pageObservationDate` (effective-date precedence with `event_date` removed and no row-timestamp fallback; mirrors #6020's `resolveObservationDate`, the seam to swap once it lands), `formatBrainDay` (midnight UTC renders as written, other instants in `brain.timezone`; the rule think's page dates use), `loadPageDateHeaders` (one `pages` read per delivery; only the derived day leaves it) and `evidenceDateHeaderEnabled` (`search.evidence_date_header`, default off). Tests: `test/evidence-date-header.test.ts`.++- `src/core/search/evidence-date.ts` — C1 dated evidence blocks: the fixed header grammar (`[observed YYYY-MM-DD|unknown]` for page blocks; `[observed unknown; valid FROM to UNTIL]` for `recall` facts), `pageObservationDate` (effective-date precedence with `event_date` removed and no row-timestamp fallback; mirrors #6020's `resolveObservationDate`, the seam to swap once it lands), `formatBrainDay` from `effective-date.ts` (midnight UTC renders as written, other instants in `brain.timezone`; the one function think's `<page date>` also renders through, while the header's `observed` stays when the text was said, never the content date), `loadPageDateHeaders` (one `pages` read per delivery; only the derived day leaves it) and `evidenceDateHeaderEnabled` (`search.evidence_date_header`, default off). Tests: `test/evidence-date-header.test.ts`.+- `src/core/search/entity-anchor.ts` — entity-anchored retrieval: `entityAnchoredPages` (the entity page plus up to 10 pages that link to it or name it as a word, newest by `COALESCE(effective_date, updated_at)`; question/synthesis/pinned-question pages excluded) and `prefixAnchoredPages`, shared by pinned-question refresh (`questions/refresh.ts` `anchoredSlugs`) and the `query`/`search` ops; `asksForCurrentState` (deterministic cue regex), `namedEntity` (exactly one `isFactEntityPage` page whose title `isTitleMentionedInQuery` matches, read-policy filtered; a title inside a longer matched title is the same mention); `applyEntityAnchoring` (anchored rows first, at most half the row count, organic rows of the same page moved up, missing pages read through `getChunkWindows` under the caller's scope, rows stamped `entity_anchored`, token budget re-applied, fail-open); `entityAnchoringEnabled` (`search.entity_anchoring`, default off). Tests: `test/search-entity-anchor.test.ts`. Gates: `docs/eval/decisions/entity-anchoring-query/`.+- `src/core/search/facts-arm.ts` — the `query` facts arm behind `search.query_facts_arm` (default on since gates 1b and 2 passed; `false` turns it off). `matchQueryFacts` reads active facts only (not expired, not superseded, `valid_until` not passed, audit rows excluded) under recall's read policy (source scope; remote callers get world facts with private provenance filtered) and matches them by query-embedding cosine (`FACT_COSINE_MIN` 0.6, the embedding `hybridSearch` already computed, via `HybridSearchOpts.onQueryEmbedding`) or by query-term share (half the terms) or a named entity, newest `valid_from` first, at most `MAX_FACT_ROWS` (3). `applyFactsArm` adds them as `fact_row` rows in spare capacity only: free slots under the caller's row count, and whole rows that fit in what the page rows leave of the token budget; a page row is never displaced `factRowOutput` strips page fields (slug, id, type, chunk_id) from fact rows on output, leaving `result_type: 'fact'`, `fact_id`, `follow_up` (`recall` by entity, or `grep` without one) and `page_slug` when the caller can read the entity page (`readableEntityPages`); and stamps `superseded_claim` on page rows whose typed `claim_metric` (plus `claim_period` when both carry it) a newer active fact covers. No model call. Tests: `test/search-facts-arm.test.ts`. Gates and verdict: `docs/eval/decisions/query-facts-arm/`. Temporal fact reserve: `applyTemporalFactReserve` behind `search.temporal_fact_reserve` (default off): `hasTemporalCue` (the preregistered word, phrase, ISO date and month-name regex), candidates from `collectFactCandidates` (50 cosine, 50 keyword, 20 entity facts; shared with the facts arm's `matchQueryFacts`), scored cosine + term share + 0.1 when `valid_from` is more than a day from `created_at`, kept at cosine >= 0.5 or term share >= 0.34, packed into 15% of the token budget and 30% of the row count (1-20), rendered as fact rows whose text starts with `factDateHeader` (evidence delivery adds no second header), oldest first after the pages. Tests: `test/search-temporal-fact-reserve.test.ts`. Gates: `docs/eval/decisions/temporal-fact-reserve/`.+- `src/core/search/query-arms.ts` — `applyQueryArms`: the `query` op's post-retrieval arms in order (entity anchoring, then the facts arm), each behind its own key (entity anchoring default off, the facts arm default on); a temporal-cue query with a token budget takes the temporal fact reserve instead of the facts arm when `search.temporal_fact_reserve` is on; with all off it returns the rows untouched.+- `src/core/search/image-vector-presence.ts` — `brainHasImageVectors` (one `EXISTS embedding_image IS NOT NULL` probe per engine, cached 60 s, fail-open to true). `hybrid/arms.ts` uses it so an inferred image/both modality on a brain with no image embeddings stays text: no multimodal embed, keyword arm kept, no `vector_arm_failed`; the opt-in LLM modality tie-break still runs, and an image or both answer is demoted to text. An explicit `crossModal` is honored. Tests: `test/search-image-arm-text-only.test.ts`, `test/cross-modal-hybrid-integration.serial.test.ts`.- `src/core/search/chunk-windows.ts` — request/response shapes and the row mapper for `BrainEngine.getChunkWindows`. The SQL lives once in `src/core/engine-sql/chunks.ts` (`getChunkWindows`): page rows (authorization + seal + max chunk index + raw body columns) and chunk rows (inside the requested chunk_index ranges, text modality, requested chunk sources, row cap) come back in one UNION so the row cap never hides a page's authorization; the predicate is the search legs' (source scope, deleted, current text projection, archived source, quarantine, private pages, safe chunks). Postgres runs it inside the scoped read transaction.diff --cc docs/architecture/key-files/core-services-3.mdindex 38bfbb8f1d,008773d22e..fa9fa734d4--- a/docs/architecture/key-files/core-services-3.md+++ b/docs/architecture/key-files/core-services-3.md@@@ -5,6 -5,8 +5,8 @@@ Current behavior and load-bearing invar- `src/core/think/index.ts` — `runThink` builds its internal `LLMClient` via a small adapter wrapping `gateway.chat()` from `src/core/ai/gateway.ts` (not `new Anthropic()` directly) so stdio MCP launches (Claude Desktop, Cursor) that don't inherit shell env still find a key set via `gbrain config set anthropic_api_key` (the gateway reads `~/.gbrain/config.json` AND env). Test seam: `opts.client?: ThinkLLMClient` injection works (`test/think-pipeline.test.ts`, `test/think-gateway-adapter.test.ts`); `opts.stubResponse` short-circuits before any LLM call. When neither key nor client is available, the "no LLM available" stub fires with `NO_ANTHROPIC_API_KEY`. Trajectory injection (default ON): `runThink` orchestrates `classifyIntent(question)` → `extractCandidateEntities(question, retrievedSlugs)` → `findTrajectory` (5s `Promise.race` timeout per candidate, concurrency cap 3) → `formatTrajectoryBlock`. `buildThinkUserMessage` (in `src/core/think/prompt.ts`) has a `trajectory?: ThinkTrajectoryBlockOpts` slot honoring BOTH prompt orderings (calibration mode: retrieval → calibration → trajectory → question; default mode: question → retrieval → trajectory → instruction). The MCP `think` op handler maps `sourceScopeOpts(ctx)` onto `RunThinkOpts` via `thinkSourceScopeOpts(ctx)` (operations.ts), and `runThink` threads the scope into `runGather` (`src/core/think/gather.ts`) — so every gather stream (hybrid retrieval, takes keyword + vector via the engines' scoped `searchTakes`/`searchTakesVector`, graph walk via `traversePaths`) AND trajectory resolution stay within the caller's source grant (federated `sourceIds[]` wins over scalar `sourceId`); pinned by `test/e2e/think-source-isolation-pglite.test.ts`. Config key `think.trajectory_enabled` (default `true`). Any error in the trajectory path degrades to "no block injected" + `TRAJECTORY_INJECTION_FAILED` warning — the think call never crashes from trajectory. Production path skips `fallback_slugify` resolutions (avoid querying invented slugs); the LongMemEval harness accepts them. Pinned by `test/think-trajectory-injection.test.ts`. Debug: `GBRAIN_THINK_DEBUG=1 gbrain think "..."` prints the spliced prompt to stderr. System One (`think/decide.ts`, no work when S2 and S4 are off): S2 decides the trajectory-gating intent (regex `classifyIntent` is the fallback and tie source) and hands gather one precomputed search-intent answer; S4 may return an abstention after gather and before synthesis (`ThinkResult.abstained`, warning `DECIDE_ABSTAINED`, `synthesisOk: false`, synthesis call skipped). Quote grounding (`think.quote_verify`, default on): after a real synthesis, every quoted span in the answer is grounded against exactly the evidence blocks the prompt carried (pages, takes, graph, trajectory; no refetch) with `groundAnswerQuotes`; when the answer had quotes, `answer` becomes the safe version (near matches repaired, quotes found nowhere unquoted and marked `[unverified]`, warning `QUOTE_NOT_IN_EVIDENCE`), `answer_raw`/`quote_check`/`unverified_quotes` are added, and `persist` (internal; stripped by the MCP `think` op) holds the raw answer run through `verifyBody(…, { checks: 'quotes' })`, which `persistSynthesis` saves with failing units in frontmatter `unverified_claims`. The `synthesize` verb returns the same additive fields. Pinned by `test/think-quote-verify.test.ts`.-- `src/core/think/temporal-context.ts` + the date-frame parts of `think/{index,prompt,gather}.ts` — `runThink` reads in a date frame: `resolveThinkTemporalContext` returns the reference day (caller `referenceDate` / MCP `reference_date` / CLI `--reference-date`, validated by `parseReferenceDate` as a real past-or-current YYYY-MM-DD, else today) in `brain.timezone` (UTC when unset or invalid); the user message carries `Current date: <day> (<zone>)` just before the question in both message shapes, and the system prompt carries the date-reading rules without the date itself (stable system text). `renderPagesBlock` adds `date="YYYY-MM-DD"` only when `effective_date_source` is a content date (`event_date|date|published|filename`); a midnight-UTC value is a day-only date and renders as written, any other instant renders in the brain zone. `ReferenceDateError` maps to `invalid_params` in the op. Test: `test/think-reading.test.ts`.++- `src/core/think/temporal-context.ts` + the date-frame parts of `think/{index,prompt,gather}.ts` — `runThink` reads in a date frame: `resolveThinkTemporalContext` returns the reference day (caller `referenceDate` / MCP `reference_date` / CLI `--reference-date`, validated by `parseReferenceDate` as a real past-or-current YYYY-MM-DD, else today) in `brain.timezone` (UTC when unset or invalid); the user message carries `Current date: <day> (<zone>)` just before the question in both message shapes, and the system prompt carries the date-reading rules without the date itself (stable system text). `renderPagesBlock` adds `date="YYYY-MM-DD"` only when `effective_date_source` is a content date (`event_date|date|published|filename`); the day renders through `formatBrainDay` (`effective-date.ts`, shared with C1's evidence headers): a midnight-UTC value is a day-only date and renders as written, any other instant renders in the brain zone. `ReferenceDateError` maps to `invalid_params` in the op. Test: `test/think-reading.test.ts`.+- `src/core/think/intent.ts` + `src/core/think/entity-extract.ts` — pure `classifyIntent(question)` returns `'temporal' | 'knowledge_update' | 'other'` (regex-first, no LLM, `'other'` fast path short-circuits with zero SQL). `extractCandidateEntities(question, retrievedSlugs)` pulls high-precision candidates from retrieved entity-prefix slugs (`people/`, `companies/`, `organizations/`) and medium-precision noun phrases. Stop-word boundaries + leading-verb stripper handle "When did I last meet Marco" → `marco`. Both consumed by `runThink` and the LongMemEval harness so the two paths cannot drift. Pinned by `test/think-intent.test.ts` and `test/think-entity-extract.test.ts`.- `src/core/transcripts/` (directory) — the transcript-adapter seam. `types.ts`: the `TranscriptAdapter` contract — `parse(path): AsyncGenerator<ParsedSession, FileDiagnostics>` (one FILE may hold many sessions; the generator RETURN value carries bytes/skipped-lines/zero-session diagnostics so an empty file explains itself), format-specific byte caps (JSONL 50MB hard cap — the 10MB default in `claude-code-jsonl.ts` belongs to the hook-lane tail reader, not imports; monolithic export JSON rejects-not-truncates at 200MB), and the ONE `buildTranscriptSlug` helper (per-provider dirs matching the conversation-archive layout; id suffixes are sha256 prefixes of the session id — hash12 in slugs, hash16 for the dedup identity — never a cleaned prefix of the source id, which would let same-prefix session ids collide). `detect.ts`: adapter registry + head-sample detection (explicit format wins; symlinks lstat-rejected) + injectable `harnessRoots` (the confined discovery surface). Adapters, each with a DATED `SPEC_TARGET` + scrubbed fixture + `bytes>0 && sessions==0` drift alarm: `claude-code.ts` (thin wrapper over the shipped `claude-code-jsonl.ts`, which also exposes the full-file `parseClaudeSessionFile` with real per-message timestamps — hook-lane `parseTranscript` output is pinned byte-identical; owns `isClaudeCodeSubagentFile` (a literal `subagents` path segment at ANY depth + `agent-*.jsonl` basename — both `<session>/subagents/agent-*.jsonl` and the workflow-nested `<session>/subagents/workflows/<wf>/agent-*.jsonl` are all-sidechain, zero-turn files carrying the PARENT session id; a project slug containing "subagents" is one segment and never matches) and `isClaudeCodeWorkflowArtifactFile` (everything under `<session>/subagents/workflows/<wf>/` — the agent logs plus the `journal.jsonl` run log that matches no adapter format; a UUID-named session directly under `subagents/` stays discoverable); `discover.ts` and the CLI's `expandPaths` skip both, so they never read as gap-table backlog, drift, or `unknown format` errors that hold the since-last watermark frozen; the adapter sets `expectedEmpty` when zero accepted turn-shaped records and zero skipped lines remain after root metadata/sidechain and explicit non-human user-text filtering. Metadata-only, non-human-text-only, and all-subagent files are understood empties and do not freeze the watermark; accepted turn records that yield no text and unparseable lines still signal drift. Pinned by `test/claude-code-jsonl-origin.test.ts`), `codex.ts` (turn selection is STRUCTURAL: user turns from `event_msg` user_message (through 0.152) or `event_msg` item_completed with item.type UserMessage, text blocks only (0.153+, #5163; a turn recorded in both shapes is kept once, other item types incl. AgentMessage skipped), assistant from `response_item` output_text; a file with assistant turns and zero user turns sets `FileDiagnostics.userTurnsMissing` (codex and claude-code; E-N4), which ingest counts as drift and the session-end hook heartbeats as `degraded`/`no_user_turns` on whole-file reads (pinned by `test/codex-rollout-0154.serial.test.ts`); role user/developer response_items are injected preambles and never leak; identity is `payload.id` — the per-thread id codex embeds in the rollout filename — with `payload.session_id` (the ROOT session shared by every forked/subagent thread) only as the legacy fallback, and the FIRST `session_meta` header wins because a child rollout carries its inherited parent header later in the file; the hook lane's `parseCodexHookTranscript` follows the same two rules), `openclaw.ts` (session header + message lines; `.checkpoint.*.jsonl` snapshots rejected), `hermes.ts` (COPY-THEN-READ of state.db + wal/shm sidecars — readonly WAL opens need -shm write access and lock against a live writer; schema from the installed hermes-agent source; PROVISIONAL), `grok.ts` (Grok Build session dirs — structural turn selection, sidecar-aware discovery; see its own entry), `chatgpt-export.ts` (the `mapping`-tree current_node walk; branches dropped by design, orphaned parents terminate quietly, latest-leaf fallback; extracted conversations.json only) + `claude-export.ts` (flat chat_messages); both export adapters load through the shared `export-json.ts` (monolithic JSON over the cap REJECTS with a split hint; a zip or wrong-shape file gets the unzip-first hint) and give id-less conversations content-derived fallback ids so two id-less exports cannot dedup-skip or overwrite each other. `render.ts`: session → part pages — imessage-slack line format with the regex IMPORTED from `conversation-parser/builtins.ts` (round-trip pinned), REAL timestamps (missing ones carry forward; zero-timestamp sessions refused — provenance is never fabricated), anchor-shaped BODY lines backslash-escaped (hostile message content cannot forge speakers), quoted facts/takes fence-marker tokens backslash-escaped at the same per-message seam (`gbrain\:facts:begin` — a session that read another page cannot plant a live or unbalanced fence on the transcript page; every fence consumer is a substring matcher, so the escape lands inside the token), fail-closed redaction (secret-scan + `harvest-private-patterns.txt` user patterns, slack-channel default excluded because it eats issue refs; imperatives COUNTED into hash-covered `transcript_import` frontmatter, never content_flag), message-boundary splitting at `PART_TARGET_BYTES` = 45,000 bytes (0.9 × the 50,000-byte content-sanity warn line, so no part takes the oversize-warn branch; far under the embed-skip threshold) with 2-message overlap, part 1 keeps the base slug, `frontmatter.id` unique per part. `ingest.ts`: the engine-facing core — a session whose part-1 `frontmatter.id` already has a live page imports at that page's slug (a renamed or re-dated conversation updates in place instead of being skipped as a cross-slug duplicate), SESSION atomicity (failed sessions skip; integrity failures abort the run), stale-part reconciliation (deletes `part > of` leftovers), session metadata banked in the base page's raw_data as the REDACTED copy and healed by content-compare even on hash-skipped re-runs (a run that died before `putRawData`, or a private pattern added after first import, repairs on the next pass), `cleanScan`/`maxSessionTs` for the watermark. `ingest-facts.ts`: ONE `runExtractConversationFactsCore` invocation (batch `slugs` selector) inside ONE `withBudgetTracker`, `isFactsExtractionEnabled` pre-checked. Pinned by `test/transcript-adapters.test.ts`, `test/transcript-render.test.ts`, `test/transcripts-retitle.test.ts`, `test/transcripts-ingest-pglite.test.ts`, `test/e2e/transcripts-writeback-fidelity.test.ts` (raw files through the adapters into the gold-extractor facts path).diff --cc src/core/effective-date.tsindex d0720629c8,2c138d7989..151bf3a4c9--- a/src/core/effective-date.ts+++ b/src/core/effective-date.ts@@@ -133,6 -135,6 +135,28 @@@ export function isValidTimeZone(timeZon}}++/** 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);++}++++/**++ * The one rule for rendering a stored date as YYYY-MM-DD (think's `<page++ * date>`, C1 evidence headers): exactly midnight UTC is a day-only date and++ * renders as written; any other instant renders in `timeZone`++ * (`brain.timezone`; UTC when unset or invalid). Null for a missing or++ * invalid value. Which date to render (content vs observation) is the++ * caller's choice.++ */++export function formatBrainDay(value: Date | string | null | undefined, timeZone?: string | null): string | null {++ if (value === null || value === undefined || value === '') return null;++ const d = value instanceof Date ? value : new Date(value);++ if (!Number.isFinite(d.getTime())) return null;++ const iso = d.toISOString();++ if (iso.endsWith('T00:00:00.000Z')) return iso.slice(0, 10);++ return dayInZone(d, timeZone && isValidTimeZone(timeZone) ? timeZone : 'UTC');++}++/** The instant a wall-clock time (held in `wall`'s UTC fields) names in `timeZone`, DST included. */function zonedWallTime(wall: Date, timeZone: string): Date {const format = new Intl.DateTimeFormat('en-US', { timeZone, hourCycle: 'h23', year: 'numeric', month: 'numeric',diff --cc src/core/search/evidence-date.tsindex b08933bbef,0000000000..6806c4e86amode 100644,000000..100644--- a/src/core/search/evidence-date.ts+++ b/src/core/search/evidence-date.ts@@@ -1,171 -1,0 +1,157 @@@+/**+ * Dated evidence blocks (C1, `search.evidence_date_header`): the one-line+ * date header evidence delivery puts at the top of every delivered block, and+ * the day formatter it shares with think's page dates.+ *+ * Header grammar (fixed, one line, parsed by agents and eval harnesses):+ *+ * page block: [observed 2026-03-05]+ * fact: [observed unknown; valid 2026-03-01 to unknown]+ *+ * Each date is YYYY-MM-DD or the literal `unknown`. `observed` is when the+ * source text was written or said (date grounding's observation time,+ * #6020): the page's filename/slug date,+ * frontmatter `date`, `published` or a created key, in effective-date+ * precedence with `event_date` removed. An event date is when something+ * happened, not when the note was written, and row timestamps are when GBrain+ * stored it, so neither is ever shown as observed. Facts carry no observation+ * date on master, so a fact's `observed` is `unknown` and its validity window+ * (`valid_from` to `valid_until`, an open end shown as `unknown`) follows.+ *+ * Seam: `pageObservationDate` mirrors `resolveObservationDate` from+ * src/core/ai/date-grounding.ts (#6020); once that lands, call it here- * instead. `formatBrainDay` is the rendering rule think's `<page date>`- * attribute uses, so both surfaces print the same day.++ * instead. Days render through `formatBrainDay` (effective-date.ts), the++ * same function think's `<page date>` attribute uses, so both surfaces print++ * the same day. The header's `observed` is when the text was written or++ * said, never the event date think shows as content date.+ */- import { computeEffectiveDate, isValidTimeZone } from '../effective-date.ts';++import { computeEffectiveDate, formatBrainDay } from '../effective-date.ts';++export const EVIDENCE_DATE_HEADER_KEY = 'search.evidence_date_header';+export const UNKNOWN_DATE = 'unknown';++const OBSERVATION_SOURCES = new Set(['filename', 'date', 'published', 'created']);+- /**- * YYYY-MM-DD for a stored instant: exactly midnight UTC is a day-only date- * and renders as written; any other instant renders in `timeZone`- * (`brain.timezone`; UTC when unset or invalid). Null for a missing or- * invalid value.- */- export function formatBrainDay(value: Date | string | null | undefined, timeZone?: string | null): string | null {- if (value === null || value === undefined || value === '') return null;- const d = value instanceof Date ? value : new Date(value);- if (!Number.isFinite(d.getTime())) return null;- const iso = d.toISOString();- if (iso.endsWith('T00:00:00.000Z')) return iso.slice(0, 10);- const zone = timeZone && isValidTimeZone(timeZone) ? timeZone : 'UTC';- return new Intl.DateTimeFormat('en-CA', { timeZone: zone, year: 'numeric', month: '2-digit', day: '2-digit' }).format(d);- }-+/** When the page's text was written or said; null when it states no such date. Never a row timestamp. */+export function pageObservationDate(page: {+ slug: string;+ frontmatter?: Record<string, unknown> | null;+ filename?: string | null;+ timeZone?: string | null;+}): Date | null {+ const { event_date: _eventDate, ...frontmatter } = page.frontmatter ?? {};+ const invalid = new Date(Number.NaN);+ const result = computeEffectiveDate({+ slug: page.slug,+ frontmatter,+ filename: page.filename ?? page.slug.split('/').pop() ?? null,+ timeZone: page.timeZone ?? undefined,+ createdAt: invalid,+ updatedAt: invalid,+ });+ return result.date && result.source && OBSERVATION_SOURCES.has(result.source) ? result.date : null;+}++export function pageDateHeader(observed: string | null): string {+ return `[observed ${observed ?? UNKNOWN_DATE}]`;+}++/** A valid_from within this of created_at is the write-time default, not a known start of validity. */+const WRITE_TIME_DEFAULT_MS = 60_000;++/**+ * `observed` is when the fact was said: the observation date of the page it+ * came from, when the caller supplies it. `valid FROM` is the fact's+ * valid_from, except a valid_from that only records the write time (the+ * default when `remember` gets no date) renders `unknown`: the header never+ * presents when a fact was written as when it became true.+ */+export function factDateHeader(+ fact: { valid_from?: Date | string | null; valid_until?: Date | string | null; created_at?: Date | string | null },+ timeZone?: string | null,+ observed?: string | null,+): string {+ const writeTimeDefault = fact.valid_from && fact.created_at+ && Math.abs(new Date(fact.valid_from).getTime() - new Date(fact.created_at).getTime()) < WRITE_TIME_DEFAULT_MS;+ const from = (writeTimeDefault ? null : formatBrainDay(fact.valid_from, timeZone)) ?? UNKNOWN_DATE;+ const until = formatBrainDay(fact.valid_until, timeZone) ?? UNKNOWN_DATE;+ return `[observed ${observed ?? UNKNOWN_DATE}; valid ${from} to ${until}]`;+}++/**+ * The page header for each page id: one read of the stored frontmatter and+ * import filename (only the derived day leaves this function) plus+ * `brain.timezone`. Ids missing from the result render `unknown`.+ */+export async function loadPageDateHeaders(+ engine: { executeRaw<T>(sql: string, params?: unknown[]): Promise<T[]>; getConfig(key: string): Promise<string | null> },+ pageIds: number[],+): Promise<Map<number, string>> {+ const out = new Map<number, string>();+ const ids = [...new Set(pageIds.filter(id => Number.isInteger(id) && id > 0))];+ if (ids.length === 0) return out;+ const timeZone = (await engine.getConfig('brain.timezone').catch(() => null))?.trim() || null;+ const rows = await engine.executeRaw<{ id: number; slug: string; frontmatter: unknown; import_filename: string | null }>(+ 'SELECT id, slug, frontmatter, import_filename FROM pages WHERE id = ANY($1::int[])', [ids]);+ for (const r of rows) {+ const fm = typeof r.frontmatter === 'string' ? JSON.parse(r.frontmatter) : r.frontmatter;+ const observed = pageObservationDate({ slug: String(r.slug), frontmatter: fm && typeof fm === 'object' ? fm as Record<string, unknown> : null, filename: r.import_filename, timeZone });+ out.set(Number(r.id), pageDateHeader(formatBrainDay(observed, timeZone)));+ }+ return out;+}++/** `recall` fact rows plus `date_header` when `search.evidence_date_header` is on; unchanged otherwise. */+export async function withFactDateHeaders<T extends { id: number; valid_from: string | null; valid_until: string | null; created_at?: string | null; entity_slug?: string | null; source_id?: string }>(+ engine: { getConfig(key: string): Promise<string | null>; executeRaw<R>(sql: string, params?: unknown[]): Promise<R[]> },+ facts: T[],+): Promise<Array<T & { date_header?: string }>> {+ if (!await evidenceDateHeaderEnabled(engine)) return facts;+ const timeZone = (await engine.getConfig('brain.timezone').catch(() => null))?.trim() || null;+ const observed = await factObservationDates(engine, facts, timeZone).catch(() => new Map<number, string>());+ return facts.map(f => ({ ...f, date_header: factDateHeader(f, timeZone, observed.get(f.id)) }));+}++/**+ * When each fact was said: the observation date of the page the fact came+ * from (`facts.source_markdown_slug`, e.g. the conversation it was extracted+ * from). A fact stored in its own entity page's facts fence has no such page,+ * so it stays unknown. One facts read and one pages read per call.+ */+async function factObservationDates(+ engine: { executeRaw<R>(sql: string, params?: unknown[]): Promise<R[]> },+ facts: Array<{ id: number; entity_slug?: string | null }>,+ timeZone: string | null,+): Promise<Map<number, string>> {+ const out = new Map<number, string>();+ const ids = facts.map(f => f.id).filter(id => Number.isInteger(id) && id > 0);+ if (!ids.length) return out;+ const rows = await engine.executeRaw<{ id: number; source_id: string; slug: string | null; entity_slug: string | null }>(+ 'SELECT id, source_id, source_markdown_slug AS slug, entity_slug FROM facts WHERE id = ANY($1::bigint[])', [ids]);+ const wanted = rows.filter(r => r.slug && r.slug !== r.entity_slug);+ if (!wanted.length) return out;+ const pages = await engine.executeRaw<{ source_id: string; slug: string; frontmatter: unknown; import_filename: string | null }>(+ `SELECT p.source_id, p.slug, p.frontmatter, p.import_filename FROM pages p+ JOIN unnest($1::text[], $2::text[]) AS w(source_id, slug) ON p.source_id = w.source_id AND p.slug = w.slug WHERE p.deleted_at IS NULL`,+ [wanted.map(r => r.source_id), wanted.map(r => r.slug!)]);+ const byKey = new Map(pages.map(p => {+ const fm = typeof p.frontmatter === 'string' ? JSON.parse(p.frontmatter) : p.frontmatter;+ const day = formatBrainDay(pageObservationDate({ slug: p.slug, frontmatter: fm && typeof fm === 'object' ? fm as Record<string, unknown> : null, filename: p.import_filename, timeZone }), timeZone);+ return [`${p.source_id}\u0000${p.slug}`, day] as const;+ }));+ for (const r of wanted) {+ const day = byKey.get(`${r.source_id}\u0000${r.slug}`);+ if (day) out.set(Number(r.id), day);+ }+ return out;+}++/** `search.evidence_date_header` is on ('true' | 'on' | '1' | 'yes'); off by default and on any read error. */+export async function evidenceDateHeaderEnabled(engine: { getConfig(key: string): Promise<string | null> }): Promise<boolean> {+ try {+ const raw = (await engine.getConfig(EVIDENCE_DATE_HEADER_KEY))?.trim().toLowerCase();+ return raw === 'true' || raw === 'on' || raw === '1' || raw === 'yes';+ } catch {+ return false;+ }+}diff --cc src/core/think/temporal-context.tsindex 0000000000,587ae02541..838aa60d55mode 000000,100644..100644--- a/src/core/think/temporal-context.ts+++ b/src/core/think/temporal-context.ts@@@ -1,0 -1,94 +1,82 @@@+ /**+ * 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';++import { dayInZone, formatBrainDay, 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);++ return formatBrainDay(typeof raw === 'string' ? raw.trim() : raw, timeZone);+ }diff --cc test/evidence-date-header.test.tsindex 0b31ade5ed,0000000000..dab7ae78e1mode 100644,000000..100644--- a/test/evidence-date-header.test.ts+++ b/test/evidence-date-header.test.ts@@@ -1,207 -1,0 +1,208 @@@+/**+ * C1 — dated evidence blocks (`search.evidence_date_header`): the fixed+ * one-line header grammar, the observation-date rule (never an event date or+ * a row timestamp), budget accounting for the header, span offsets, the+ * default-off byte identity, recall fact validity windows, and the+ * configurable remote budget clamp the eval relies on.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { operations, type OperationContext } from '../src/core/operations.ts';+import { prepareMarkdownChunks } from '../src/core/markdown-chunks.ts';+import { installFixtureChunks } from './helpers/page-projection.ts';+import type { SearchResult } from '../src/core/types.ts';+import { countEvidenceTokens, deliverEvidence, type EvidencePlan } from '../src/core/search/evidence-delivery.ts';+import {- EVIDENCE_DATE_HEADER_KEY, factDateHeader, formatBrainDay, pageDateHeader, pageObservationDate,++ EVIDENCE_DATE_HEADER_KEY, factDateHeader, pageDateHeader, pageObservationDate,+} from '../src/core/search/evidence-date.ts';++import { formatBrainDay } from '../src/core/effective-date.ts';++const HEADER_LINE = /^\[observed (\d{4}-\d{2}-\d{2}|unknown)\]\n/;++describe('header grammar and dates', () => {+ test('page and fact headers are fixed one-line strings; unknown dates read "unknown"', () => {+ expect(pageDateHeader('2026-03-05')).toBe('[observed 2026-03-05]');+ expect(pageDateHeader(null)).toBe('[observed unknown]');+ expect(factDateHeader({ valid_from: new Date('2026-03-01T00:00:00Z'), valid_until: null })).toBe('[observed unknown; valid 2026-03-01 to unknown]');+ expect(factDateHeader({ valid_from: null, valid_until: '2026-04-01T00:00:00.000Z' })).toBe('[observed unknown; valid unknown to 2026-04-01]');+ for (const h of [pageDateHeader(null), factDateHeader({})]) expect(h).not.toContain('\n');+ // A valid_from that only records the write time is not a known start of validity.+ expect(factDateHeader({ valid_from: '2026-10-05T12:00:00.000Z', valid_until: null, created_at: '2026-10-05T12:00:00.400Z' })).toBe('[observed unknown; valid unknown to unknown]');+ expect(factDateHeader({ valid_from: '2026-03-01T00:00:00.000Z', valid_until: null, created_at: '2026-10-05T12:00:00.000Z' }, null, '2026-02-10')).toBe('[observed 2026-02-10; valid 2026-03-01 to unknown]');+ });++ test('formatBrainDay: midnight UTC renders as written, other instants in brain.timezone', () => {+ expect(formatBrainDay(new Date('2026-03-05T00:00:00Z'), 'America/Los_Angeles')).toBe('2026-03-05');+ expect(formatBrainDay(new Date('2026-03-05T03:00:00Z'), 'America/Los_Angeles')).toBe('2026-03-04');+ expect(formatBrainDay(new Date('2026-03-05T03:00:00Z'), null)).toBe('2026-03-05');+ expect(formatBrainDay(new Date('2026-03-05T03:00:00Z'), 'Not/AZone')).toBe('2026-03-05');+ expect(formatBrainDay(null)).toBeNull();+ expect(formatBrainDay('garbage')).toBeNull();+ });++ test('observation date: filename, date, published, created keys; never event_date or row times', () => {+ const day = (d: Date | null) => d?.toISOString().slice(0, 10) ?? null;+ expect(day(pageObservationDate({ slug: 'notes/x', frontmatter: { date: '2026-03-05' } }))).toBe('2026-03-05');+ expect(day(pageObservationDate({ slug: 'notes/x', frontmatter: { event_date: '2024-01-01', date: '2026-03-05' } }))).toBe('2026-03-05');+ expect(pageObservationDate({ slug: 'notes/x', frontmatter: { event_date: '2024-01-01' } })).toBeNull();+ expect(day(pageObservationDate({ slug: 'chat/2026-02-10-session', frontmatter: {} }))).toBe('2026-02-10');+ expect(day(pageObservationDate({ slug: 'notes/x', frontmatter: { created: '2025-12-31' } }))).toBe('2025-12-31');+ expect(pageObservationDate({ slug: 'notes/undated', frontmatter: {} })).toBeNull();+ });+});++describe('deliverEvidence with the header on', () => {+ const body = Array.from({ length: 30 }, (_, i) => `**${i % 2 ? 'assistant' : 'user'}:** turn ${i} about the renewal and the roadmap.`).join('\n\n');+ const chunks = [body.slice(0, body.length / 2).trim(), body.slice(body.length / 2).trim()];+ function stub(frontmatter: Record<string, unknown>) {+ return {+ async getConfig(key: string) { return key === 'brain.timezone' ? 'UTC' : null; },+ async executeRaw() { return [{ id: 1, slug: 'chat/s', frontmatter, import_filename: null }]; },+ async getChunkWindows() {+ return [{ page_id: 1, slug: 'chat/s', source_id: 'default', type: 'note', revision: 'r1', sealed: true, max_chunk_index: 1, row_limited: false,+ compiled_truth: body, timeline: '', chunks: chunks.map((t, i) => ({ id: 1000 + i, chunk_index: i, chunk_text: t, chunk_source: 'compiled_truth' })) }];+ },+ } as never;+ }+ const hit: SearchResult = { slug: 'chat/s', page_id: 1, title: 'S', type: 'note', chunk_text: chunks[1], chunk_source: 'compiled_truth', chunk_id: 1001, chunk_index: 1, score: 1, stale: false, source_id: 'default' };+ const plan = (budget: number, dateHeader: boolean): EvidencePlan => ({ requestedUnit: 'page', unit: 'page', window: 1, budgetTokens: budget, explicitUnit: true, ...(dateHeader ? { dateHeader: true as const } : {}) });++ test('every block starts with its header; tokens and spans account for it', async () => {+ const off = await deliverEvidence(stub({ date: '2026-03-05' }), [hit], plan(32000, false), {});+ const on = await deliverEvidence(stub({ date: '2026-03-05' }), [hit], plan(32000, true), {});+ const header = '[observed 2026-03-05]\n';+ expect(on.results[0].chunk_text).toBe(header + off.results[0].chunk_text);+ expect(on.results[0].delivered.tokens).toBe(off.results[0].delivered.tokens + countEvidenceTokens(header));+ expect(on.delivery.tokens_delivered).toBe(countEvidenceTokens(on.results[0].chunk_text));+ expect(on.delivery.date_header).toBe(true);+ expect(off.delivery.date_header).toBeUndefined();+ const spanOn = on.results[0].delivered.match_spans[0];+ const spanOff = off.results[0].delivered.match_spans[0];+ expect(on.results[0].chunk_text.slice(spanOn.start, spanOn.end)).toBe(off.results[0].chunk_text.slice(spanOff.start, spanOff.end));+ });++ test('the budget is honoured with the header counted', async () => {+ for (const budget of [12, 40, 120, 400]) {+ const on = await deliverEvidence(stub({}), [hit], plan(budget, true), {});+ expect(on.results[0].chunk_text).toMatch(HEADER_LINE);+ expect(on.results[0].chunk_text.startsWith('[observed unknown]\n')).toBe(true);+ expect(on.delivery.budget_used).toBeLessThanOrEqual(budget);+ }+ });++ test('a failed date read renders unknown and says so', async () => {+ const engine = Object.assign(stub({}) as object, { async executeRaw() { throw new Error('boom'); } }) as never;+ const on = await deliverEvidence(engine, [hit], plan(32000, true), {});+ expect(on.results[0].chunk_text.startsWith('[observed unknown]\n')).toBe(true);+ expect(on.delivery.fallbacks).toContain('date_header_unavailable');+ });+});++describe('ops on PGLite', () => {+ let engine: PGLiteEngine;+ let lastMeta: Record<string, any> | null = null;+ const op = (name: string) => operations.find(o => o.name === name)!;+ const ctxOf = (overrides: Partial<OperationContext> = {}): OperationContext => ({+ engine: engine as never, config: {} as never, logger: console as never, dryRun: false, remote: false, sourceId: 'default',+ emitResponseMeta: (key: string, value: unknown) => { if (key === 'retrieval') lastMeta = value as Record<string, any>; },+ ...overrides,+ }) as OperationContext;+ const SESSION = Array.from({ length: 12 }, (_, i) => `**user:** question ${i} about the walrus launch\n\n**assistant:** reply ${i} on walrus timelines`).join('\n\n');+ const NOTE = '## Walrus\n\nThe walrus pricing note describes the plan.';++ beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ const pages: Array<[string, string, Record<string, unknown>]> = [+ ['chat/2026-02-10-walrus', SESSION, {}],+ ['notes/walrus-dated', NOTE, { date: '2026-03-05', event_date: '2020-01-01' }],+ ['notes/walrus-undated', NOTE.replace('pricing', 'support'), {}],+ ];+ for (const [slug, body, frontmatter] of pages) {+ await engine.putPage(slug, { type: 'note', title: slug, compiled_truth: body, timeline: '', frontmatter });+ await installFixtureChunks(engine, slug, await prepareMarkdownChunks({ compiled_truth: body, timeline: '' }));+ }+ await engine.setConfig('search.mcp_keyword_only', 'true');+ await engine.insertFact({ fact: 'Walrus launch is in March', kind: 'fact', entity_slug: 'notes/walrus-dated', source: 'test', visibility: 'world',+ valid_from: new Date('2026-03-01T00:00:00Z') }, { source_id: 'default' });+ }, 240_000);++ afterAll(async () => { await engine.disconnect(); }, 240_000);++ test('default off: no header, no meta key, recall facts unchanged', async () => {+ const rows = await op('search').handler(ctxOf(), { query: 'walrus', return_unit: 'page' }) as SearchResult[];+ expect(rows.length).toBeGreaterThan(0);+ expect(rows.some(r => HEADER_LINE.test(r.chunk_text))).toBe(false);+ expect(lastMeta!.delivery.date_header).toBeUndefined();+ const recall = await op('recall').handler(ctxOf(), { entity: 'notes/walrus-dated' }) as Record<string, any>;+ expect(recall.facts[0].date_header).toBeUndefined();+ });++ test('on: query/search blocks carry observed dates; recall facts carry their validity window', async () => {+ await engine.setConfig(EVIDENCE_DATE_HEADER_KEY, 'true');+ try {+ const rows = await op('query').handler(ctxOf(), { query: 'walrus', return_unit: 'page', expand: false }) as SearchResult[];+ const by = (slug: string) => rows.find(r => r.slug === slug)!;+ expect(by('chat/2026-02-10-walrus').chunk_text.split('\n')[0]).toBe('[observed 2026-02-10]');+ expect(by('notes/walrus-dated').chunk_text.split('\n')[0]).toBe('[observed 2026-03-05]');+ expect(by('notes/walrus-undated').chunk_text.split('\n')[0]).toBe('[observed unknown]');+ expect(lastMeta!.delivery.date_header).toBe(true);+ expect(lastMeta!.delivery.budget_used).toBeLessThanOrEqual(lastMeta!.delivery.budget_tokens);+ const auto = await op('search').handler(ctxOf(), { query: 'walrus' }) as SearchResult[];+ expect(auto.every(r => HEADER_LINE.test(r.chunk_text))).toBe(true);+ const recall = await op('recall').handler(ctxOf(), { entity: 'notes/walrus-dated' }) as Record<string, any>;+ expect(recall.facts[0].date_header).toBe('[observed unknown; valid 2026-03-01 to unknown]');+ } finally {+ await engine.unsetConfig(EVIDENCE_DATE_HEADER_KEY);+ }+ });++ test('on: a fact from a dated source page is observed on that date; a fact written without a date does not show the write time as valid-from', async () => {+ await engine.setConfig(EVIDENCE_DATE_HEADER_KEY, 'true');+ try {+ const fromChat = await engine.insertFact({ fact: 'Walrus moved its launch to April', kind: 'fact', entity_slug: 'notes/walrus-undated', source: 'test', visibility: 'world',+ valid_from: new Date('2026-02-10T00:00:00Z') }, { source_id: 'default' });+ await engine.executeRaw('UPDATE facts SET source_markdown_slug = $2 WHERE id = $1', [fromChat.id, 'chat/2026-02-10-walrus']);+ const undated = await op('recall').handler(ctxOf(), { entity: 'notes/walrus-undated' }) as Record<string, any>;+ expect(undated.facts.find((f: any) => f.fact.includes('April')).date_header).toBe('[observed 2026-02-10; valid 2026-02-10 to unknown]');+ const written = await engine.insertFact({ fact: 'Walrus hired a new lead', kind: 'fact', entity_slug: 'notes/walrus-undated', source: 'test', visibility: 'world' }, { source_id: 'default' });+ const again = await op('recall').handler(ctxOf(), { entity: 'notes/walrus-undated' }) as Record<string, any>;+ expect(again.facts.find((f: any) => f.id === written.id).date_header).toBe('[observed unknown; valid unknown to unknown]');+ } finally {+ await engine.unsetConfig(EVIDENCE_DATE_HEADER_KEY);+ }+ });++ test('remember with valid_from stores it, and the header shows it as the start of validity', async () => {+ await engine.setConfig(EVIDENCE_DATE_HEADER_KEY, 'true');+ try {+ await op('remember').handler(ctxOf(), { fact: 'Walrus opened a Porto office', provenance: 'chat on 2026-03-01', entity: 'notes/walrus-undated', valid_from: '2026-03-01' });+ const recall = await op('recall').handler(ctxOf(), { entity: 'notes/walrus-undated' }) as Record<string, any>;+ const row = recall.facts.find((f: any) => f.fact.includes('Porto'));+ expect(row.valid_from.slice(0, 10)).toBe('2026-03-01');+ expect(row.date_header).toBe('[observed unknown; valid 2026-03-01 to unknown]');+ } finally {+ await engine.unsetConfig(EVIDENCE_DATE_HEADER_KEY);+ }+ });++ test('remember rejects a valid_from that is not an ISO 8601 date', async () => {+ await expect(op('remember').handler(ctxOf(), { fact: 'Walrus is in Lisbon', provenance: 'test', valid_from: 'last spring' })).rejects.toMatchObject({ code: 'invalid_params' });+ });++ test('remote clamp: 32k by default and reported; a trusted eval brain raises it with search.return_budget_max_remote', async () => {+ await op('search').handler(ctxOf({ remote: true }), { query: 'walrus', return_unit: 'page', token_budget: 90000 });+ expect(lastMeta!.delivery.budget_clamped).toEqual({ requested: 90000, max: 32000 });+ expect(lastMeta!.delivery.fallbacks).toContain('budget_clamped');+ await engine.setConfig('search.return_budget_max_remote', '200000');+ try {+ await op('search').handler(ctxOf({ remote: true }), { query: 'walrus', return_unit: 'page', token_budget: 90000 });+ expect(lastMeta!.delivery.budget_tokens).toBe(90000);+ expect(lastMeta!.delivery.budget_clamped).toBeUndefined();+ expect(lastMeta!.delivery.fallbacks).not.toContain('budget_clamped');+ } finally {+ await engine.unsetConfig('search.return_budget_max_remote');+ }+ });+});diff --cc test/fixtures/goldens/cli/tools-json.jsonindex 2b8f6f2370,5a8c2483f3..277903264c--- a/test/fixtures/goldens/cli/tools-json.json+++ b/test/fixtures/goldens/cli/tools-json.json@@@ -2,8 -2,8 +2,8 @@@"golden": {"exitCode": 0,"stderr": "",- "stdoutBytes": 210328,- "stdoutSha256": "7796557202b324d19a4ea8961ec479267fd1926bc60a1d2c12edb014883fd50e",- "stdoutBytes": 205173,- "stdoutSha256": "cc60b726a258b932cc425079c3011b4a1f0b376ea6c258273e54d019ab75e9cc",++ "stdoutBytes": 210555,++ "stdoutSha256": "d18dbea3bd68cb5574acd6f0f13b0814e5320e64c7c1d85a9174ff3c8350a963","toolNames": ["remember","entity",