Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
/**
* v0.40.3.0 — contextual retrieval E2E against PGLite (hermetic; no API
* keys needed; no Postgres needed).
*
* Pins the wave's most critical invariants end-to-end:
*
* IRON RULE #1 (D20-T1): wrapper text NEVER lands in
* content_chunks.chunk_text. The wrapped string went to the embedder,
* but the raw chunk_text stays canonical for FTS / snippets / reranker /
* debug.
*
* IRON RULE #2 (D14): page-level CR mode is stamped on every page after
* import. NULL on pre-v81 pages; current mode on freshly-imported pages.
*
* IRON RULE #3 (D20-T4): fenced code chunks inside markdown pages DON'T
* get wrapped — only compiled_truth + timeline chunks do.
*
* IRON RULE #4 (D18 kill switch): when search.contextual_retrieval_disabled
* is true, imports skip wrapping AND mode column is stamped 'none'.
*
* IRON RULE #5 (T9 reindex sweep): the predicate catches both
* chunker_version < 3 AND contextual_retrieval_mode IS NULL.
*
* Stubs the embedding gateway so the test runs in <1s with no API key.
*/
import { describe, test, expect, beforeAll, afterAll, beforeEach } from 'bun:test';
import { PGLiteEngine } from '../../src/core/pglite-engine.ts';
import { importFromContent } from '../../src/core/import-file.ts';
import {
__setEmbedTransportForTests,
configureGateway,
resetGateway,
} from '../../src/core/ai/gateway.ts';
import { MARKDOWN_CHUNKER_VERSION } from '../../src/core/chunkers/recursive.ts';
import { operationsByName } from '../../src/core/operations.ts';
import type { OperationContext } from '../../src/core/operations.ts';
import { randomUUID } from 'node:crypto';
import { runEmbedCore } from '../../src/commands/embed.ts';
import { disposePersistenceConsumer } from '../../src/core/persistence/service.ts';
import { runReindex } from '../../src/commands/reindex.ts';
import { resetPgliteState } from '../helpers/reset-pglite.ts';
const STUB_DIMS = 1536;
let engine: PGLiteEngine;
// Capture the texts the embedder receives so we can assert wrapping
// happened. The stub transport receives the wrapped string array AFTER
// import-file's wrap step.
const embedderInputs: string[][] = [];
beforeAll(async () => {
engine = new PGLiteEngine();
await engine.connect({});
await engine.initSchema();
// Configure gateway with a fake API key so embedding provider resolution
// succeeds; the transport stub intercepts the actual embedMany call so
// no real API request fires.
configureGateway({
embedding_model: 'openai:text-embedding-3-large',
embedding_dimensions: STUB_DIMS,
env: { OPENAI_API_KEY: 'sk-test-fake-key-for-stub' },
});
__setEmbedTransportForTests(async ({ values }: any) => {
embedderInputs.push([...values]);
return {
embeddings: values.map(() => new Array<number>(STUB_DIMS).fill(0.001)),
usage: { tokens: 0 },
} as any;
});
});
afterAll(async () => {
__setEmbedTransportForTests(null);
resetGateway();
await engine.disconnect();
});
beforeEach(() => {
embedderInputs.length = 0;
});
describe('contextual retrieval wrapper applies at embed time (D20-T1)', () => {
test('balanced mode (title tier) wraps embedder input but stores raw chunk_text', async () => {
// Default mode is balanced → title tier per MODE_BUNDLES.balanced.
// Import a page with a known title; verify (a) the embedder saw a
// wrapped string containing the title, AND (b) content_chunks.chunk_text
// in the DB is the raw, unwrapped chunk text.
const slug = 'wiki/concepts/acme-funding';
const content = `---
title: "Acme Corp Series A"
type: concept
---
This is the body of the page. It will be chunked and embedded.
The wrapper SHOULD prepend the title before sending to the embedder,
but should NOT mutate what we store as canonical chunk_text.`;
await importFromContent(engine, slug, content, { sourceId: 'default' });
// Verify the embedder saw wrapped text containing the title.
expect(embedderInputs.length).toBeGreaterThan(0);
const wrappedTexts = embedderInputs.flat();
expect(wrappedTexts.length).toBeGreaterThan(0);
expect(wrappedTexts[0]).toContain('<context>Acme Corp Series A');
// Critical: stored chunk_text MUST be the raw unwrapped text.
const chunks = await engine.getChunks(slug, { sourceId: 'default' });
expect(chunks.length).toBeGreaterThan(0);
for (const c of chunks) {
expect(c.chunk_text).not.toContain('<context>');
expect(c.chunk_text).not.toContain('</context>');
}
});
test('pages.contextual_retrieval_mode is stamped after import (D14)', async () => {
const slug = 'wiki/concepts/post-mode-check';
await importFromContent(engine, slug, '---\ntitle: "Test"\n---\n\nBody.', {
sourceId: 'default',
});
const rows = await engine.executeRaw<{ mode: string | null; gen: string | null }>(
`SELECT contextual_retrieval_mode AS mode, corpus_generation AS gen
FROM pages WHERE slug = $1 AND source_id = 'default'`,
[slug],
);
expect(rows[0].mode).toBe('title'); // balanced mode default
expect(rows[0].gen).toMatch(/^[0-9a-f]{16}$/); // hash present
});
test('chunker_version stamps to current version after import', async () => {
const slug = 'wiki/concepts/chunker-version-check';
await importFromContent(engine, slug, '---\ntitle: "V"\n---\n\nBody.', {
sourceId: 'default',
});
const rows = await engine.executeRaw<{ cv: number }>(
`SELECT chunker_version AS cv FROM pages WHERE slug = $1 AND source_id = 'default'`,
[slug],
);
expect(rows[0].cv).toBe(MARKDOWN_CHUNKER_VERSION);
expect(rows[0].cv).toBe(4); // v0.48.3.0 safe index requires strict full-body sanitation.
});
});
describe('per-page frontmatter override (D5)', () => {
test('per-page contextual_retrieval: none overrides global title default', async () => {
const slug = 'wiki/concepts/override-test';
const content = `---
title: "Override Test"
contextual_retrieval: none
---
Body that should NOT be wrapped because frontmatter says 'none'.`;
await importFromContent(engine, slug, content, { sourceId: 'default' });
// The embedder should have seen UNWRAPPED text.
const wrappedTexts = embedderInputs.flat();
expect(wrappedTexts.length).toBeGreaterThan(0);
expect(wrappedTexts[0]).not.toContain('<context>');
const rows = await engine.executeRaw<{ mode: string | null }>(
`SELECT contextual_retrieval_mode AS mode FROM pages WHERE slug = $1 AND source_id = 'default'`,
[slug],
);
expect(rows[0].mode).toBe('none');
});
});
describe('T9 reindex sweep predicate', () => {
test('counts pages with contextual_retrieval_mode IS NULL', async () => {
// Insert a page with mode explicitly NULL (simulates pre-v81 row).
await engine.executeRaw(
`INSERT INTO pages (source_id, slug, type, title, compiled_truth, chunker_version, contextual_retrieval_mode)
VALUES ('default', $1, 'concept', 'Pre-v81 page', 'body', 3, NULL)
ON CONFLICT (source_id, slug) DO UPDATE SET contextual_retrieval_mode = NULL`,
['wiki/concepts/prev81-row'],
);
const { countPending } = await import('../../src/commands/reindex.ts').then((m) => ({
countPending: (m as any).countPending,
})).catch(() => ({ countPending: null }));
// countPending isn't exported, so use the raw predicate:
const rows = await engine.executeRaw<{ count: number }>(
`SELECT COUNT(*)::int AS count FROM pages
WHERE page_kind = 'markdown'
AND (chunker_version < $1 OR contextual_retrieval_mode IS NULL)
AND deleted_at IS NULL`,
[MARKDOWN_CHUNKER_VERSION],
);
expect(rows[0].count).toBeGreaterThanOrEqual(1);
});
});
describe('per-source CR mode on the import path (#3885)', () => {
beforeEach(async () => {
await resetPgliteState(engine);
});
async function seedSource(id: string, mode: string): Promise<void> {
await engine.executeRaw(
`INSERT INTO sources (id, name, config, contextual_retrieval_mode)
VALUES ($1, $1, '{}'::jsonb, $2)
ON CONFLICT (id) DO UPDATE SET contextual_retrieval_mode = EXCLUDED.contextual_retrieval_mode`,
[id, mode],
);
}
async function pageMode(slug: string, sourceId: string): Promise<string | null> {
const rows = await engine.executeRaw<{ mode: string | null }>(
`SELECT contextual_retrieval_mode AS mode FROM pages WHERE slug = $1 AND source_id = $2`,
[slug, sourceId],
);
return rows[0]?.mode ?? null;
}
function putPageCtx(sourceId: string): OperationContext {
return {
engine,
config: { engine: 'pglite' as const, embedding_disabled: true },
logger: { info: () => {}, warn: () => {}, error: () => {} },
dryRun: false,
remote: false,
sourceId,
};
}
test('importFromContent honors sources.set-cr-mode=none over global title', async () => {
const sourceId = 'src-none-import';
await seedSource(sourceId, 'none');
const slug = 'wiki/concepts/source-none-import';
await importFromContent(
engine,
slug,
'---\ntitle: "Source None"\n---\n\nBody that must not wrap.',
{ sourceId },
);
expect(await pageMode(slug, sourceId)).toBe('none');
const wrapped = embedderInputs.flat();
expect(wrapped.length).toBeGreaterThan(0);
expect(wrapped[0]).not.toContain('<context>');
});
test('put_page (capture write path) honors per-source none', async () => {
const sourceId = 'src-none-capture';
await seedSource(sourceId, 'none');
const slug = 'inbox/source-none-capture';
const result = await operationsByName['put_page']!.handler(putPageCtx(sourceId), {
slug, request_id: randomUUID(),
content: '---\ntitle: "Capture None"\n---\n\nCaptured body for CR source override.',
});
expect(result).toMatchObject({ state: 'committed', status: 'created_or_updated' });
expect(await pageMode(slug, sourceId)).toBe('none');
expect(embedderInputs).toEqual([]); // canonical publication does not wait on a provider
await disposePersistenceConsumer(engine);
const embedded = await runEmbedCore(engine, { slugs: [slug], sourceId, quiet: true });
expect(embedded.embedded).toBeGreaterThan(0);
expect(embedderInputs.flat()[0]).not.toContain('<context>');
});
test('reindex --markdown honors per-source none', async () => {
const sourceId = 'src-none-reindex';
await seedSource(sourceId, 'none');
const slug = 'wiki/concepts/source-none-reindex';
await engine.executeRaw(
`INSERT INTO pages (source_id, slug, type, title, compiled_truth, chunker_version, contextual_retrieval_mode)
VALUES ($1, $2, 'concept', 'Reindex None', 'Body that must not wrap after markdown reindex.', 1, NULL)`,
[sourceId, slug],
);
// W4.5: a re-embedding reindex needs the user's approval; --yes is it.
const result = await runReindex(engine, ['--markdown', '--json', '--limit', '10', '--yes']);
expect(result.reindexed).toBeGreaterThanOrEqual(1);
expect(await pageMode(slug, sourceId)).toBe('none');
const wrapped = embedderInputs.flat();
expect(wrapped.length).toBeGreaterThan(0);
expect(wrapped.every((text) => !text.includes('<context>'))).toBe(true);
});
test('source per_chunk_synopsis beats global conservative (inline demotes to title wrap)', async () => {
const sourceId = 'src-synopsis-import';
await seedSource(sourceId, 'per_chunk_synopsis');
await engine.setConfig('search.mode', 'conservative');
try {
const slug = 'wiki/concepts/source-synopsis-import';
await importFromContent(
engine,
slug,
'---\ntitle: "Source Synopsis"\n---\n\nBody that should wrap at the title tier.',
{ sourceId },
);
// Inline import refuses paid synopsis generation; it must still SEE the
// source override and land at title instead of global none.
expect(await pageMode(slug, sourceId)).toBe('title');
expect(embedderInputs.flat()[0]).toContain('<context>Source Synopsis');
} finally {
await engine.setConfig('search.mode', 'balanced');
}
});
});