Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript
8.2 KB
Raw Blame
/**
 * #1663 — CRAG gate behavior on the `query` op (hermetic PGLite, keyless:
 * the keyword-only fallback path). Pins:
 *   - the crag block rides the retrieval response meta on EVERY call
 *   - a slug-identity query grades strong end-to-end (exact-lookup tier)
 *   - weak + search.crag_escalation=true → one high-ceiling re-run
 *   - weak without the config → no re-run, hint only (default OFF)
 */
import { describe, test, expect, beforeAll, afterAll, beforeEach } from 'bun:test';
import { PGLiteEngine } from '../../src/core/pglite-engine.ts';
import { resetPgliteState } from '../helpers/reset-pglite.ts';
import { installFixtureChunks } from '../helpers/page-projection.ts';
import { operationsByName } from '../../src/core/operations.ts';
import type { OperationContext } from '../../src/core/operations.ts';
import type { CragMetaBlock } from '../../src/core/search/crag.ts';

let engine: PGLiteEngine;

beforeAll(async () => {
  engine = new PGLiteEngine();
  await engine.connect({});
  await engine.initSchema();
});
afterAll(async () => { await engine.disconnect(); });
beforeEach(async () => { await resetPgliteState(engine); });

function ctxWithMeta(): { ctx: OperationContext; meta: Record<string, unknown> } {
  const meta: Record<string, unknown> = {};
  const ctx = {
    engine,
    remote: false,
    sourceId: 'default',
    emitResponseMeta: (key: string, value: unknown) => { meta[key] = value; },
  } as unknown as OperationContext;
  return { ctx, meta };
}

function cragOf(meta: Record<string, unknown>): CragMetaBlock {
  const retrieval = meta.retrieval as { crag?: CragMetaBlock } | undefined;
  expect(retrieval).toBeDefined();
  expect(retrieval!.crag).toBeDefined();
  return retrieval!.crag!;
}

describe('query op — CRAG gate (#1663)', () => {
  test('crag block is attached on every call (grade + query shape)', async () => {
    await engine.putPage('notes/kelpie-workshop', {
      type: 'note', title: 'Kelpie Workshop', compiled_truth: 'A note about the kelpie workshop agenda.',
    });
    const { ctx, meta } = ctxWithMeta();
    await operationsByName.query.handler(ctx, { query: 'kelpie workshop agenda' });
    const crag = cragOf(meta);
    expect(['strong', 'moderate', 'weak']).toContain(crag.confidence);
    expect(['factual', 'open']).toContain(crag.query_shape);
    expect(typeof crag.reason).toBe('string');
  });

  test('slug-identity query grades strong end-to-end (exact-lookup tier through the op)', async () => {
    await engine.putPage('people/alice-example', {
      type: 'person', title: 'Alice Example', compiled_truth: 'Founder of widget-co.',
    });
    const { ctx, meta } = ctxWithMeta();
    const results = (await operationsByName.query.handler(ctx, {
      query: 'people/alice-example',
    })) as Array<{ slug: string; exact_lookup?: string }>;
    expect(results[0]?.slug).toBe('people/alice-example');
    expect(results[0]?.exact_lookup).toBe('slug');
    const crag = cragOf(meta);
    expect(crag.confidence).toBe('strong');
    expect(crag.reason).toBe('exact_lookup');
  });

  test('weak result WITHOUT config: no escalation, think hint only (default OFF)', async () => {
    const { ctx, meta } = ctxWithMeta();
    await operationsByName.query.handler(ctx, { query: 'zxqv nonexistent quux' });
    const crag = cragOf(meta);
    expect(crag.confidence).toBe('weak');
    expect(crag.escalated).toBeUndefined();
    expect(crag.escalate_to_think).toBe(true);
  });

  test('weak result + search.crag_escalation=true: one high-ceiling re-run fires (expand:false caller)', async () => {
    await engine.setConfig('search.crag_escalation', 'true');
    const { ctx, meta } = ctxWithMeta();
    // #4610: the callerExpanded guard means the re-run only fires when the
    // first pass did NOT already use the expansion knob.
    await operationsByName.query.handler(ctx, { query: 'zxqv nonexistent quux', expand: false });
    const crag = cragOf(meta);
    // Keyless corpus with no match: escalation ran and honestly stayed weak.
    expect(crag.escalated).toBe(true);
    expect(crag.escalated_confidence).toBe('weak');
    expect(crag.confidence).toBe('weak');
    expect(crag.escalate_to_think).toBe(true);
  }, 30000);

  test('#5390: types: [] escalates exactly like an omitted filter (the re-run reuses the normalized types)', async () => {
    await engine.setConfig('search.crag_escalation', 'true');
    let keywordCalls = 0;
    const counted = new Proxy(engine, {
      get(target, key) {
        const value = Reflect.get(target, key, target);
        if (key === 'searchKeyword') return (...args: unknown[]) => { keywordCalls++; return (value as (...a: unknown[]) => unknown).apply(target, args); };
        return typeof value === 'function' ? value.bind(target) : value;
      },
    });
    const calls: number[] = [];
    for (const types of [undefined, []]) {
      keywordCalls = 0;
      const { ctx, meta } = ctxWithMeta();
      await operationsByName.query.handler({ ...ctx, engine: counted } as OperationContext,
        { query: 'zxqv nonexistent quux', expand: false, ...(types ? { types } : {}) });
      expect(cragOf(meta).escalated).toBe(true);
      calls.push(keywordCalls);
    }
    expect(calls[1]).toBe(calls[0]);
  }, 30000);

  test('remote and unset-trust escalation cannot adopt a matching private page', async () => {
    await engine.setConfig('search.crag_escalation', 'true');
    await engine.putPage('notes/private-crag', {
      type: 'note', title: 'Synthetic restricted record', compiled_truth: 'PRIVATE_CRAG_CANARY',
      frontmatter: { visibility: 'private' },
    });
    await installFixtureChunks(engine, 'notes/private-crag', [
      { chunk_index: 0, chunk_text: 'PRIVATE_CRAG_CANARY', chunk_source: 'compiled_truth' },
    ]);
    await engine.upsertChunks('notes/private-crag', [{ chunk_index: 0, chunk_source: 'compiled_truth', chunk_text: 'Synthetic restricted record PRIVATE_CRAG_CANARY' }]);
    for (const remote of [true, undefined]) {
      const { ctx, meta } = ctxWithMeta();
      const rows = await operationsByName.query.handler({ ...ctx, remote } as OperationContext, { query: 'Synthetic restricted record', expand: false });
      expect(rows).toEqual([]);
      expect(cragOf(meta).escalated).toBe(true);
      expect(cragOf(meta).confidence).toBe('weak');
    }
    const { ctx } = ctxWithMeta();
    const local = await operationsByName.query.handler(ctx, { query: 'Synthetic restricted record', expand: false });
    expect(JSON.stringify(local)).toContain('PRIVATE_CRAG_CANARY');
  }, 30000);

  test('#4610 + GBRA-81 item 1b: a default-shape caller did not expand (the mode decides), so the guard lets the re-run fire', async () => {
    await engine.setConfig('search.crag_escalation', 'true');
    const { ctx, meta } = ctxWithMeta();
    // No expand param: the resolved mode decides, and nothing expanded on this
    // keyless brain. The callerExpanded guard reads expansion_applied, so the
    // high-ceiling re-run is not redundant and runs once. The skip case (the
    // first pass really expanded) is pinned in operation-expansion-contract.serial.test.ts.
    await operationsByName.query.handler(ctx, { query: 'zxqv nonexistent quux' });
    const crag = cragOf(meta);
    expect((meta.retrieval as { expansion_applied?: boolean }).expansion_applied).toBe(false);
    expect(crag.escalated).toBe(true);
    expect(crag.escalated_confidence).toBe('weak');
    expect(crag.confidence).toBe('weak');
    expect(crag.escalate_to_think).toBe(true);
  }, 30000);

  test('escalation can rescue: identity page invisible to page-1 keyword rank still grades strong via the wide re-run', async () => {
    // Sanity-bound version: with the tier + escalation both on, a present
    // page keeps strong confidence and never regresses via the re-run.
    await engine.setConfig('search.crag_escalation', 'true');
    await engine.putPage('projects/mingtang', {
      type: 'note', title: 'The Mingtang', compiled_truth: 'Indoor amphitheater notes.',
    });
    const { ctx, meta } = ctxWithMeta();
    const results = (await operationsByName.query.handler(ctx, {
      query: 'projects/mingtang',
    })) as Array<{ slug: string }>;
    expect(results[0]?.slug).toBe('projects/mingtang');
    const crag = cragOf(meta);
    expect(crag.confidence).toBe('strong');
    expect(crag.escalated).toBeUndefined(); // strong first pass → no re-run
  });
});