Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
feat(think): bound the evidence to the one explicit date a question names when the caller passes no window (PR #5086)
garrytan334533ad8e1b
diff --git a/docs/architecture/key-files/core-services-3.md b/docs/architecture/key-files/core-services-3.mdindex 3a705a0e39..facc60a258 100644--- a/docs/architecture/key-files/core-services-3.md+++ b/docs/architecture/key-files/core-services-3.md@@ -5,6 +5,8 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `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-window.ts` — the evidence window. `parseTemporalWindow(since, until)` validates caller bounds (inclusive UTC days or months); `filterPagesToWindow` keeps undated pages and counts the dated ones it drops. PR #5086 (wave 14): `parseQuestionWindow(question)` returns the one explicit date a question names (ISO day, ISO month, English month name + year) as bounds spanning it, null on no token, a bare year, two distinct tokens, an invalid token or a relative phrase; `resolveThinkWindow(question, since, until)` is what `runThink` calls: caller bounds first (`source: 'caller'`), else the question's (`source: 'question'`, `WINDOW_FROM_QUESTION` warning), surfaced as `ThinkResult.window_source` and fed to the system prompt's since/until.+- `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/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`.diff --git a/llms-full.txt b/llms-full.txtindex e4523c066b..0e99d702e0 100644--- a/llms-full.txt+++ b/llms-full.txt@@ -8703,7 +8703,7 @@ Response — an additive SUPERSET of the plain facts envelope on EVERY call| `protocol_version` | int | always present (every verb, every call) || `facts[]` | array | the base fact fields, PLUS per fact: `fact_id` (opaque STRING — the value `forget` accepts; the numeric `id` remains alongside it for compatibility) and `provenance` (the stored source attribution) || `total` | int | count of facts returned |-| `results[]` | array | search arm only: `slug`, `title`, `chunk`, `evidence`, `create_safety`, `provenance` (origin page slug) |+| `results[]` | array | search arm only: `slug`, `title`, `chunk`, `evidence`, `create_safety`, `provenance` (origin page slug), `source_id` (additive since #4830: the source the hit came from; on a federated read each hit names its own source, and a hit that carries none is labeled only when the read's scope is a single source, never a blind `default`) || `search_degraded` | string? | present when keyword-only fallback fired || `budget_tokens` / `budget_used` / `dropped_count` | int? | present for a positive finite numeric budget, including when its floor is zero || `budget_packing` | object? | present only when a valid `budget_policy` is supplied; effective policy and per-arm accounting |@@ -9084,7 +9084,11 @@ A pending write is a protocol `unavailable` error with a populated suggestion,`protocol_version: 1`, and optional `write_request` and `write_error` fields.It never returns a success `status` or `expired` value. `write_error` carriesthe detailed concurrency reason without changing the frozen protocol error-enum. A committed receipt retains the original memory-verb success fields.+enum. Its values branch three ways on revisions: `revision_required` (the page+exists and the write named no `expected_revision`: read it and resend),+`revision_conflict` (the named revision is stale: re-read and merge) and+`revision_backfill_pending` (resume the revision backfill). A committed receipt+retains the original memory-verb success fields.Compaction may remove diagnostics, but must preserve those frozen result fields.The optional caller-generated UUID `request_id` identifies one write intent.@@ -9178,6 +9182,7 @@ Refusals name the edit and never include protected text:| `edit_protected_span` | `edit_index=<i>` | The text touches a takes or facts section; use the scoped operations. || `edit_invalid` | `edit_index=<i>` when one edit is malformed | Pass 1 to 50 `{old_text, new_text}` objects with non-empty `old_text`. || `revision_conflict` | `current_revision=<uuid>` | Read the page again, rebuild the edits, resend. |+| `revision_required` | — | The page exists and the call named no `expected_revision` (`put_page`; additive since #5385, formerly reported as `revision_conflict`). Read the page, then resend with its revision, or `force: true` for an intentional overwrite. |```json→ get_page {"slug": "projects/example", "include_content": true}@@ -9828,6 +9833,8 @@ Source: https://raw.githubusercontent.com/garrytan/gbrain/master/docs/guides/tro| Recall returns conversation facts like "Date said …", "Attendees said …" or "Summary said …" | `gbrain repair conversation-labels` previews them ([conversation labels](repair.md#conversation-labels)); apply the printed command with `--yes` | agent, after the user agrees | `destructive` | `gbrain doctor --only conversation_label_facts --json` is ok || Conversation facts are dated 1970-01-01 | same preview: `gbrain repair conversation-labels` (an undated page's pre-fix facts carry a `segment 1970-01-01` context); add a `date:` to the page frontmatter before re-extracting it | agent, after the user agrees | `destructive` | `gbrain doctor --only conversation_label_facts --json` is ok || `remember` or `put_page` refused `source_changed` "The canonical file contains an uncoordinated local edit" on many pages nobody edited, or doctor `lost_caller_writes` warns | upgrade to v0.60.157.0 or later (a database-only v0.13.1 `validate: false` stamp was read as a file edit, #6429); then `gbrain repair failed-writes --source <id>` previews the refused writes and prints the apply command ([failed writes](repair.md#failed-writes)) | agent; the apply after the user agrees | none to preview | `gbrain doctor --only lost_caller_writes --json` is ok |+| A write (`add_timeline_entry`, `put_page`, `remember`, any `mutating` tool) refused `invalid_params` "unknown parameter … write operations always reject unknown parameters; nothing was written" | the call named a parameter the tool does not declare (for example `content` instead of `detail`); the `suggestion` names the submitted key and the declared one; resend with the declared name. Reads keep the `mcp.strict_params` warn grace period | agent | none | the resent call returns no `invalid_params` and no `unknown_param` warning |+| Facts extraction or embedding reports `(cause=AIConfigError model_not_found)` or `gbrain models doctor` says `model_not_found` while the key is valid | the provider refused the model, not the key (a 404, or a 403 "project does not have access to model"): check the model id with `gbrain models`, enable the model for the project in the provider console or set another model (`gbrain config set models.facts <provider:model>`) | user (provider console); agent for the config change, after the user agrees | none | `gbrain models doctor` reports the model `ok` || A gbrain call failed with a code you don't recognize | follow `fix.next` ([protocol](../protocol/AGENT_OPERATOR_v1.md)); `gbrain errors <code>` | agent | as the fix's `consent` | the fix's `verify` || A graph read omits a relationship you know existed, or says someone still works somewhere they left | the default read returns relationships true today: repeat with `status: "all"` or `as_of`; to record an end, add a dated timeline line (`Ended works_at [[companies/x]]`) or `add_link ... valid_until` ([temporal edges](temporal-edges.md)) | agent | none | `gbrain doctor --only edge_validity --json` || A command exited 3 (`confirmation_required`) | relay `user_message`; run `fix.command` only after the user agrees | agent, after the user agrees | the payload's `effects` | the fix's `verify` |diff --git a/src/core/operation-manifest.generated.ts b/src/core/operation-manifest.generated.tsindex 4eaed11ab4..25dac51ce3 100644--- a/src/core/operation-manifest.generated.ts+++ b/src/core/operation-manifest.generated.ts@@ -3445,7 +3445,7 @@ export const OPERATION_MANIFEST: OperationMeta[] = [},"since": {"type": "string",- "description": "Start of temporal window (YYYY-MM-DD or YYYY-MM)"+ "description": "Start of temporal window (YYYY-MM-DD or YYYY-MM). Omit both bounds and a question naming one explicit date (2026-09-15, 2026-09, September 2026) is bounded to it; the result says window_source."},"until": {"type": "string",diff --git a/src/core/ops/takes.ts b/src/core/ops/takes.tsindex ac48bbcf4c..daffad09a7 100644--- a/src/core/ops/takes.ts+++ b/src/core/ops/takes.ts@@ -225,7 +225,7 @@ const think: Operation = {save: { type: 'boolean', description: 'Persist a synthesis page (local-CLI only; ignored for MCP)' },take: { type: 'boolean', description: 'Append a take row to the anchor page (requires anchor)' },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)' },+ since: { type: 'string', description: 'Start of temporal window (YYYY-MM-DD or YYYY-MM). Omit both bounds and a question naming one explicit date (2026-09-15, 2026-09, September 2026) is bounded to it; the result says window_source.' },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).' },},diff --git a/src/core/think/index.ts b/src/core/think/index.tsindex 62abefeac5..b3338800d4 100644--- a/src/core/think/index.ts+++ b/src/core/think/index.ts@@ -32,7 +32,7 @@ import { chat as gatewayChat, probeChatModel, isThinkingModel, type ChatResult }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 { resolveThinkWindow } 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';@@ -248,6 +248,8 @@ export interface ThinkResult {abstained?: ThinkAbstention;/** The date frame the synthesis read in (reference date + brain timezone). */temporal?: { reference_date: string; time_zone: string };+ /** PR #5086: who bounded the evidence, when a window applied: the caller's `since`/`until`, or the one explicit date the question named (`WINDOW_FROM_QUESTION` warning). */+ window_source?: 'caller' | 'question';}const DEFAULT_MAX_OUTPUT_TOKENS = 4000;@@ -576,7 +578,11 @@ export async function runThink(): Promise<ThinkResult> {const rounds = Math.max(1, opts.rounds ?? 1);const warnings: string[] = [];- const window = parseTemporalWindow(opts.since, opts.until);+ // PR #5086: caller bounds are authoritative; with none, the one explicit date the question names bounds the synthesis.+ const resolvedWindow = resolveThinkWindow(opts.question, opts.since, opts.until);+ const window = resolvedWindow?.window ?? null;+ if (resolvedWindow?.source === 'question') warnings.push('WINDOW_FROM_QUESTION');+ const windowMeta = resolvedWindow ? { window_source: resolvedWindow.source } : {};const temporal = await resolveThinkTemporalContext(engine, { referenceDate: opts.referenceDate });// Resolve the model through the 6-tier chain.@@ -778,8 +784,8 @@ export async function runThink(const systemPrompt = buildThinkSystemPrompt({currentDate: true, intent, willSave: opts.save, withCalibration: !!calibrationBlockOpts,...(opts.anchor !== undefined ? { anchor: opts.anchor } : {}),- ...(opts.since !== undefined ? { since: opts.since } : {}),- ...(opts.until !== undefined ? { until: opts.until } : {}),+ ...(resolvedWindow?.since !== undefined ? { since: resolvedWindow.since } : {}),+ ...(resolvedWindow?.until !== undefined ? { until: resolvedWindow.until } : {}),});const userMessage = buildThinkUserMessage({question: opts.question, pagesBlock, takesBlock, currentDate: `${temporal.referenceDate} (${temporal.timeZone})`,@@ -858,6 +864,7 @@ export async function runThink(synthesis_status: modelProblem ? 'model_unusable' : 'no_llm',...(stubExtractive ? { extractive: stubExtractive } : {}),usage: null, // [E2] no LLM ran — no accounting+ ...windowMeta,diagnostics: {pagesFromHybrid: gather.diagnostics.pagesFromHybrid,takesFromKeyword: gather.diagnostics.takesFromKeyword,@@ -1010,6 +1017,7 @@ export async function runThink(graphHits: gather.diagnostics.graphHits,},temporal: { reference_date: temporal.referenceDate, time_zone: temporal.timeZone },+ ...windowMeta,};}diff --git a/src/core/think/temporal-window.ts b/src/core/think/temporal-window.tsindex 6f966b2d43..0d6fad34c0 100644--- a/src/core/think/temporal-window.ts+++ b/src/core/think/temporal-window.ts@@ -91,3 +91,43 @@ export function filterPagesToWindow<T extends DatedPage>(pages: T[], window: Tem}return { kept, droppedOutOfWindow, undatedKept };}++// PR #5086 (@tarush1989), wave 14 P3.17: a window from exactly one explicit date in the question.+const MONTH_NAMES = ['january', 'february', 'march', 'april', 'may', 'june', 'july', 'august', 'september', 'october', 'november', 'december'];+const MONTH_NAME_YEAR = new RegExp(`\\b(${MONTH_NAMES.join('|')})\\s+(\\d{4})\\b`, 'gi');++/**+ * The one explicit date a question names, as `since`/`until` bounds spanning it: an ISO day (`2026-09-15`), an ISO+ * month (`2026-09`) or an English month name with a four-digit year ("September 2026"). Fail closed to null on+ * anything else: no token, a bare year ("in 2026", "GPT-4"), two or more distinct tokens (a range the caller must+ * spell out), a token `parseTemporalWindow` refuses (`2026-13`, `2026-02-30`), a relative phrase ("next week").+ * Deterministic: no clock, no timezone.+ */+export function parseQuestionWindow(question: string | null | undefined): { since: string; until: string } | null {+ if (typeof question !== 'string' || !question) return null;+ const tokens = new Set<string>();+ for (const m of question.matchAll(/\b(\d{4}-\d{2}-\d{2})\b/g)) tokens.add(m[1]);+ for (const m of question.matchAll(/\b(\d{4}-\d{2})\b(?!-\d)/g)) tokens.add(m[1]);+ for (const m of question.matchAll(MONTH_NAME_YEAR)) tokens.add(`${m[2]}-${String(MONTH_NAMES.indexOf(m[1].toLowerCase()) + 1).padStart(2, '0')}`);+ if (tokens.size !== 1) return null;+ const [token] = tokens;+ try { parseTemporalWindow(token, token); } catch { return null; }+ return { since: token, until: token };+}++export interface ResolvedThinkWindow {+ window: TemporalWindow;+ /** Who bounded the synthesis: the caller's `since`/`until`, or the one explicit date the question named. */+ source: 'caller' | 'question';+ since: string | undefined;+ until: string | undefined;+}++/** `runThink`'s window: a caller bound is authoritative (and still validated); only when both are absent does the question's one explicit date apply. */+export function resolveThinkWindow(question: string, since?: string | null, until?: string | null): ResolvedThinkWindow | null {+ const caller = parseTemporalWindow(since, until);+ if (caller) return { window: caller, source: 'caller', since: since?.trim() || undefined, until: until?.trim() || undefined };+ const derived = parseQuestionWindow(question);+ if (!derived) return null;+ return { window: parseTemporalWindow(derived.since, derived.until)!, source: 'question', ...derived };+}diff --git a/test/think-question-window.test.ts b/test/think-question-window.test.tsnew file mode 100644index 0000000000..68bc4d71b8--- /dev/null+++ b/test/think-question-window.test.ts@@ -0,0 +1,83 @@+/**+ * PR #5086 (@tarush1989), wave 14 P3.17: `think` derives a temporal window from exactly one explicit date in the+ * question when the caller passed no `since`/`until`, and says where the window came from.+ *+ * Protects: caller bounds stay authoritative; a question with one unambiguous ISO day, ISO month or "Month YYYY"+ * token is bounded to it and the result carries `window_source: 'question'` plus a `WINDOW_FROM_QUESTION` warning;+ * two distinct dates, a bare year, a relative phrase or an invalid token derive nothing (fail closed); caller bounds+ * report `window_source: 'caller'`; no window reports no field.+ * Seams: `resolveThinkWindow` (the resolver `runThink` calls), `runThink({ stubResponse })` on a PGLite brain.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { importFromContent } from '../src/core/import-file.ts';+import { runThink } from '../src/core/think/index.ts';+import { parseQuestionWindow, parseTemporalWindow, resolveThinkWindow } from '../src/core/think/temporal-window.ts';+import { __setEmbedTransportForTests } from '../src/core/ai/gateway.ts';++const win = (since: string, until?: string) => parseTemporalWindow(since, until)!;++describe('parseQuestionWindow: one explicit date, or nothing', () => {+ test('an ISO day, an ISO month and a month name with a year each bound the question to that span', () => {+ expect(parseQuestionWindow('what changed on 2026-09-15 exactly')).toEqual({ since: '2026-09-15', until: '2026-09-15' });+ expect(parseQuestionWindow('summarize 2026-09 for me')).toEqual({ since: '2026-09', until: '2026-09' });+ expect(parseQuestionWindow('meetings in September 2026')).toEqual({ since: '2026-09', until: '2026-09' });+ expect(parseQuestionWindow('SEPTEMBER 2026 recap (mid-september 2026)')).toEqual({ since: '2026-09', until: '2026-09' });+ expect(parseQuestionWindow('September 2026 (2026-09) plans')).toEqual({ since: '2026-09', until: '2026-09' });+ });++ test('fails closed: no token, a bare year, two distinct dates, an invalid or partial token, a relative phrase', () => {+ for (const q of ['what are my open commitments', 'what did GPT-4 in 2024 change', 'what happened in 2026', 'notes about v2026',+ 'between September 2026 and October 2026', 'compare 2026-09-15 and 2026-09-22', 'September 2026 vs 2026-10',+ 'the 2026-13 quarter', 'around 2026-9 sometime', 'Septober 2026 offsite', 'the 2026-02-30 meeting',+ 'meetings next week', 'what happened in the last 7 days', '']) {+ expect(parseQuestionWindow(q)).toBeNull();+ }+ });+});++describe('resolveThinkWindow: caller bounds first', () => {+ test('any caller bound wins; both absent → the question; nothing → null', () => {+ expect(resolveThinkWindow('September 2026', '2020-01-01', '2020-12-31')).toEqual({ window: win('2020-01-01', '2020-12-31'), source: 'caller', since: '2020-01-01', until: '2020-12-31' });+ expect(resolveThinkWindow('September 2026', '2020-01-01', undefined)).toEqual({ window: win('2020-01-01'), source: 'caller', since: '2020-01-01', until: undefined });+ expect(resolveThinkWindow('September 2026', undefined, undefined)).toEqual({ window: win('2026-09', '2026-09'), source: 'question', since: '2026-09', until: '2026-09' });+ expect(resolveThinkWindow('open commitments', undefined, undefined)).toBeNull();+ });+});++describe('runThink reports the window and its origin', () => {+ let engine: PGLiteEngine;+ const stub = { answer: 'stubbed', citations: [], gaps: [] };+ beforeAll(async () => {+ __setEmbedTransportForTests(() => { throw new Error('keyword-only test'); });+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ for (const [slug, date] of [['brain/ops/2026-09-10', '2026-09-10'], ['brain/ops/2026-06-01', '2026-06-01']]) {+ const imported = await importFromContent(engine, slug, `---\ntitle: ${slug}\ntype: meeting\ndate: "${date}T09:00:00Z"\n---\n\noperations review notes\n`,+ { noEmbed: true, sourceId: 'default' });+ expect(imported.status).toBe('imported');+ }+ }, 60_000);+ afterAll(async () => { __setEmbedTransportForTests(null); await engine.disconnect(); });++ test('a question naming September 2026 is bounded to it and says so', async () => {+ const r = await runThink(engine, { question: 'operations review in September 2026', stubResponse: stub });+ expect(r.window_source).toBe('question');+ expect(r.warnings).toContain('WINDOW_FROM_QUESTION');+ expect((r.feedback_evidence ?? []).map((e) => e.slug)).toEqual(['brain/ops/2026-09-10']);+ });++ test('caller bounds are reported as the caller\'s and win over the question', async () => {+ const r = await runThink(engine, { question: 'operations review in September 2026', since: '2026-06-01', until: '2026-06-30', stubResponse: stub });+ expect(r.window_source).toBe('caller');+ expect(r.warnings).not.toContain('WINDOW_FROM_QUESTION');+ expect((r.feedback_evidence ?? []).map((e) => e.slug)).toEqual(['brain/ops/2026-06-01']);+ });++ test('no date anywhere: no window, no field, every page', async () => {+ const r = await runThink(engine, { question: 'operations review', stubResponse: stub });+ expect(r.window_source).toBeUndefined();+ expect((r.feedback_evidence ?? []).map((e) => e.slug).sort()).toEqual(['brain/ops/2026-06-01', 'brain/ops/2026-09-10']);+ });+});