Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript
15.7 KB
Raw Blame
/**
 * GBRA-438 PR 2, done item 4: gbrain maintain --schedule / --unschedule, the
 * opt-in operating-system schedule for free upkeep (decision E1).
 *
 * 1. Protects: the generated wrapper, launchd plist, systemd service and timer
 *    and cron line (pinned, pure); a refusal without --yes writes nothing and
 *    exits through the consent contract; --dry-run writes nothing; the cron
 *    install keeps one line per brain and --unschedule removes it; Windows and
 *    containers install nothing and print their outcome; a scheduled run
 *    exits 0 while a live serve owns the brain.
 * 2. Fails when: a generated file drifts, an install happens without consent,
 *    a second install duplicates the cron line, or a scheduled run opens a
 *    brain a serve owns.
 * 3. Seams: ScheduleEnv (platform, execution environment, dirs, a fake
 *    CommandRunner, interactive=false) and tryRunMaintainEngineFree's liveServe.
 */
import { afterAll, afterEach, beforeEach, describe, expect, spyOn, test } from 'bun:test';
import { existsSync, mkdtempSync, readFileSync, rmSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import {
  isScheduleCronLine, renderScheduleLaunchdPlist, renderScheduleSystemdService, renderScheduleSystemdTimer, renderScheduleWrapper,
  runMaintainSchedule, scheduleCronLine, scheduleNames, tryRunMaintainEngineFree, windowsScheduleCommand, type ScheduleEnv,
} from '../src/commands/maintain-schedule.ts';
import { _resetCliExitVerdictForTests, currentExitCode } from '../src/core/cli-force-exit.ts';
import { exitCodeForCode } from '../src/core/error-catalogue.ts';
import type { CommandRunner } from '../src/core/tailscale.ts';

describe('generated files (pure)', () => {
  test('job names: bare for the default brain, suffixed for another GBRAIN_HOME', () => {
    expect(scheduleNames(null)).toEqual({ label: 'com.gbrain.maintain', unit: 'gbrain-maintain', cronMarker: '# gbrain-maintain' });
    expect(scheduleNames('abcd1234')).toEqual({ label: 'com.gbrain.maintain.abcd1234', unit: 'gbrain-maintain-abcd1234', cronMarker: '# gbrain-maintain:abcd1234' });
  });

  test('wrapper: env file, PATH, baked GBRAIN_HOME, PATH fallback, one unattended run as runner schedule', () => {
    expect(renderScheduleWrapper({ gbrainCommand: ['/opt/bun/bin/bun', '/opt/gbrain/src/cli.ts'], gbrainEnvFile: '/home/u/.gbrain/env', gbrainHome: '/home/u/alt', runtimeDir: '/opt/bun/bin' })).toBe(
      "#!/bin/bash\n"
      + "# Auto-generated by `gbrain maintain --schedule`: runs free upkeep once and exits.\n"
      + "# Remove with `gbrain maintain --unschedule`. Keys come from the gbrain env file only.\n"
      + "[ -f '/home/u/.gbrain/env' ] && { set -a; source '/home/u/.gbrain/env' 2>/dev/null; set +a; }\n"
      + "export PATH='/opt/bun/bin':\"$HOME/.bun/bin:$PATH\"\n"
      + "export GBRAIN_HOME='/home/u/alt'\n"
      + "cd \"$HOME\"\n"
      + "_gbrain='/opt/bun/bin/bun'\n"
      + "if [ ! -x \"$_gbrain\" ]; then\n"
      + "  _gbrain=$(type -P gbrain 2>/dev/null)\n"
      + "  if [ -z \"$_gbrain\" ]; then\n"
      + "    echo \"$(date -u +%FT%TZ) [gbrain-maintain] gbrain CLI not found at\" '/opt/bun/bin/bun' \"nor on PATH; re-run: gbrain maintain --schedule\" >&2\n"
      + "    exit 1\n"
      + "  fi\n"
      + "fi\n"
      + "exec \"$_gbrain\" '/opt/gbrain/src/cli.ts' maintain --unattended --runner schedule\n",
    );
    expect(renderScheduleWrapper({ gbrainCommand: ['/usr/local/bin/gbrain'], gbrainEnvFile: '/h/.gbrain/env' })).toContain("export PATH=\"$HOME/.bun/bin:$PATH\"\ncd \"$HOME\"\n");
  });

  test('launchd: a user agent every 6 hours, at load, no KeepAlive', () => {
    expect(renderScheduleLaunchdPlist({ label: 'com.gbrain.maintain', wrapperPath: '/Users/u/.gbrain/maintain-run.sh', home: '/Users/u', logPath: '/Users/u/.gbrain/maintain.log' })).toBe(
      '<?xml version="1.0" encoding="UTF-8"?>\n'
      + '<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">\n'
      + '<plist version="1.0">\n'
      + '<dict>\n'
      + '  <key>Label</key><string>com.gbrain.maintain</string>\n'
      + '  <key>ProgramArguments</key><array>\n'
      + '    <string>/Users/u/.gbrain/maintain-run.sh</string>\n'
      + '  </array>\n'
      + '  <key>WorkingDirectory</key><string>/Users/u</string>\n'
      + '  <key>RunAtLoad</key><true/>\n'
      + '  <key>StartInterval</key><integer>21600</integer>\n'
      + '  <key>StandardOutPath</key><string>/Users/u/.gbrain/maintain.log</string>\n'
      + '  <key>StandardErrorPath</key><string>/Users/u/.gbrain/maintain.log</string>\n'
      + '</dict>\n'
      + '</plist>\n',
    );
  });

  test('systemd: a oneshot service and a persistent 6-hour timer', () => {
    expect(renderScheduleSystemdService({ wrapperPath: '/home/u/.gbrain/maintain-run.sh', logPath: '/home/u/.gbrain/maintain.log' })).toBe(
      '[Unit]\nDescription=GBrain free upkeep (gbrain maintain --unattended --runner schedule)\n\n'
      + '[Service]\nType=oneshot\nExecStart=/home/u/.gbrain/maintain-run.sh\n'
      + 'StandardOutput=append:/home/u/.gbrain/maintain.log\nStandardError=append:/home/u/.gbrain/maintain.log\n',
    );
    expect(renderScheduleSystemdTimer({ unit: 'gbrain-maintain' })).toBe(
      '[Unit]\nDescription=GBrain free upkeep every 6 hours\n\n'
      + '[Timer]\nOnCalendar=*-*-* 00/6:17:00\nPersistent=true\nRandomizedDelaySec=600\nUnit=gbrain-maintain.service\n\n'
      + '[Install]\nWantedBy=timers.target\n',
    );
    expect(renderScheduleSystemdService({ wrapperPath: '/home/u 1/%x.sh', logPath: '/l/%h.log' })).toContain('ExecStart="/home/u 1/%%x.sh"\nStandardOutput=append:/l/%%h.log');
  });

  test('cron: one tagged line every 6 hours; the marker matches only its own brain', () => {
    const line = scheduleCronLine({ wrapperPath: '/home/u/.gbrain/maintain-run.sh', logPath: '/home/u/.gbrain/maintain.log', marker: '# gbrain-maintain' });
    expect(line).toBe("17 */6 * * * '/home/u/.gbrain/maintain-run.sh' >> '/home/u/.gbrain/maintain.log' 2>&1 # gbrain-maintain");
    expect(isScheduleCronLine(line, '# gbrain-maintain')).toBe(true);
    expect(isScheduleCronLine(line.replace('# gbrain-maintain', '# gbrain-maintain:abcd1234'), '# gbrain-maintain')).toBe(false);
    expect(isScheduleCronLine('*/5 * * * * /x/autopilot-run.sh # gbrain-autopilot:abcd1234', '# gbrain-maintain')).toBe(false);
  });

  test('Windows: the schtasks line to add by hand', () => {
    expect(windowsScheduleCommand(['C:\\gbrain\\gbrain.exe'])).toBe('schtasks /Create /SC HOURLY /MO 6 /TN gbrain-maintain /TR "C:\\gbrain\\gbrain.exe maintain --unattended --runner schedule"');
  });
});

describe('gbrain maintain --schedule', () => {
  let root: string;
  let out: string[];
  let crontab: string;
  let calls: string[][];
  let logSpy: ReturnType<typeof spyOn>;
  let errSpy: ReturnType<typeof spyOn>;
  let stderrSpy: ReturnType<typeof spyOn>;
  let errOut: string[] = [];

  const run: CommandRunner = async (argv) => {
    calls.push(argv);
    if (argv[0] === 'crontab' && argv[1] === '-l') return { status: 0, stdout: crontab, stderr: '' };
    if (argv[0] === 'crontab') { crontab = readFileSync(argv[1]!, 'utf8'); return { status: 0, stdout: '', stderr: '' }; }
    return { status: 0, stdout: '', stderr: '' };
  };
  const env = (platform: string, executionEnv: ScheduleEnv['executionEnv'] = 'local'): ScheduleEnv => ({
    platform, executionEnv, home: join(root, 'home'), dir: join(root, 'home', '.gbrain'), names: scheduleNames(null),
    gbrainCommand: ['/usr/local/bin/gbrain'], runtimeDir: '', run, systemdBooted: false, interactive: false,
  });
  const json = () => JSON.parse(out.join('\n'));

  beforeEach(() => {
    root = mkdtempSync(join(tmpdir(), 'gbrain-schedule-'));
    out = []; calls = []; crontab = 'MAILTO=""\n0 1 * * * /usr/bin/true\n';
    _resetCliExitVerdictForTests();
    logSpy = spyOn(console, 'log').mockImplementation((...a: unknown[]) => { out.push(a.map(String).join(' ')); });
    errSpy = spyOn(process.stdout, 'write').mockImplementation(((chunk: string | Uint8Array) => { out.push(String(chunk)); return true; }) as never);
    stderrSpy = spyOn(process.stderr, 'write').mockImplementation(((chunk: string | Uint8Array) => { errOut.push(String(chunk)); return true; }) as never);
    errOut = [];
  });
  afterEach(() => {
    logSpy.mockRestore();
    errSpy.mockRestore();
    stderrSpy.mockRestore();
    rmSync(root, { recursive: true, force: true });
  });
  afterAll(() => { _resetCliExitVerdictForTests(); process.exitCode = 0; });

  test('without --yes it refuses through the consent contract and writes nothing', async () => {
    await runMaintainSchedule(['--schedule', '--json'], env('linux'));
    expect(currentExitCode()).toBe(exitCodeForCode('confirmation_required'));
    const doc = json();
    expect(JSON.stringify(doc)).toContain('persistent_install');
    expect(JSON.stringify(doc)).toContain('gbrain maintain --schedule --yes');
    expect(existsSync(join(root, 'home', '.gbrain', 'maintain-run.sh'))).toBe(false);
    expect(calls.filter((c) => c[0] === 'crontab' && c[1] !== '-l')).toEqual([]);
  });

  test('--dry-run lists what it would write and writes nothing', async () => {
    await runMaintainSchedule(['--schedule', '--dry-run', '--json'], env('linux'));
    expect(currentExitCode()).toBe(0);
    expect(json()).toMatchObject({ status: 'dry_run', target: 'linux-cron', interval_hours: 6 });
    expect(existsSync(join(root, 'home', '.gbrain', 'maintain-run.sh'))).toBe(false);
  });

  test('--yes on cron installs the wrapper and one line; a reinstall keeps one; --unschedule removes it and keeps the rest', async () => {
    await runMaintainSchedule(['--schedule', '--yes', '--json'], env('linux'));
    expect(currentExitCode()).toBe(0);
    expect(json()).toMatchObject({ status: 'installed', target: 'linux-cron' });
    const wrapper = join(root, 'home', '.gbrain', 'maintain-run.sh');
    expect(readFileSync(wrapper, 'utf8')).toContain('maintain --unattended --runner schedule');
    expect(crontab.split('\n').filter((l) => l.endsWith('# gbrain-maintain'))).toHaveLength(1);
    out.length = 0;
    await runMaintainSchedule(['--schedule', '--yes', '--json'], env('linux'));
    expect(crontab.split('\n').filter((l) => l.endsWith('# gbrain-maintain'))).toHaveLength(1);
    expect(crontab).toContain('0 1 * * * /usr/bin/true');
    out.length = 0;
    await runMaintainSchedule(['--unschedule', '--json'], env('linux'));
    expect(json()).toMatchObject({ status: 'removed' });
    expect(crontab).not.toContain('gbrain-maintain');
    expect(crontab).toContain('0 1 * * * /usr/bin/true');
    expect(existsSync(wrapper)).toBe(false);
  });

  test('a crontab -l that fails for any reason but "no crontab" leaves the crontab alone: install and --unschedule write nothing', async () => {
    const failing: CommandRunner = async (argv) => {
      calls.push(argv);
      if (argv[0] === 'crontab' && argv[1] === '-l') return { status: 1, stdout: '', stderr: 'crontab: cannot open your crontab: permission denied' };
      return run(argv);
    };
    const before = crontab;
    await runMaintainSchedule(['--schedule', '--yes', '--json'], { ...env('linux'), run: failing });
    expect(currentExitCode()).toBe(exitCodeForCode('schedule_install_failed'));
    expect([...out, ...errOut].join('\n')).toContain('crontab -l failed');
    _resetCliExitVerdictForTests();
    await runMaintainSchedule(['--unschedule', '--json'], { ...env('linux'), run: failing });
    expect(currentExitCode()).toBe(1);
    expect(calls.filter((c) => c[0] === 'crontab' && c[1] !== '-l')).toEqual([]);
    expect(crontab).toBe(before);
  });

  test('"no crontab for user" reads as an empty crontab, and an install keeps the other lines exactly, blank ones included', async () => {
    const none: CommandRunner = async (argv) => {
      if (argv[0] === 'crontab' && argv[1] === '-l') { calls.push(argv); return { status: 1, stdout: '', stderr: 'no crontab for user' }; }
      return run(argv);
    };
    await runMaintainSchedule(['--schedule', '--yes', '--json'], { ...env('linux'), run: none });
    expect(currentExitCode()).toBe(0);
    expect(crontab.split('\n').filter(Boolean)).toHaveLength(1);
    expect(crontab).toEndWith('# gbrain-maintain\n');
    crontab = 'MAILTO=""\n\n0 1 * * * /usr/bin/true\n';
    out.length = 0;
    await runMaintainSchedule(['--schedule', '--yes', '--json'], env('linux'));
    expect(crontab.startsWith('MAILTO=""\n\n0 1 * * * /usr/bin/true\n')).toBe(true);
  });

  test('a mounted brain gets no schedule: --schedule refuses with schedule_unsupported (reason mount) and writes nothing', async () => {
    await runMaintainSchedule(['--schedule', '--yes', '--json'], { ...env('linux'), brainId: 'work' });
    expect(currentExitCode()).toBe(exitCodeForCode('schedule_unsupported'));
    const text = [...out, ...errOut].join('\n');
    expect(text).toContain('mount');
    expect(text).toContain('gbrain --brain work maintain --unattended');
    expect(existsSync(join(root, 'home', '.gbrain', 'maintain-run.sh'))).toBe(false);
    expect(calls.filter((c) => c[0] === 'crontab')).toEqual([]);
  });

  test('--yes on a systemd host writes the service and timer and enables the timer', async () => {
    await runMaintainSchedule(['--schedule', '--yes', '--json'], { ...env('linux'), systemdBooted: true });
    expect(json()).toMatchObject({ status: 'installed', target: 'linux-systemd' });
    const units = join(root, 'home', '.config', 'systemd', 'user');
    expect(readFileSync(join(units, 'gbrain-maintain.timer'), 'utf8')).toContain('OnCalendar=*-*-* 00/6:17:00');
    expect(readFileSync(join(units, 'gbrain-maintain.service'), 'utf8')).toContain('Type=oneshot');
    expect(calls).toContainEqual(['systemctl', '--user', 'enable', '--now', 'gbrain-maintain.timer']);
    expect(json().notes.join(' ')).toContain('loginctl enable-linger');
  });

  test('--yes on macOS writes the plist and bootstraps it in the user domain', async () => {
    await runMaintainSchedule(['--schedule', '--yes', '--json'], { ...env('darwin'), uid: 501 });
    const plist = join(root, 'home', 'Library', 'LaunchAgents', 'com.gbrain.maintain.plist');
    expect(readFileSync(plist, 'utf8')).toContain('<key>StartInterval</key><integer>21600</integer>');
    expect(calls).toContainEqual(['launchctl', 'bootstrap', 'gui/501', plist]);
  });

  test('Windows installs nothing and prints the schtasks line', async () => {
    await runMaintainSchedule(['--schedule', '--yes', '--json'], env('win32'));
    expect(currentExitCode()).toBe(exitCodeForCode('schedule_unsupported'));
    const text = [...out, ...errOut].join('\n');
    expect(text).toContain('schedule_unsupported');
    expect(text).toContain('schtasks /Create /SC HOURLY /MO 6 /TN gbrain-maintain');
    expect(calls).toEqual([]);
  });

  test('a container installs nothing and names the resident serve as its runner', async () => {
    await runMaintainSchedule(['--schedule', '--yes', '--json'], env('linux', 'ephemeral-container' as ScheduleEnv['executionEnv']));
    const text = [...out, ...errOut].join('\n');
    expect(text).toContain('schedule_unsupported');
    expect(text).toContain('gbrain serve');
    expect(existsSync(join(root, 'home', '.gbrain', 'maintain-run.sh'))).toBe(false);
  });

  test('a scheduled run exits 0 "serve owns upkeep" while a live serve owns the brain, without opening it', async () => {
    expect(await tryRunMaintainEngineFree(['--unattended', '--runner', 'schedule', '--json'], { liveServe: async () => true })).toBe(true);
    expect(currentExitCode()).toBe(0);
    expect(json()).toMatchObject({ status: 'skipped', exit: 0, code: 'maintenance_owned_by_serve' });
    expect(json().message).toContain('serve owns upkeep');
    expect(await tryRunMaintainEngineFree(['--unattended', '--runner', 'schedule'], { liveServe: async () => false })).toBe(false);
    expect(await tryRunMaintainEngineFree(['--unattended'], { liveServe: async () => true })).toBe(false);
  });
});