Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript
3.5 KB
Raw Blame
import type { BrainEngine } from '../../src/core/engine.ts';

/** Minimal coherent read/transaction surface for provider orchestration tests. */
export function mockEmbedProjectionEngine(overrides: Partial<Record<string, any>> = {}): BrainEngine {
  // Raw SQL the stale drain issues (the page-provenance stamp check) reads an
  // empty result set unless a test models it — the Proxy's null default would
  // throw on indexing and count the page as a failed embed.
  const revision = '00000000-0000-4000-8000-000000000001';
  const pages = new Map<string, number>();
  const pageKinds = new Map<number, string>();
  overrides = {
    executeRaw: async (sql: string) => sql.startsWith('SELECT count(*)::int AS n FROM pages p')
      && sql.includes('p.text_projection_revision IS DISTINCT FROM p.knowledge_revision') ? [{ n: 0 }] : [],
    getConfigKeys: async () => [],
    transaction: async (run: (tx: BrainEngine) => Promise<unknown>) => run(engine),
    readPageSnapshot: async (slug: string, opts?: { sourceId?: string }) => {
      const page = overrides.getPage ? await overrides.getPage(slug, opts) : { slug, compiled_truth: 'Fixture body', timeline: '' };
      if (!page) return null;
      if (!pages.has(slug)) pages.set(slug, pages.size + 1);
      pageKinds.set(pages.get(slug)!, page.page_kind ?? (page.type === 'code' ? 'code' : 'markdown'));
      return { revision, sourceIncarnation: revision, tags: [], withdrawals: [], page: {
        id: pages.get(slug), slug, source_id: opts?.sourceId ?? 'default', title: slug,
        knowledge_revision: revision, text_projection_revision: revision, ...page,
      } };
    },
    ...overrides,
  };
  const executeRaw = overrides.executeRaw;
  overrides.executeRaw = async (sql: string, params?: unknown[]) => sql.startsWith('SELECT page_kind FROM pages WHERE id=')
    ? [{ page_kind: pageKinds.get(Number(params?.[0])) ?? 'markdown' }]
    : sql === 'SELECT archived FROM sources WHERE id=$1' ? [{ archived: false }]
    : sql.includes('FROM persistence_brain') ? [{ enabled: false }]
    // The per-page embedding lease (src/core/page-embedding-lease.ts) is always free, and its install-time renewal always holds, in this single-process mock.
    : sql.startsWith('INSERT INTO gbrain_cycle_locks') || sql.startsWith('UPDATE gbrain_cycle_locks') ? [{ id: params?.[0] }]
    : executeRaw(sql, params);
  const calls: { method: string; args: any[] }[] = [];
  const track = (method: string) => (...args: any[]) => {
    calls.push({ method, args });
    if (overrides[method]) return overrides[method](...args);
    return Promise.resolve(null);
  };
  const engine = new Proxy({} as any, {
    get(_, prop: string) {
      if (prop === '_calls') return calls;
      if (overrides[prop] && typeof overrides[prop] !== 'function') return overrides[prop];
      return track(prop);
    },
  });
  return engine;
}

/**
 * Vector writes installPageEmbeddings issued, one entry per updated row. Its
 * batched statement binds `[page_id, rows]`; each row is expanded to the
 * positional layout `[id, vector, image, model, page_id, chunk_text, input_hash]`.
 */
export function embeddingUpdates(engine: BrainEngine) {
  return (engine as any)._calls.filter((call: any) => call.method === 'executeRaw'
    && /^UPDATE content_chunks SET/.test(call.args[0]))
    .flatMap((call: any) => !call.args[0].includes('jsonb_to_recordset') ? [call]
      : (JSON.parse(call.args[1][1]) as any[]).map(row => ({ ...call,
        args: [call.args[0], [row.id, row.embedding, row.image, row.model, call.args[1][0], row.chunk_text, row.input_hash]] })));
}