Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript
4.9 KB
Raw Blame
/**
 * #3874 — `gbrain call` must compute the SAME federated read scope as the
 * direct CLI path. Pre-fix, call.ts resolved via bare resolveSourceId and
 * never computed localFederatedSourceIds, so an unqualified
 * `gbrain call resolve_slugs ...` on a federated multi-source brain silently
 * saw only the scalar source while `gbrain query` spanned the federated set.
 */
import { describe, test, expect } from 'bun:test';
import { runCall } from '../src/commands/call.ts';
import type { BrainEngine } from '../src/core/engine.ts';
import { withEnv } from './helpers/with-env.ts';
import { OperationError } from '../src/core/ops/contract.ts';
import { _resetCliExitVerdictForTests, currentExitCode } from '../src/core/cli-force-exit.ts';

type SourceRow = { id: string; local_path: string | null; archived: boolean; config: Record<string, unknown> };

const SOURCES: SourceRow[] = [
  { id: 'default', local_path: null, archived: false, config: {} },
  { id: 'vault', local_path: '/nonexistent/vault-3874', archived: false, config: {} },
  { id: 'wiki', local_path: '/nonexistent/wiki-3874', archived: false, config: { federated: true } },
];

function makeEngine(capture: { resolveSlugsOpts: unknown[] }): BrainEngine {
  return {
    executeRaw: async (sql: string, params?: unknown[]) => {
      if (sql.includes('WHERE id = $1 AND archived = false')) {
        return SOURCES.filter((s) => s.id === params?.[0] && !s.archived).map((s) => ({ id: s.id }));
      }
      // localFederatedSourceIds: SELECT id, config, archived FROM sources ...
      if (sql.includes('SELECT id, config, archived FROM sources')) {
        return SOURCES.filter((s) => !s.archived).map((s) => ({
          id: s.id, config: s.config, archived: s.archived,
        }));
      }
      // Tier-4 registered query (old or #3880 shape) — paths never match cwd.
      if (sql.includes('FROM sources WHERE local_path IS NOT NULL')) {
        return SOURCES.filter((s) => s.local_path !== null).map((s) => ({
          id: s.id, local_path: s.local_path, archived: s.archived,
        }));
      }
      if (sql.includes('FROM pages')) return [];
      return [];
    },
    getConfig: async (key: string) => (key === 'sources.default' ? 'vault' : null),
    resolveSlugs: async (_partial: string, opts?: unknown) => {
      capture.resolveSlugsOpts.push(opts);
      return [];
    },
  } as unknown as BrainEngine;
}

describe('#3874 gbrain call federated scope parity', () => {
  test('direct call errors retain the typed receipt in delivered JSON and set a failing exit verdict', async () => {
    await withEnv({ GBRAIN_SOURCE: undefined }, async () => {
      const receipt = { request_id: '10000000-0000-4000-8000-000000000001', state: 'conflict' as const, retry_after_ms: null };
      const error = new OperationError('revision_conflict', 'The observed revision is stale.');
      error.writeRequest = receipt;
      error.writeError = 'revision_conflict';
      const engine = makeEngine({ resolveSlugsOpts: [] });
      engine.resolveSlugs = async () => { throw error; };
      const outs: string[] = [];
      const priorExitCode = process.exitCode;
      try {
        await runCall(engine, ['resolve_slugs', '{"partial":"example"}'], async payload => { outs.push(payload); });
        expect(outs).toHaveLength(1);
        expect(JSON.parse(outs[0])).toMatchObject({ error: 'revision_conflict', write_error: 'revision_conflict', write_request: receipt });
        expect(currentExitCode()).toBe(1);
      } finally { _resetCliExitVerdictForTests(); process.exitCode = priorExitCode ?? 0; }
    });
  });

  test('ambient-tier resolution widens unqualified reads across federated sources', async () => {
    await withEnv({ GBRAIN_SOURCE: undefined }, async () => {
      const capture = { resolveSlugsOpts: [] as unknown[] };
      const engine = makeEngine(capture);
      const outs: string[] = [];
      await runCall(engine, ['resolve_slugs', JSON.stringify({ partial: 'foo' })], async (s) => {
        outs.push(s);
      });
      expect(capture.resolveSlugsOpts.length).toBe(1);
      const opts = capture.resolveSlugsOpts[0] as { sourceId?: string; sourceIds?: string[] };
      // Pre-fix: { sourceId: 'vault' } (scalar). Post-fix: the federated set.
      expect(opts.sourceIds).toEqual(['vault', 'wiki']);
    });
  });

  test('explicit --source keeps the scalar scope (no widening)', async () => {
    await withEnv({ GBRAIN_SOURCE: undefined }, async () => {
      const capture = { resolveSlugsOpts: [] as unknown[] };
      const engine = makeEngine(capture);
      await runCall(
        engine,
        ['--source', 'vault', 'resolve_slugs', JSON.stringify({ partial: 'foo' })],
        async () => {},
      );
      expect(capture.resolveSlugsOpts.length).toBe(1);
      const opts = capture.resolveSlugsOpts[0] as { sourceId?: string; sourceIds?: string[] };
      expect(opts.sourceIds).toBeUndefined();
      expect(opts.sourceId).toBe('vault');
    });
  });
});