Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(think): a month named in the question keeps the entity trajectory (GST-731, Cat 25)
garrytan2c1a83944fe5
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 8cadb056cf..b182a5247f 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -10,6 +10,17 @@ credits are retained; no result has been reassigned to another provider. Originaidentifiers and attribution are available in the pre-removal Git revision`6040075c6cb95be5881cc2e1b76ef7d71f4e5d29` (retained on 2026-09-23).+## [Unreleased]++**`think` keeps an entity's trajectory when the question names a month.** A question such as "What was the MRR of acme-example in April 2026?" bounds think's evidence to April (PR #5086), and that window used to cost the trajectory block twice over: a metric whose readings fall before and after April (March and June) injected nothing, although the March reading was the value in force all April; and an entity page last edited outside April was dropped from the gathered pages, so when the question's noun phrase ("the acme-example team") did not resolve on its own, no entity was found. Each metric's latest reading before the window now joins the readings inside it, and pages the window drops still name the entities whose trajectory is read; they stay out of the evidence. BrainBench Cat 25's hermetic gate goes from 4 of 6 probes (FAIL) to 6 of 6 (PASS).++### Itemized changes++- `src/core/think/index.ts`: the trajectory window filter keeps each metric's latest point before the window start (events are not carried); candidate entities come from the gathered pages plus the pages the window dropped.+- `src/core/think/gather.ts`: `ThinkGatherResult.outsideWindowSlugs` lists the pages the window dropped.+- `src/core/think/temporal-window.ts`: `filterPagesToWindow` also returns the dropped pages.+- Tests: `test/think-trajectory-window.test.ts` (a month with no reading of its own gets the March reading and not January's or June's; an entity page dated outside the month still routes its trajectory). Each test fails with its own fix reverted.+## [0.60.620.0] - 2026-11-09**A diverged managed checkout now publishes its local commits on refresh by default when Git durability is on, after a secret scan of those commits.** Commits a script made with plain `git commit` in a managed checkout used to strand there whenever the remote moved: every `gbrain sources refresh` refused `refresh_diverged` and asked the user, unless `sources.refresh_publish_diverged` was set to `true`. With the setting unset, a worktree whose Git durability is on (`gbrain sources writer git-durability <source> --enable`, or the legacy hook) now publishes them itself: the local commits merged with the upstream in memory, never a rebase or force-push, then the fast-forward. The publish child scans, under its publish lock and for the exact commits it pushes, what they add: commit messages, added lines (including a value a later commit removed) and merge-commit conflict resolutions. A value that looks like a secret, added text too large to scan, or a commit that changes `.gbrain-scan-allow` or a `.gitattributes` refuses the new `publish_secret_found` naming the file, line, rule and commit, never the value, with nothing pushed; commits the scan cannot read in full refuse `publish_scan_unreadable` instead. The rewritten-upstream refusal and the `--expect-remote` bound are unchanged. `false` turns it off; `true` still publishes with durability off.diff --git a/docs/architecture/key-files/core-services-3.md b/docs/architecture/key-files/core-services-3.mdindex d7ba74c5f7..71d158e3e7 100644--- a/docs/architecture/key-files/core-services-3.md+++ b/docs/architecture/key-files/core-services-3.md@@ -7,7 +7,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/think/pages-budget.ts` + `pagesBlockExcerptLen` / `renderPagesBlockDetailed` in `think/gather.ts` (#5461) — the synthesize pages-block budget as configuration. `readThinkPagesBudget(engine, warnings)` reads `think.pages_budget_chars` (4 000-200 000, default 12 000) and `think.excerpt_ceiling_chars` (600-200 000, default 2 400) once per `runThink`; a stored out-of-range or non-integer value keeps the default and warns `THINK_BUDGET_CONFIG_IGNORED:<key>`, and `gbrain config set` refuses it up front (`commands/config.ts`, same hook shape as `cycle.consolidate.cluster_threshold`). The per-page excerpt is `max(600, min(ceiling, floor(total / pages)))`, so the total is SOFT (the floor wins) and whole pages are never promised while the ceiling holds; the unit shown is the gathered chunk or compiled text. `renderPagesBlockDetailed` returns `{ text, truncated }` (`truncated` = any excerpt cut at either end, or a delivered block over its cap / cut to its window) and `runThink` reports it as `ThinkResult.evidence_truncated`; the `synthesize` verb adds `evidence_truncated` and `citations[] { slug, source_id, row_num }` (source-qualified `sources[]`, `source_id` null for a slug outside the gather; `sources[]` stays frozen). Conversation-type pages go through evidence delivery (`think.return_unit`) and its token budget instead. Pinned by `test/think-pages-budget-5461.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. With a window, `think/gather.ts` adds a dated floor (`listPages` over the window, 50 rows) to the hybrid search; it passes `excludeSlugPrefixes: resolveHardExcludes()`, the same hard excludes search applies, so excluded pages are dropped in SQL before LIMIT and cannot fill the floor (#6890, `test/think-temporal-window.serial.test.ts`, `test/list-pages-exclude-prefixes-6890.test.ts` + Postgres twin).+- `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 returns and counts the dated ones it drops; gather exposes their slugs as `outsideWindowSlugs`, which `runThink` adds to its trajectory entity candidates, and `runThink`'s trajectory filter keeps each metric's latest reading before the window (the value in force when it opens; GST-731, `test/think-trajectory-window.test.ts`). 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. With a window, `think/gather.ts` adds a dated floor (`listPages` over the window, 50 rows) to the hybrid search; it passes `excludeSlugPrefixes: resolveHardExcludes()`, the same hard excludes search applies, so excluded pages are dropped in SQL before LIMIT and cannot fill the floor (#6890, `test/think-temporal-window.serial.test.ts`, `test/list-pages-exclude-prefixes-6890.test.ts` + Postgres twin).- `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`.diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex 2e82668a4c..efec24d524 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -1489,6 +1489,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;{ since: '0.60.618.0', id: 'refresh_replan_own_commits_8828', text: 'A `gbrain sources refresh` whose checkout HEAD moved while it waited for writes admitted before its fence no longer refuses `refresh_source_changed` when every commit since its start is one of gbrain\'s own (in the commit ledger) and the upstream branch holds them: it takes HEAD as its start and fast-forwards to the upstream. A HEAD move that includes a commit gbrain did not make, or gbrain\'s commits the upstream does not hold yet, still refuses as before.' },{ since: '0.60.619.0', id: 'managed_commit_push_unpublished_gst1923', text: 'On a managed checkout, `gbrain git commit-push -m <msg> -- <paths>` now reports how many commits the upstream lacks as last fetched (`unpublished` in `--json`, `null` when there is no upstream) and says nothing was pushed, instead of answering `nothing to commit; <remote>/<branch> at -` and logging `[push] ok-already-on-remote` for a commit that already existed. It writes no push-log line on a managed checkout. It still never pushes there; `gbrain git commit-push --push-only --keep-checkout --path <checkout>` publishes.' },{ since: '0.60.620.0', id: 'refresh_publish_diverged_default_gbra386', text: 'A diverged managed checkout now publishes its local commits on `gbrain sources refresh` by default when the worktree\'s Git durability is on: `sources.refresh_publish_diverged` unset now means on there (it used to mean off), merged with the upstream in memory, never rebased or forced. The refresh publish first scans what the local commits add (messages, added lines, merge resolutions) and refuses the new `publish_secret_found` naming the file, line and rule, never the value, when one looks like a secret; `gbrain git commit-push --push-only --scan-secrets` runs the same gate. Unset with durability not on still refuses, naming `gbrain sources writer git-durability <source> --enable`; `false` turns it off.' },+ { since: 'TBD', id: 'think_window_trajectory_gst731', text: '`think` on a question that names one month or day (or given `since`/`until`) still gets the entity\'s trajectory: each metric\'s latest reading before the window now joins the readings inside it, as the value in force when the window opens, and an entity page dated outside the window still names whose trajectory to read (it stays out of the evidence). Before, "MRR in April" with readings in March and June, or a company page last edited outside the month, injected no trajectory. `WINDOW_EXCLUDED_<n>_TRAJECTORY_POINTS` no longer counts the carried reading.' },];/** The newest disclosed change's release: the notice id moves only when a release adds rows. */diff --git a/src/core/think/gather.ts b/src/core/think/gather.tsindex 5aa54b1c22..fc08581288 100644--- a/src/core/think/gather.ts+++ b/src/core/think/gather.ts@@ -66,6 +66,8 @@ export interface ThinkGatherResult {takes: TakeHit[];/** Graph nodes — slugs reachable from anchor within graphDepth. Empty when no anchor. */graphSlugs: string[];+ /** Pages the search found that the window dropped as dated outside it: not evidence, but still who the question is about (GST-731). */+ outsideWindowSlugs: string[];/*** Machine-stable warning codes for per-stream failures (D6: code-only on the* wire; the raw error text goes to stderr/server logs). Lets MCP/remote@@ -164,6 +166,7 @@ export async function runGather(});let windowDiagnostic: ThinkGatherResult['diagnostics']['window'];+ let outsideWindowSlugs: string[] = [];// GBRA-200: a degraded page search (keyword-only fallback, a cut arm) is reported, never silent.const searchDegraded = new Set<string>();const onMeta = (m: HybridSearchMeta) => { for (const d of m.degraded ?? []) if (affectsRecall(d)) searchDegraded.add(d.stage); };@@ -200,6 +203,7 @@ export async function runGather(const combined = [...hybrid, ...floor].filter(page => !seen.has(page.slug) && !!seen.add(page.slug));const filtered = filterPagesToWindow(combined, window);windowDiagnostic = { dropped: filtered.droppedOutOfWindow, undatedKept: filtered.undatedKept };+ outsideWindowSlugs = filtered.dropped.map(page => page.slug);return filtered.kept.slice(0, gatherLimit);}) : hybridSearch(engine, opts.question, {limit: gatherLimit,@@ -314,6 +318,7 @@ export async function runGather(pages: pages.slice(0, gatherLimit),takes: fusedTakes,graphSlugs,+ outsideWindowSlugs,warnings,diagnostics: {pagesFromHybrid,diff --git a/src/core/think/index.ts b/src/core/think/index.tsindex f6f46cc9dd..ea7863c66c 100644--- a/src/core/think/index.ts+++ b/src/core/think/index.ts@@ -740,7 +740,7 @@ export async function runThink(const trajIntent = thinkDecide ? await thinkDecide.trajectoryIntent(classifyIntent(opts.question)) : classifyIntent(opts.question);if (trajIntent === 'temporal' || trajIntent === 'knowledge_update') {const { extractCandidateEntities } = await import('./entity-extract.ts');- const retrievedSlugs = gather.pages.map(p => p.slug);+ const retrievedSlugs = [...gather.pages.map(p => p.slug), ...gather.outsideWindowSlugs];const candidates = extractCandidateEntities(opts.question, retrievedSlugs);if (candidates.length > 0) {const { resolveEntitySlugWithSource } = await import('../entities/resolve.ts');@@ -782,9 +782,17 @@ export async function runThink(if (err instanceof OperationTimeoutError) return [];throw err;});+ // A metric's latest reading before the window is the value in force when it opens (GST-731), so it stays.+ const inForce = new Map<string, { fact_id: number; valid_from: Date }>();+ if (window?.startMs != null) {+ for (const point of points) {+ const prior = point.metric === null ? undefined : inForce.get(point.metric);+ if (point.metric !== null && point.valid_from.getTime() < window.startMs && (!prior || point.valid_from >= prior.valid_from)) inForce.set(point.metric, point);+ }+ }const boundedPoints = window ? points.filter(point => {const ms = point.valid_from.getTime();- const outside = (window.startMs !== null && ms < window.startMs)+ const outside = (window.startMs !== null && ms < window.startMs && inForce.get(point.metric ?? '')?.fact_id !== point.fact_id)|| (window.endMs !== null && ms > window.endMs);if (outside) trajectoryExcludedCount++;return !outside;diff --git a/src/core/think/temporal-window.ts b/src/core/think/temporal-window.tsindex 0d6fad34c0..4edaba513b 100644--- a/src/core/think/temporal-window.ts+++ b/src/core/think/temporal-window.ts@@ -80,16 +80,16 @@ export function resolvePageDateMs(page: DatedPage): number | null {export function filterPagesToWindow<T extends DatedPage>(pages: T[], window: TemporalWindow) {const kept: T[] = [];- let droppedOutOfWindow = 0;+ const dropped: T[] = [];let undatedKept = 0;for (const page of pages) {const ms = resolvePageDateMs(page);if (ms === null) { undatedKept++; kept.push(page); continue; }if ((window.startMs !== null && ms < window.startMs) || (window.endMs !== null && ms > window.endMs)) {- droppedOutOfWindow++;+ dropped.push(page);} else kept.push(page);}- return { kept, droppedOutOfWindow, undatedKept };+ return { kept, dropped, droppedOutOfWindow: dropped.length, undatedKept };}// PR #5086 (@tarush1989), wave 14 P3.17: a window from exactly one explicit date in the question.diff --git a/test/think-trajectory-window.test.ts b/test/think-trajectory-window.test.tsnew file mode 100644index 0000000000..36975afcfc--- /dev/null+++ b/test/think-trajectory-window.test.ts@@ -0,0 +1,83 @@+/**+ * GST-731 (Cat 25): a question that names one month bounds think's evidence to that month+ * (PR #5086), and that window must not cost the trajectory block. Two failures at 555b73a8:+ * - the reading in force when the month opens (the latest one before it) was filtered out,+ * so "MRR in April" with readings in Jan, Mar and Jun injected nothing;+ * - the entity page dated outside the month was dropped from the gathered pages, and the+ * question's noun phrase ("foundry example team") resolves to no entity, so nothing was injected.+ */++import { describe, test, expect, beforeAll, afterAll } from 'bun:test';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { runThink, type ThinkLLMClient } from '../src/core/think/index.ts';+import { importFromContent } from '../src/core/import-file.ts';++let engine: PGLiteEngine;++async function seedCompany(slug: string, title: string, readings: Array<[string, string, string, number]>) {+ await importFromContent(engine, slug, `---\ntype: company\ntitle: ${title}\n---\n# ${title}\n\n${title} is a company. Dated metric readings live in the facts index.\n`, { noEmbed: true });+ await engine.executeRaw(`UPDATE pages SET effective_date = '2026-11-01T00:00:00Z' WHERE slug = $1`, [slug]);+ for (const [since, text, metric, value] of readings) {+ await engine.executeRaw(+ `INSERT INTO facts (source_id, entity_slug, fact, kind, visibility, valid_from, source, claim_metric, claim_value)+ VALUES ('default', $1, $2, 'fact', 'private', $3, 'test', $4, $5)`,+ [slug, text, `${since}T00:00:00Z`, metric, value],+ );+ }+}++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({ database_url: '' });+ await engine.initSchema();+ await seedCompany('companies/nimbus-example', 'Nimbus Example', [+ ['2026-01-05', 'MRR is $40K', 'mrr', 40000],+ ['2026-03-20', 'MRR is $75K', 'mrr', 75000],+ ['2026-06-12', 'MRR is $130K', 'mrr', 130000],+ ]);+ await seedCompany('companies/foundry-example', 'Foundry Example', [+ ['2026-01-10', 'team is 8 people', 'team_size', 8],+ ['2026-04-15', 'team is 15 people', 'team_size', 15],+ ]);+}, 60_000);++afterAll(async () => {+ await engine.disconnect();+});++async function thinkPrompt(question: string): Promise<{ user: string; warnings: string[] }> {+ let user = '';+ const client: ThinkLLMClient = {+ create: async (params) => {+ const msg = params.messages[0]?.content;+ user = typeof msg === 'string' ? msg : JSON.stringify(msg);+ return {+ id: 'stub', type: 'message', role: 'assistant', model: 'stub', stop_reason: 'end_turn', 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: JSON.stringify({ answer: 'stubbed answer', citations: [], gaps: [] }) }],+ } as never;+ },+ };+ const result = await runThink(engine, { remote: false, question, client });+ return { user, warnings: result.warnings };+}++describe('runThink: a month named in the question keeps the trajectory', () => {+ test('a month with no reading of its own gets the reading in force when it opens', async () => {+ const { user, warnings } = await thinkPrompt('What was the MRR of Nimbus Example in April 2026?');+ expect(warnings).toContain('WINDOW_FROM_QUESTION');+ expect(user).toContain('<trajectory entity="companies/nimbus-example"');+ expect(user).toContain('2026-03-20');+ expect(user).not.toContain('2026-01-05');+ expect(user).not.toContain('2026-06-12');+ expect(warnings).toContain('WINDOW_EXCLUDED_2_TRAJECTORY_POINTS');+ });++ test('an entity page dated outside the month still routes its trajectory', async () => {+ const { user, warnings } = await thinkPrompt('How big was the Foundry Example team in January 2026?');+ expect(warnings).toContain('WINDOW_FROM_QUESTION');+ expect(user).toContain('<trajectory entity="companies/foundry-example"');+ expect(user).toContain('2026-01-10');+ expect(user).not.toContain('2026-04-15');+ });+});