Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript
11.5 KB
Raw Blame
/**
 * GBRA-156: `gbrain sources add` warns when the new source is not federated.
 *
 * 1. Protects: a new source is not federated unless --federated is passed, so
 *    a remote token with no source grant (and an unbound agent connection)
 *    never reads its pages, and its searches answer empty. The stored default
 *    stays non-federated; the command now says what that means on stderr,
 *    with the two commands that change it.
 *    When the sources such a connection reads (the default source and the
 *    federated ones) hold no page, the add also prints the federate command
 *    as its next step on stdout, and as `next` under --json.
 * 2. Fails when: the default add prints no warning, the warning lacks the
 *    federate or grant command, a --federated or explicit --no-federated add
 *    warns, the stored default flips to federated, the next step is missing
 *    while the no-grant floor holds no page, or it is printed while the floor
 *    holds pages.
 * 3. Existing coverage: the stdout `federated: false` line only.
 * 4. No production seam: the real command on PGLite, console spies only.
 */
import { afterAll, beforeAll, describe, expect, spyOn, test } from 'bun:test';
import { mkdtempSync, rmSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { PGLiteEngine } from '../src/core/pglite-engine.ts';
import { runSources } from '../src/commands/sources.ts';
import { syncOutOfSearchNotice } from '../src/commands/sources-add-next.ts';

let engine: PGLiteEngine;
const dirs: string[] = [];

async function add(args: string[]): Promise<{ stdout: string; stderr: string }> {
  const dir = mkdtempSync(join(tmpdir(), 'gbrain-sources-add-warn-'));
  dirs.push(dir);
  const out: string[] = [];
  const err: string[] = [];
  const log = spyOn(console, 'log').mockImplementation((...a: unknown[]) => { out.push(a.join(' ')); });
  const warn = spyOn(console, 'error').mockImplementation((...a: unknown[]) => { err.push(a.join(' ')); });
  const raw = spyOn(process.stderr, 'write').mockImplementation(((chunk: unknown) => { err.push(String(chunk)); return true; }) as never);
  try {
    await runSources(engine, ['add', args[0]!, '--path', dir, '--force', ...args.slice(1)]);
  } finally {
    log.mockRestore();
    warn.mockRestore();
    raw.mockRestore();
  }
  return { stdout: out.join('\n'), stderr: err.join('\n') };
}

async function federated(id: string): Promise<unknown> {
  const rows = await engine.executeRaw<{ f: unknown }>(`SELECT config->'federated' AS f FROM sources WHERE id = $1`, [id]);
  return rows[0]?.f ?? null;
}

beforeAll(async () => {
  engine = new PGLiteEngine();
  await engine.connect({ engine: 'pglite' } as never);
  await engine.initSchema();
  // GST-2732 B: a personal brain federates a new source by default (test/sources-add-default-search.test.ts); these cases are the shared brain.
  await engine.setConfig('brain.audience', 'shared');
}, 60_000);

afterAll(async () => {
  await engine?.disconnect();
  for (const d of dirs) rmSync(d, { recursive: true, force: true });
});

describe('sources add federation warning', () => {
  test('the default add warns on stderr and names both remedies; the stored default stays non-federated', async () => {
    const { stdout, stderr } = await add(['source-a']);
    expect(stdout).toContain('federated: false');
    expect(stderr).toContain('source "source-a" is not federated');
    expect(stderr).toContain('no source grant');
    expect(stderr).toContain('gbrain sources federate source-a');
    expect(stderr).toContain('gbrain auth rescope --token <name> --sources source-a');
    expect(stderr).toContain('source_not_in_default_search');
    expect(stderr).toContain('not in default search');
    expect(await federated('source-a')).not.toBe(true);
  });

  test('--json carries the not-in-default-search notice with the federate fix, and keeps the existing fields', async () => {
    const { stdout } = await add(['source-n', '--json']);
    const out = JSON.parse(stdout);
    expect(out).toMatchObject({ id: 'source-n', federated: false });
    expect(out.notices).toHaveLength(1);
    expect(out.notices[0]).toMatchObject({ code: 'source_not_in_default_search', kind: 'info', fix: { argv: ['gbrain', 'sources', 'federate', 'source-n'] } });
  });

  // GBRA-585: a personal source (private-<member>) on a team brain was met with "next: ask_user: gbrain sources federate".
  test('the notice asks whether the source should be shared, and says a private source needs nothing', async () => {
    const { stdout, stderr } = await add(['private-alice-example', '--json']);
    const notice = JSON.parse(stdout).notices[0];
    expect(notice.fix.next).toBe('ask_user');
    expect(notice.user_message).toContain('Should the source "private-alice-example" be shared');
    expect(notice.user_message).toContain('leave it as it is');
    expect(notice.why).toContain('A source meant to stay private needs nothing');
    expect(stderr).not.toContain('Run `gbrain sources federate private-alice-example` to add it');
  });

  test('--federated adds without the warning', async () => {
    const { stderr } = await add(['source-b', '--federated']);
    expect(stderr).not.toContain('is not federated');
    expect(await federated('source-b')).toBe(true);
  });

  test('an explicit --no-federated add is the operator\'s stated choice and does not warn', async () => {
    const { stdout, stderr } = await add(['source-c', '--no-federated']);
    expect(stdout).toContain('federated: false');
    expect(stderr).not.toContain('is not federated');
    expect(stdout).not.toContain('next:');
  });
});

describe('sources add next step when the no-grant floor holds no page', () => {
  test('a default add on a brain whose default and federated sources hold no page prints the federate command on stdout', async () => {
    const { stdout } = await add(['source-d']);
    expect(stdout).toContain('next: gbrain sources federate source-d');
  });

  test('--json carries the same step as next, with the human lines on stderr', async () => {
    const { stdout, stderr } = await add(['source-e', '--json']);
    const out = JSON.parse(stdout);
    expect(out).toMatchObject({ id: 'source-e', federated: false, next: { command: 'gbrain sources federate source-e', argv: ['gbrain', 'sources', 'federate', 'source-e'] } });
    expect(stderr).toContain('Created source "source-e"');
  });

  // Generated by gstack /ship Step 7 coverage audit (GBRA-156).
  // Value: protects=a page in a federated non-default source counts as the no-grant floor holding a page, so no next step prints;
  // fails_when=the floor query reads only the default source and tells the operator to federate when reads already work;
  // why_new=the floor tests put pages only in the default source; seam=none;
  // no_claim=remote read behavior after the add (console spies on the real command; PGLite)
  test('a page in a federated non-default source fills the floor, so the add prints no next step', async () => {
    await engine.putPage('notes/federated-page', { type: 'note', title: 'Federated', compiled_truth: 'A page in a federated source.', timeline: '' }, { sourceId: 'source-b' });
    try {
      const human = await add(['source-h']);
      expect(human.stderr).toContain('source "source-h" is not federated');
      expect(human.stdout).not.toContain('next:');
      expect(JSON.parse((await add(['source-i', '--json'])).stdout).next).toBeUndefined();
    } finally {
      await engine.executeRaw(`DELETE FROM pages WHERE source_id = 'source-b'`);
    }
  });

  // Value: protects=a failing floor read after the source is created never fails the add; the add still prints its result without a next step;
  // fails_when=noGrantFloorNext's read error propagates and the committed add exits non-zero;
  // why_new=no test fails the floor read; seam=engine.executeRaw spy that throws on the floor query only;
  // no_claim=which database errors occur in practice (forced error; PGLite)
  test('a floor read that fails never fails the add; it prints no next step', async () => {
    const real = engine.executeRaw.bind(engine);
    const raw = spyOn(engine, 'executeRaw').mockImplementation((async (sql: string, params?: unknown[]) => {
      if (sql.includes('AS holds')) throw new Error('forced floor read failure');
      return real(sql, params as never);
    }) as never);
    try {
      const json = JSON.parse((await add(['source-j', '--json'])).stdout);
      expect(json).toMatchObject({ id: 'source-j', federated: false });
      expect(json.next).toBeUndefined();
    } finally {
      raw.mockRestore();
    }
  });

  // Value: protects=a floor holding only a private page still gets the next step, since remote reads never show that page;
  // fails_when=the floor read counts pages a remote caller cannot read;
  // why_new=no test puts a private page on the floor; seam=none; no_claim=search.remote_private_pages visible
  test('a floor holding only a private page still prints the next step', async () => {
    await engine.putPage('notes/private-floor', { type: 'note', title: 'Private', compiled_truth: 'A private page in the default source.', timeline: '', frontmatter: { visibility: 'private' } } as never);
    try {
      expect((await add(['source-k'])).stdout).toContain('next: gbrain sources federate source-k');
    } finally {
      await engine.executeRaw("DELETE FROM pages WHERE source_id = 'default' AND slug = 'notes/private-floor'");
    }
  });

  test('once the floor holds a page, the add warns but prints no next step', async () => {
    await engine.putPage('notes/floor-page', { type: 'note', title: 'Floor', compiled_truth: 'A page in the default source.', timeline: '' });
    const human = await add(['source-f']);
    expect(human.stderr).toContain('source "source-f" is not federated');
    expect(human.stdout).not.toContain('next:');
    const json = JSON.parse((await add(['source-g', '--json'])).stdout);
    expect(json).toMatchObject({ id: 'source-g', federated: false });
    expect(json.next).toBeUndefined();
  });
});

describe('gbrain sync --source names a source that default search leaves out', () => {
  test('a synced source with pages and no federated setting gets the notice; a federated one, the default source and status do not', async () => {
    await add(['source-m']);
    expect(await syncOutOfSearchNotice(engine, ['--source', 'source-m'])).toBeNull();
    await engine.putPage('notes/m', { type: 'note', title: 'M', compiled_truth: 'A page in source-m.', timeline: '' }, { sourceId: 'source-m' });
    const notice = await syncOutOfSearchNotice(engine, ['--source', 'source-m', '--no-pull']);
    expect(notice).toMatchObject({ code: 'source_not_in_default_search', fix: { argv: ['gbrain', 'sources', 'federate', 'source-m'], ask_user: true } });
    expect(await syncOutOfSearchNotice(engine, ['status', '--source', 'source-m'])).toBeNull();
    expect(await syncOutOfSearchNotice(engine, ['--source', 'default'])).toBeNull();
    await engine.executeRaw(`UPDATE sources SET config = config || '{"federated": false}'::jsonb WHERE id = 'source-m'`);
    expect(await syncOutOfSearchNotice(engine, ['--source', 'source-m'])).toBeNull();
  });

  test('a source a remote MCP caller added stays out without a federate step after sync', async () => {
    await add(['source-r']);
    await engine.executeRaw(`UPDATE sources SET config = (config - 'federated') || '{"added_by_remote_caller": true}'::jsonb WHERE id = 'source-r'`);
    await engine.putPage('notes/r', { type: 'note', title: 'R', compiled_truth: 'A page in source-r.', timeline: '' }, { sourceId: 'source-r' });
    expect(await syncOutOfSearchNotice(engine, ['--source', 'source-r'])).toBeNull();
  });
});