Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(think): apply search hard excludes to the temporal window floor (#6890)

time-attack72f29c5c38a2
diff --git a/docs/architecture/key-files/core-services-3.md b/docs/architecture/key-files/core-services-3.md
index 202c4a9471..7fd4cc80c0 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.
+- `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-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/engine-sql/pages.ts b/src/core/engine-sql/pages.ts
index 6e2b250551..3fb62400a4 100644
--- a/src/core/engine-sql/pages.ts
+++ b/src/core/engine-sql/pages.ts
@@ -464,6 +464,12 @@ export async function listPages(exec: ScopedRead, filters?: PageFilters): Promis
const slugCondition = slugPrefix
? sqlFragment`AND p.slug LIKE ${slugPrefix.replace(/[\\%_]/g, (c) => '\\' + c) + '%'} ESCAPE '\\'`
: sqlFragment``;
+ // Search fallbacks must exclude before LIMIT: post-filtering can lose the
+ // entire evidence floor when newer excluded pages occupy every slot.
+ const excludedSlugs = filters?.excludeSlugPrefixes?.filter(prefix => prefix.length > 0) ?? [];
+ const excludedSlugCondition = excludedSlugs.length
+ ? sqlFragment` AND NOT EXISTS (SELECT 1 FROM unnest(${excludedSlugs}::text[]) AS excluded(prefix) WHERE starts_with(p.slug, excluded.prefix))`
+ : sqlFragment``;
// #6500 slug keyset (single-source contract, see PageFilters.slugAfter).
const slugAfterCondition = filters?.slugAfter !== undefined
? sqlFragment`AND p.slug > ${filters.slugAfter}`
@@ -502,7 +508,7 @@ export async function listPages(exec: ScopedRead, filters?: PageFilters): Promis
const { rows } = await exec.run(sqlFragment`
SELECT ${columns}, to_char(p.updated_at AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.US"Z"') AS updated_at_iso FROM pages p
${tagJoin}
- WHERE 1=1 ${typeCondition} ${tagCondition} ${updatedCondition} ${slugCondition} ${slugAfterCondition} ${sourceCondition} ${deletedCondition} ${privateCondition} ${effectiveAfterCondition} ${effectiveBeforeCondition}
+ WHERE 1=1 ${typeCondition} ${tagCondition} ${updatedCondition} ${slugCondition}${excludedSlugCondition} ${slugAfterCondition} ${sourceCondition} ${deletedCondition} ${privateCondition} ${effectiveAfterCondition} ${effectiveBeforeCondition}
ORDER BY ${orderBy} LIMIT ${limit} OFFSET ${offset}
`);
return rows.map(rowToPage);
diff --git a/src/core/think/gather.ts b/src/core/think/gather.ts
index fe6e8987c6..ca1081a076 100644
--- a/src/core/think/gather.ts
+++ b/src/core/think/gather.ts
@@ -20,6 +20,7 @@ import type { TrustTier } from '../trust/tier.ts';
import { EXTERNAL_DATA_RULE, needsDataEnvelope, trustAttributes } from '../eligibility/labels.ts';
import { hybridSearch } from '../search/hybrid.ts';
import { INTERNAL_BREADTH_SEARCH_OPTS } from '../search/internal-breadth.ts';
+import { resolveHardExcludes } from '../search/source-boost.ts';
import { boundedProjectedPrefix } from '../page-window/document.ts';
import { overlaidBoundedRows, pageLeadSource } from '../page-window/bounded-lead.ts';
import type { Page, SearchResult } from '../types.ts';
@@ -178,6 +179,7 @@ export async function runGather(
...(window.startMs !== null ? { effective_after: new Date(window.startMs).toISOString() } : {}),
...(window.endMs !== null ? { effective_before: new Date(window.endMs).toISOString() } : {}),
limit: 50, ...pageScope,
+ excludeSlugPrefixes: resolveHardExcludes(),
}).then(async pages => {
const leads = await visibleLeads(pages);
return pages.map((page, rank) => toSearchResult(page, rank, leads[rank]!));
diff --git a/src/core/types.ts b/src/core/types.ts
index 2c613cb57a..7ccf11683d 100644
--- a/src/core/types.ts
+++ b/src/core/types.ts
@@ -349,6 +349,8 @@ export interface PageFilters {
* queries to a tier directory without loading every page into memory.
*/
slugPrefix?: string;
+ /** Literal slug prefixes to omit before ordering/pagination. Opt-in: ordinary listings remain unrestricted. */
+ excludeSlugPrefixes?: string[];
/**
* v0.26.5: include soft-deleted pages (rows with `deleted_at IS NOT NULL`).
* Default false: hides soft-deleted pages from `list_pages` so agents see the
diff --git a/test/e2e/list-pages-exclude-prefixes-6890.test.ts b/test/e2e/list-pages-exclude-prefixes-6890.test.ts
new file mode 100644
index 0000000000..df8dd1cb45
--- /dev/null
+++ b/test/e2e/list-pages-exclude-prefixes-6890.test.ts
@@ -0,0 +1,2 @@
+import { registerPostgresTests } from '../helpers/test-backends.ts';
+await registerPostgresTests(() => import('../list-pages-exclude-prefixes-6890.test.ts'));
diff --git a/test/fixtures/goldens/exports/types.json b/test/fixtures/goldens/exports/types.json
index c7ff1eaa18..91792a56ac 100644
--- a/test/fixtures/goldens/exports/types.json
+++ b/test/fixtures/goldens/exports/types.json
@@ -949,6 +949,7 @@
"effective_after?: string | undefined",
"effective_before?: string | undefined",
"excludePrivate?: boolean | undefined",
+ "excludeSlugPrefixes?: string[] | undefined",
"includeDeleted?: boolean | undefined",
"limit?: number | undefined",
"listColumnsOnly?: boolean | undefined",
@@ -9170,6 +9171,7 @@
"effective_after?: string | undefined",
"effective_before?: string | undefined",
"excludePrivate?: boolean | undefined",
+ "excludeSlugPrefixes?: string[] | undefined",
"includeDeleted?: boolean | undefined",
"limit?: number | undefined",
"listColumnsOnly?: boolean | undefined",
diff --git a/test/list-pages-exclude-prefixes-6890.test.ts b/test/list-pages-exclude-prefixes-6890.test.ts
new file mode 100644
index 0000000000..dcef45b683
--- /dev/null
+++ b/test/list-pages-exclude-prefixes-6890.test.ts
@@ -0,0 +1,54 @@
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
+import { testBackends } from './helpers/test-backends.ts';
+
+for (const backend of testBackends()) {
+ describe(`listPages literal exclusions (${backend})`, () => {
+ let engine: BrainEngine;
+ let close: () => Promise<void>;
+ beforeAll(async () => {
+ if (backend === 'postgres') {
+ ({ engine, close } = await isolatedPersistencePostgres(process.env.DATABASE_URL!));
+ } else {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+ close = () => engine.disconnect();
+ }
+ await engine.executeRaw("INSERT INTO sources (id, name) VALUES ('floor-allowed', 'floor-allowed'), ('floor-denied', 'floor-denied')");
+ for (const sourceId of ['floor-allowed', 'floor-denied']) {
+ for (const slug of ['evidence/a', 'evidence/b', 'synthesis/new', 'literal%/hidden', 'literal_/hidden', "quote'/hidden", 'literalx/kept']) {
+ await engine.putPage(slug, { title: slug, type: 'note', compiled_truth: 'dated evidence', frontmatter: {} }, { sourceId });
+ }
+ await engine.putPage('private/hidden', { title: 'private', type: 'note', compiled_truth: 'private evidence', frontmatter: { visibility: 'private' } }, { sourceId });
+ await engine.putPage('deleted/hidden', { title: 'deleted', type: 'note', compiled_truth: 'deleted evidence', frontmatter: {} }, { sourceId });
+ await engine.softDeletePage('deleted/hidden', { sourceId });
+ }
+ }, 120_000);
+ afterAll(async () => { await close?.(); });
+
+ test('excludes before LIMIT/OFFSET while preserving source and private/deleted fences', async () => {
+ const options = {
+ sourceId: 'floor-denied', sourceIds: ['floor-allowed'], excludePrivate: true,
+ excludeSlugPrefixes: ['synthesis/', 'literal%/', 'literal_/', "quote'/"],
+ sort: 'slug' as const, limit: 2,
+ };
+ const first = await engine.listPages(options);
+ const next = await engine.listPages({ ...options, offset: 2 });
+ expect(first.map(p => p.slug)).toEqual(['evidence/a', 'evidence/b']);
+ expect(next.map(p => p.slug)).toEqual(['literalx/kept']);
+ expect([...first, ...next].every(p => p.source_id === 'floor-allowed')).toBe(true);
+ });
+
+ test('ordinary listings are unchanged; empty prefix entries do not exclude everything', async () => {
+ const options = { sourceId: 'floor-allowed', limit: 100, sort: 'slug' as const };
+ const plain = await engine.listPages(options);
+ expect(plain.map(p => p.slug)).toContain('synthesis/new');
+ expect(plain.map(p => p.slug)).toContain('private/hidden');
+ expect((await engine.listPages({ ...options, excludeSlugPrefixes: ['', ''] })).map(p => p.slug)).toEqual(plain.map(p => p.slug));
+ expect((await engine.listPages({ ...options, slugPrefix: 'literal', excludeSlugPrefixes: ['literal%/', 'literal_/'] })).map(p => p.slug)).toEqual(['literalx/kept']);
+ });
+ });
+}
diff --git a/test/think-temporal-window.serial.test.ts b/test/think-temporal-window.serial.test.ts
index f775873864..af84df6328 100644
--- a/test/think-temporal-window.serial.test.ts
+++ b/test/think-temporal-window.serial.test.ts
@@ -2,6 +2,7 @@ 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 { runGather } from '../src/core/think/gather.ts';
+import { runThink } from '../src/core/think/index.ts';
import {
filterPagesToWindow,
parseTemporalWindow,
@@ -128,4 +129,32 @@ describe('engine and gather enforcement', () => {
expect(gathered.pages.map(page => page.slug)).toContain('brain/ops/2026-06-01');
expect(gathered.diagnostics.window).toBeUndefined();
});
+
+ test('hard-excluded recent pages cannot leak into or starve the temporal floor (#6890)', async () => {
+ // No lexical overlap: these pages can only enter through the dated floor.
+ await seed('reports/allowed-floor', 'quux eligible evidence', '2026-07-18T12:00:00Z');
+ for (let i = 0; i < 51; i++) {
+ await seed(`synthesis/floor-${i}`, 'quux previous synthesis', '2026-07-18T12:00:00Z');
+ }
+ await seed('test/default-excluded-floor', 'quux default excluded', '2026-07-18T12:00:00Z');
+ const prior = process.env.GBRAIN_SEARCH_EXCLUDE;
+ try {
+ process.env.GBRAIN_SEARCH_EXCLUDE = 'synthesis/';
+ const gathered = await runGather(engine, { question: 'unmatchedfloorquestion', window, remote: false });
+ expect(gathered.warnings).not.toContain('GATHER_WINDOW_FLOOR_FAILED');
+ expect(gathered.pages.map(page => page.slug)).toContain('reports/allowed-floor');
+ expect(gathered.pages.some(page => page.slug.startsWith('synthesis/') || page.slug.startsWith('test/'))).toBe(false);
+ const result = await runThink(engine, {
+ question: 'unmatchedfloorquestion', since: '2026-07-17', until: '2026-07-18',
+ remote: false, stubResponse: { answer: 'stubbed', citations: [], gaps: [] },
+ });
+ expect(result.feedback_evidence?.map(page => page.slug)).toContain('reports/allowed-floor');
+ expect(result.feedback_evidence?.some(page => page.slug.startsWith('synthesis/') || page.slug.startsWith('test/'))).toBe(false);
+ // This is search policy, not a global listing/visibility mutation.
+ expect((await engine.listPages({ slugPrefix: 'synthesis/', limit: 100 })).length).toBe(51);
+ } finally {
+ if (prior === undefined) delete process.env.GBRAIN_SEARCH_EXCLUDE;
+ else process.env.GBRAIN_SEARCH_EXCLUDE = prior;
+ }
+ }, 60_000);
});