Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript
10.7 KB
Raw Blame
/**
 * #2120 — `gbrain config get` must resolve the file/env plane, not just the
 * DB plane. Pre-fix, `get` called only `engine.getConfig(key)`, so a
 * runtime-effective key in ~/.gbrain/config.json reported not-found while
 * the runtime happily used it.
 *
 * Hermetic: GBRAIN_HOME points at a tmp dir (configDir() honors it) via
 * withEnv (check-test-isolation R1), and the engine is a getConfig-only
 * stub — the `get` path touches nothing else.
 */

import { describe, test, expect, spyOn } from 'bun:test';
import { mkdtempSync, writeFileSync, mkdirSync } from 'node:fs';
import { join } from 'node:path';
import { tmpdir } from 'node:os';
import { runConfig } from '../src/commands/config.ts';
import { operations } from '../src/core/operations.ts';
import { readPublishGate, type PublishGateKey } from '../src/mcp/publish-gates.ts';
import { loadConfig } from '../src/core/config.ts';
import { withEnv } from './helpers/with-env.ts';
import type { BrainEngine } from '../src/core/engine.ts';

const home = mkdtempSync(join(tmpdir(), 'gbrain-config-get-'));
mkdirSync(join(home, '.gbrain'), { recursive: true });

function stubEngine(dbValues: Record<string, string>): BrainEngine {
  return {
    getConfig: async (key: string) => dbValues[key] ?? null,
  } as unknown as BrainEngine;
}

function writeFileConfig(cfg: Record<string, unknown>): void {
  writeFileSync(join(home, '.gbrain', 'config.json'), JSON.stringify(cfg));
}

/** Run `config get <key>` with GBRAIN_HOME pinned to the tmp brain and the
 *  chat-model + anthropic-key env overlays cleared (loadConfig folds
 *  ANTHROPIC_API_KEY into anthropic_api_key, which the #3943 pins read),
 *  capturing output + exit code. `extraArgs` lands flags around the key. */
async function runGet(
  dbValues: Record<string, string>,
  key: string,
  extraArgs: { before?: string[]; after?: string[] } = {},
): Promise<{ logs: string[]; errs: string[]; exit: number | null }> {
  const logs: string[] = [];
  const errs: string[] = [];
  let exit: number | null = null;
  const logSpy = spyOn(console, 'log').mockImplementation((...a: unknown[]) => { logs.push(a.join(' ')); });
  const errSpy = spyOn(console, 'error').mockImplementation((...a: unknown[]) => { errs.push(a.join(' ')); });
  const exitSpy = spyOn(process, 'exit').mockImplementation(((code?: number) => {
    exit = code ?? 0;
    throw new Error(`EXIT:${code}`);
  }) as never);
  try {
    await withEnv(
      { GBRAIN_HOME: home, GBRAIN_CHAT_MODEL: undefined, ANTHROPIC_API_KEY: undefined },
      () => runConfig(stubEngine(dbValues), ['get', ...(extraArgs.before ?? []), key, ...(extraArgs.after ?? [])]),
    );
  } catch (e) {
    if (!(e as Error).message.startsWith('EXIT:')) throw e;
  } finally {
    logSpy.mockRestore();
    errSpy.mockRestore();
    exitSpy.mockRestore();
  }
  return { logs, errs, exit };
}

describe('#2120 — config get resolves file plane with DB fallback', () => {
  test('file-plane key with no DB row is found (the pre-fix not-found bug)', async () => {
    writeFileConfig({ engine: 'pglite', chat_model: 'anthropic:claude-sonnet-4-6' });
    const { logs, errs, exit } = await runGet({}, 'chat_model');
    expect(exit).toBeNull();
    expect(logs).toContain('anthropic:claude-sonnet-4-6');
    expect(errs.join('\n')).toContain('file/env plane');
  });

  test('file plane wins over DB plane (matches runtime precedence) and reports the shadow', async () => {
    writeFileConfig({ engine: 'pglite', chat_model: 'anthropic:claude-sonnet-4-6' });
    const { logs, errs } = await runGet({ chat_model: 'openai:gpt-5' }, 'chat_model');
    expect(logs).toContain('anthropic:claude-sonnet-4-6');
    expect(logs).not.toContain('openai:gpt-5');
    expect(errs.join('\n')).toContain('shadowed');
  });

  test('DB-plane-only key still resolves (no regression for dotted keys)', async () => {
    writeFileConfig({ engine: 'pglite' });
    const { logs, errs } = await runGet({ 'search.mode': 'balanced' }, 'search.mode');
    expect(logs).toContain('balanced');
    expect(errs.join('\n')).toContain('db plane');
  });

  test('key in neither plane is still not-found (exit 1)', async () => {
    writeFileConfig({ engine: 'pglite' });
    const { errs, exit } = await runGet({}, 'chat_model');
    expect(exit).toBe(1);
    expect(errs.join('\n')).toContain('Config key not found: chat_model');
  });
});

describe('#3943 — config get redacts sensitive values by default (--raw opts out)', () => {
  test('file-plane sensitive key prints *** and the secret appears nowhere', async () => {
    writeFileConfig({ engine: 'pglite', anthropic_api_key: 'sk-ant-test3943-file-secret' });
    const { logs, errs, exit } = await runGet({}, 'anthropic_api_key');
    expect(exit).toBeNull();
    expect(logs).toContain('***');
    expect(logs.join('\n')).not.toContain('sk-ant-test3943-file-secret');
    expect(errs.join('\n')).not.toContain('sk-ant-test3943-file-secret');
  });

  test('DB-plane sensitive key prints ***', async () => {
    writeFileConfig({ engine: 'pglite' });
    const { logs, exit } = await runGet({ github_token: 'ghp-test3943-db-secret' }, 'github_token');
    expect(exit).toBeNull();
    expect(logs).toContain('***');
    expect(logs.join('\n')).not.toContain('ghp-test3943-db-secret');
  });

  // Pin: redactConfigValue routes DSNs through redactPgUrl, which drops the
  // whole userinfo (both scheme spellings) — host/db stay legible for scripts.
  test('database_url prints the userinfo-redacted URL', async () => {
    writeFileConfig({ engine: 'pglite', database_url: 'postgresql://user:pw3943@host/db' });
    const { logs, exit } = await runGet({}, 'database_url');
    expect(exit).toBeNull();
    expect(logs).toContain('postgresql://***@host/db');
    expect(logs.join('\n')).not.toContain('pw3943');
  });

  test('--raw before the key still resolves the key and prints the verbatim secret', async () => {
    writeFileConfig({ engine: 'pglite', anthropic_api_key: 'sk-ant-test3943-raw-optout' });
    const { logs, exit } = await runGet({}, 'anthropic_api_key', { before: ['--raw'] });
    expect(exit).toBeNull();
    expect(logs).toContain('sk-ant-test3943-raw-optout');
  });

  test('--raw after the key prints the verbatim secret', async () => {
    writeFileConfig({ engine: 'pglite', anthropic_api_key: 'sk-ant-test3943-raw-optout' });
    const { logs, exit } = await runGet({}, 'anthropic_api_key', { after: ['--raw'] });
    expect(exit).toBeNull();
    expect(logs).toContain('sk-ant-test3943-raw-optout');
  });

  test('non-sensitive key still prints its raw value (scripting regression guard)', async () => {
    writeFileConfig({ engine: 'pglite', chat_model: 'anthropic:claude-sonnet-4-6' });
    const { logs, exit } = await runGet({}, 'chat_model');
    expect(exit).toBeNull();
    expect(logs).toContain('anthropic:claude-sonnet-4-6');
  });
});

describe('#5358 — config get resolves publish-gate keys the way the runtime gate does (DB > file)', () => {
  const gateKeys = [...new Set(operations.flatMap((op) => (op.publishGateKey ? [op.publishGateKey] : [])))];

  test('the operation contract still registers publish gates (the set config get derives from)', () => {
    expect(gateKeys).toContain('mcp.publish_skills');
    expect(gateKeys.length).toBeGreaterThan(0);
  });

  test('mcp.publish_skills prints the DB value and warns about the diverged file mirror', async () => {
    writeFileConfig({ engine: 'pglite', mcp: { publish_skills: true } });
    const { logs, errs, exit } = await runGet({ 'mcp.publish_skills': 'false' }, 'mcp.publish_skills');
    expect(exit).toBeNull();
    expect(logs).toEqual(['false']);
    expect(errs.join('\n')).toContain('db plane (authoritative for this key)');
    expect(errs.join('\n')).toContain('file mirror disagrees');
  });

  test('mcp.publish_skills falls back to the file plane when no DB row exists', async () => {
    writeFileConfig({ engine: 'pglite', mcp: { publish_skills: true } });
    const { logs, errs } = await runGet({}, 'mcp.publish_skills');
    expect(logs).toEqual(['true']);
    expect(errs.join('\n')).toContain('file mirror (no DB row)');
  });

  test.each(gateKeys)('%s: config get reports the value the runtime gate resolves when the planes differ', async (key) => {
    const leaf = key.slice('mcp.'.length);
    writeFileConfig({ engine: 'pglite', mcp: { [leaf]: true } });
    const db = { [key]: 'false' };
    const { logs } = await runGet(db, key);
    const runtime = await withEnv({ GBRAIN_HOME: home }, () =>
      readPublishGate(stubEngine(db), loadConfig(), key as PublishGateKey, 'http'));
    expect(logs).toEqual([String(runtime)]);
  });
});

describe('#7346 — config get and show redact secrets nested in an object value', () => {
  // Value: protects=object-storage credentials never reach scrollback or agent transcripts through config get/show;
  // fails_when=a nested camelCase secret (storage.secretAccessKey) prints in the clear; why_new=the #3943 pins cover
  // only flat snake_case keys; seam=runConfig with a file-plane storage object; no_claim=redaction of --raw output.
  const SECRET = 'minio-test7346-secret-value';
  const KEY_ID = 'minio-test7346-key-id';
  const storage = { backend: 's3', bucket: 'brain-files', endpoint: 'http://127.0.0.1:9000', accessKeyId: KEY_ID, secretAccessKey: SECRET };

  async function runShow(): Promise<string> {
    const logs: string[] = [];
    const logSpy = spyOn(console, 'log').mockImplementation((...a: unknown[]) => { logs.push(a.join(' ')); });
    const errSpy = spyOn(console, 'error').mockImplementation(() => {});
    try {
      await withEnv({ GBRAIN_HOME: home }, () => runConfig(stubEngine({}), ['show']));
    } finally {
      logSpy.mockRestore();
      errSpy.mockRestore();
    }
    return logs.join('\n');
  }

  test('get storage masks the nested credentials and keeps the other fields', async () => {
    writeFileConfig({ engine: 'pglite', storage });
    const { logs, errs, exit } = await runGet({}, 'storage');
    expect(exit).toBeNull();
    const out = logs.join('\n');
    expect(out).not.toContain(SECRET);
    expect(out).not.toContain(KEY_ID);
    expect(errs.join('\n')).not.toContain(SECRET);
    expect(JSON.parse(out)).toEqual({ ...storage, accessKeyId: '***', secretAccessKey: '***' });
  });

  test('get storage.secretAccessKey prints ***; --raw still prints the value', async () => {
    writeFileConfig({ engine: 'pglite', storage });
    expect((await runGet({}, 'storage.secretAccessKey')).logs).toEqual(['***']);
    expect((await runGet({}, 'storage.secretAccessKey', { after: ['--raw'] })).logs).toEqual([SECRET]);
  });

  test('show masks the nested credentials', async () => {
    writeFileConfig({ engine: 'pglite', storage });
    const out = await runShow();
    expect(out).toContain('brain-files');
    expect(out).not.toContain(SECRET);
    expect(out).not.toContain(KEY_ID);
  });
});