Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
/**
* `gbrain maintain --schedule [--yes] [--dry-run]` and `--unschedule` (GBRA-438 PR 2, decision E1):
* the opt-in operating-system schedule for free upkeep, never installed by default. Every
* 6 hours the job runs `gbrain maintain --unattended --runner schedule` once and exits:
*
* - macOS: a launchd user agent (no sudo; runs while the user is logged in);
* - Linux with a working systemd user manager: a .service plus .timer pair (runs after
* logout only with lingering, which may need an admin);
* - other Linux: one user crontab line, tagged with this brain's marker;
* - a container or cloud sandbox: nothing is installed; the resident `gbrain serve`
* (stdio or --http) is the runner there;
* - Windows: nothing is installed; the outcome prints the schtasks line to add by hand.
*
* Installing is a persistent_install, so it goes through requireConsent (`--yes`, a TTY
* prompt or the user's preapproval); a refusal prints the consent payload and writes nothing.
* A scheduled run exits 0 at once when a live serve owns the brain ("serve owns upkeep"):
* the PGLite lock holder on a PGLite brain, the warm CLI socket (GBRA-156) on Postgres.
*
* Renderers are pure and pinned by test/maintain-schedule-gbra438.test.ts; every exec goes
* through an injectable CommandRunner and every path through injectable dirs, as in
* src/core/serve-service.ts, whose wrapper and escaping helpers this reuses.
*/
import { chmodSync, existsSync, mkdirSync, unlinkSync, writeFileSync } from 'node:fs';
import { dirname, join } from 'node:path';
import { gbrainPath, isThinClient, loadConfig } from '../core/config.ts';
import { resolveAutopilotJob } from '../core/autopilot-paths.ts';
import { detectExecutionEnvironment, type ExecutionEnvironment } from '../core/execution-env.ts';
import { escapeXml, refuseSymlink, resolveServeGbrainCommand, systemdArg, systemdSpecifierEscape } from '../core/serve-service.ts';
import { defaultCommandRunner, type CommandRunner } from '../core/tailscale.ts';
import { isConsentRefusal, printConsentRefusal, requireConsent } from '../core/consent.ts';
import { setCliExitVerdict } from '../core/cli-force-exit.ts';
import { writeCliError } from '../cli/cli-error.ts';
import { opError } from '../core/ops/contract.ts';
import { resolveBrainId } from '../core/brain-resolver.ts';
import { HOST_BRAIN_ID } from '../core/brain-registry.ts';
import { getCliOptions } from '../core/cli-options.ts';
export const SCHEDULE_INTERVAL_HOURS = 6;
/** What the job runs: one unattended upkeep run, recorded with runner `schedule`. */
export const SCHEDULED_RUN_ARGS: readonly string[] = ['maintain', '--unattended', '--runner', 'schedule'];
export type ScheduleTarget = 'macos' | 'linux-systemd' | 'linux-cron' | 'container' | 'windows';
export interface ScheduleNames { label: string; unit: string; cronMarker: string }
/** One brain's job names: the default brain keeps the bare names; another GBRAIN_HOME carries its install-id suffix (#5195). */
export function scheduleNames(suffix: string | null): ScheduleNames {
return {
label: suffix ? `com.gbrain.maintain.${suffix}` : 'com.gbrain.maintain',
unit: suffix ? `gbrain-maintain-${suffix}` : 'gbrain-maintain',
cronMarker: suffix ? `# gbrain-maintain:${suffix}` : '# gbrain-maintain',
};
}
const sq = (s: string) => `'${s.replace(/'/g, "'\\''")}'`;
export interface ScheduleWrapperParams {
/** From resolveServeGbrainCommand: `[gbrain]` or `[bun, cli.ts]`. */
gbrainCommand: string[];
/** `<gbrain home>/env`, sourced for keys (set -a). */
gbrainEnvFile: string;
/** The installer's GBRAIN_HOME, baked when set (supervisors pass no environment). */
gbrainHome?: string;
/** Directory of the running bun; '' skips the PATH prefix. */
runtimeDir?: string;
}
export function renderScheduleWrapper(p: ScheduleWrapperParams): string {
const [program, ...programArgs] = p.gbrainCommand;
const tail = [...programArgs.map(sq), ...SCHEDULED_RUN_ARGS].join(' ');
const runtimeDir = p.runtimeDir ?? '';
const runtimePrefix = runtimeDir && runtimeDir !== '.' ? `${sq(runtimeDir)}:` : '';
const homeLine = p.gbrainHome ? `export GBRAIN_HOME=${sq(p.gbrainHome)}\n` : '';
return `#!/bin/bash
# Auto-generated by \`gbrain maintain --schedule\`: runs free upkeep once and exits.
# Remove with \`gbrain maintain --unschedule\`. Keys come from the gbrain env file only.
[ -f ${sq(p.gbrainEnvFile)} ] && { set -a; source ${sq(p.gbrainEnvFile)} 2>/dev/null; set +a; }
export PATH=${runtimePrefix}"$HOME/.bun/bin:$PATH"
${homeLine}cd "$HOME"
_gbrain=${sq(program!)}
if [ ! -x "$_gbrain" ]; then
_gbrain=$(type -P gbrain 2>/dev/null)
if [ -z "$_gbrain" ]; then
echo "$(date -u +%FT%TZ) [gbrain-maintain] gbrain CLI not found at" ${sq(program!)} "nor on PATH; re-run: gbrain maintain --schedule" >&2
exit 1
fi
fi
exec "$_gbrain" ${tail}
`;
}
export function renderScheduleLaunchdPlist(p: { label: string; wrapperPath: string; home: string; logPath: string }): string {
return `<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>Label</key><string>${escapeXml(p.label)}</string>
<key>ProgramArguments</key><array>
<string>${escapeXml(p.wrapperPath)}</string>
</array>
<key>WorkingDirectory</key><string>${escapeXml(p.home)}</string>
<key>RunAtLoad</key><true/>
<key>StartInterval</key><integer>${SCHEDULE_INTERVAL_HOURS * 3600}</integer>
<key>StandardOutPath</key><string>${escapeXml(p.logPath)}</string>
<key>StandardErrorPath</key><string>${escapeXml(p.logPath)}</string>
</dict>
</plist>
`;
}
export function renderScheduleSystemdService(p: { wrapperPath: string; logPath: string }): string {
return `[Unit]
Description=GBrain free upkeep (gbrain maintain --unattended --runner schedule)
[Service]
Type=oneshot
ExecStart=${systemdArg(p.wrapperPath)}
StandardOutput=append:${systemdSpecifierEscape(p.logPath)}
StandardError=append:${systemdSpecifierEscape(p.logPath)}
`;
}
export function renderScheduleSystemdTimer(p: { unit: string }): string {
return `[Unit]
Description=GBrain free upkeep every ${SCHEDULE_INTERVAL_HOURS} hours
[Timer]
OnCalendar=*-*-* 00/${SCHEDULE_INTERVAL_HOURS}:17:00
Persistent=true
RandomizedDelaySec=600
Unit=${p.unit}.service
[Install]
WantedBy=timers.target
`;
}
export function scheduleCronLine(p: { wrapperPath: string; logPath: string; marker: string }): string {
return `17 */${SCHEDULE_INTERVAL_HOURS} * * * ${sq(p.wrapperPath)} >> ${sq(p.logPath)} 2>&1 ${p.marker}`;
}
/** Windows gets no installer (org rule: minimal Windows support); this is the line the outcome prints. */
export function windowsScheduleCommand(gbrainCommand: string[]): string {
const run = [...gbrainCommand, ...SCHEDULED_RUN_ARGS].map((a) => (/\s/.test(a) ? `\\"${a}\\"` : a)).join(' ');
return `schtasks /Create /SC HOURLY /MO ${SCHEDULE_INTERVAL_HOURS} /TN gbrain-maintain /TR "${run}"`;
}
/** Whether a cron line is this brain's schedule line: it ends with exactly this marker. */
export function isScheduleCronLine(line: string, marker: string): boolean {
return line.trimEnd().endsWith(marker);
}
export interface ScheduleEnv {
platform: string;
executionEnv: ExecutionEnvironment;
/** `<HOME>`: where LaunchAgents and the systemd user dir live. */
home: string;
/** The brain's gbrain home (GBRAIN_HOME aware): wrapper, log. */
dir: string;
names: ScheduleNames;
gbrainCommand: string[];
gbrainHome?: string;
runtimeDir?: string;
/** The brain this command selects (--brain, GBRAIN_BRAIN_ID, a mount); the schedule covers the host brain only. */
brainId?: string;
run: CommandRunner;
/** `/run/systemd/system` exists (the host booted with systemd); the user manager is probed through `run`. */
systemdBooted: boolean;
uid?: number;
/** Test seam for requireConsent's TTY check. */
interactive?: boolean;
}
export function defaultScheduleEnv(): ScheduleEnv {
const runtimeDir = dirname(process.execPath || '');
return {
platform: process.platform,
executionEnv: detectExecutionEnvironment(),
home: process.env.HOME || '',
dir: gbrainPath(),
names: scheduleNames(resolveAutopilotJob({ mint: true }).suffix),
gbrainCommand: resolveServeGbrainCommand(),
...(process.env.GBRAIN_HOME ? { gbrainHome: process.env.GBRAIN_HOME } : {}),
runtimeDir: runtimeDir === '.' ? '' : runtimeDir,
brainId: resolveBrainId(getCliOptions().brain),
run: defaultCommandRunner,
systemdBooted: existsSync('/run/systemd/system'),
};
}
export async function detectScheduleTarget(env: ScheduleEnv): Promise<ScheduleTarget> {
if (env.platform === 'win32') return 'windows';
if (env.platform === 'darwin') return 'macos';
if (env.executionEnv !== 'local') return 'container';
if (!env.systemdBooted) return 'linux-cron';
const bus = await env.run(['systemctl', '--user', 'is-system-running'], { timeoutMs: 3_000 });
return bus.status === 0 || /\b(running|degraded)\b/i.test(bus.stdout) ? 'linux-systemd' : 'linux-cron';
}
export interface SchedulePaths { wrapper: string; log: string; plist: string; service: string; timer: string }
export function schedulePaths(env: Pick<ScheduleEnv, 'home' | 'dir' | 'names'>): SchedulePaths {
const userUnits = join(env.home, '.config', 'systemd', 'user');
return {
wrapper: join(env.dir, 'maintain-run.sh'),
log: join(env.dir, 'maintain.log'),
plist: join(env.home, 'Library', 'LaunchAgents', `${env.names.label}.plist`),
service: join(userUnits, `${env.names.unit}.service`),
timer: join(userUnits, `${env.names.unit}.timer`),
};
}
/** Every file or table entry an install on `target` writes. */
export function scheduleWrites(target: ScheduleTarget, paths: SchedulePaths): string[] {
if (target === 'macos') return [paths.wrapper, paths.plist];
if (target === 'linux-systemd') return [paths.wrapper, paths.service, paths.timer];
if (target === 'linux-cron') return [paths.wrapper, 'your crontab (one gbrain-maintain line)'];
return [];
}
function writeFile(path: string, content: string, mode: number, what: string): void {
refuseSymlink(path, what);
mkdirSync(dirname(path), { recursive: true });
writeFileSync(path, content, { mode });
chmodSync(path, mode);
}
const describe = (r: { status: number | null; stdout: string; stderr: string }) => (r.stderr || r.stdout).trim() || `exit ${r.status}`;
async function readCrontab(run: CommandRunner): Promise<{ lines: string[] } | { error: string }> {
const r = await run(['crontab', '-l'], { timeoutMs: 15_000 });
if (r.status === 0) return { lines: r.stdout ? r.stdout.replace(/\n$/, '').split('\n') : [] };
if (r.status === 1 && /no crontab|no such file/i.test(`${r.stderr}${r.stdout}`)) return { lines: [] };
return { error: `crontab -l failed (${describe(r)}), so the crontab was left unchanged` };
}
async function writeCrontab(env: ScheduleEnv, lines: string[]): Promise<{ status: number | null; stdout: string; stderr: string }> {
const tmp = join(env.dir, 'crontab.tmp');
writeFile(tmp, lines.length ? lines.join('\n') + '\n' : '', 0o600, 'the crontab staging file');
try { return await env.run(['crontab', tmp], { timeoutMs: 15_000 }); } finally { try { unlinkSync(tmp); } catch { /* best-effort */ } }
}
export interface ScheduleResult { written: string[]; notes: string[]; error?: string }
export async function installSchedule(target: 'macos' | 'linux-systemd' | 'linux-cron', env: ScheduleEnv): Promise<ScheduleResult> {
const paths = schedulePaths(env);
const out: ScheduleResult = { written: [], notes: [] };
writeFile(paths.wrapper, renderScheduleWrapper({ gbrainCommand: env.gbrainCommand, gbrainEnvFile: join(env.dir, 'env'), gbrainHome: env.gbrainHome, runtimeDir: env.runtimeDir }), 0o755, 'the upkeep wrapper');
out.written.push(paths.wrapper);
if (target === 'macos') {
writeFile(paths.plist, renderScheduleLaunchdPlist({ label: env.names.label, wrapperPath: paths.wrapper, home: env.home, logPath: paths.log }), 0o644, 'the launchd plist');
out.written.push(paths.plist);
const domain = `gui/${env.uid ?? (typeof process.getuid === 'function' ? process.getuid() : 501)}`;
await env.run(['launchctl', 'bootout', domain, paths.plist], { timeoutMs: 60_000 });
const boot = await env.run(['launchctl', 'bootstrap', domain, paths.plist], { timeoutMs: 60_000 });
if (boot.status !== 0) out.error = `launchctl bootstrap failed: ${describe(boot)}`;
return out;
}
if (target === 'linux-systemd') {
writeFile(paths.service, renderScheduleSystemdService({ wrapperPath: paths.wrapper, logPath: paths.log }), 0o644, 'the systemd service');
writeFile(paths.timer, renderScheduleSystemdTimer({ unit: env.names.unit }), 0o644, 'the systemd timer');
out.written.push(paths.service, paths.timer);
await env.run(['systemctl', '--user', 'daemon-reload'], { timeoutMs: 15_000 });
const enable = await env.run(['systemctl', '--user', 'enable', '--now', `${env.names.unit}.timer`], { timeoutMs: 60_000 });
if (enable.status !== 0) out.error = `systemctl --user enable --now ${env.names.unit}.timer failed: ${describe(enable)}`;
out.notes.push('The timer runs while your user manager runs; for runs after logout turn on lingering (loginctl enable-linger "$USER", which may need an admin).');
return out;
}
const current = await readCrontab(env.run);
if ('error' in current) {
out.error = current.error;
return out;
}
const kept = current.lines.filter((l) => !isScheduleCronLine(l, env.names.cronMarker));
const write = await writeCrontab(env, [...kept, scheduleCronLine({ wrapperPath: paths.wrapper, logPath: paths.log, marker: env.names.cronMarker })]);
if (write.status !== 0) out.error = `crontab failed: ${describe(write)}`;
else out.written.push('crontab: one gbrain-maintain line');
return out;
}
export async function uninstallSchedule(target: ScheduleTarget, env: ScheduleEnv): Promise<ScheduleResult> {
const paths = schedulePaths(env);
const out: ScheduleResult = { written: [], notes: [] };
const remove = (path: string) => { if (existsSync(path)) { unlinkSync(path); out.written.push(path); } };
if (target === 'macos') {
const domain = `gui/${env.uid ?? (typeof process.getuid === 'function' ? process.getuid() : 501)}`;
if (existsSync(paths.plist)) await env.run(['launchctl', 'bootout', domain, paths.plist], { timeoutMs: 60_000 });
remove(paths.plist);
} else if (target === 'linux-systemd') {
if (existsSync(paths.timer)) await env.run(['systemctl', '--user', 'disable', '--now', `${env.names.unit}.timer`], { timeoutMs: 60_000 });
remove(paths.timer);
remove(paths.service);
await env.run(['systemctl', '--user', 'daemon-reload'], { timeoutMs: 15_000 });
} else if (target === 'linux-cron') {
const current = await readCrontab(env.run);
const lines = 'error' in current ? [] : current.lines;
if ('error' in current) out.error = current.error;
const kept = lines.filter((l) => !isScheduleCronLine(l, env.names.cronMarker));
if (kept.length !== lines.length) {
const write = await writeCrontab(env, kept);
if (write.status !== 0) out.error = `crontab failed: ${describe(write)}`;
else out.written.push('crontab: the gbrain-maintain line');
}
}
remove(paths.wrapper);
return out;
}
/** "serve owns upkeep": a live serve holds this brain (PGLite lock holder, or the warm CLI socket on Postgres). */
export async function liveServeOwnsBrain(): Promise<boolean> {
const config = loadConfig();
if (!config || isThinClient(config)) return false;
if (config.database_path && !config.database_url) {
const { probeLivePgliteHolder } = await import('../core/bootstrap/uninstall.ts');
return !!probeLivePgliteHolder(config.database_path)?.serve;
}
const { probeCliSocket } = await import('../core/cli-socket/probe.ts');
return (await probeCliSocket()).state === 'accepted';
}
function print(json: boolean, doc: Record<string, unknown>, lines: string[]): void {
if (json) console.log(JSON.stringify(doc, null, 2));
else for (const line of lines) console.log(line);
}
/** `--schedule` / `--unschedule`. Engine-free: it never opens the brain. */
export async function runMaintainSchedule(args: string[], env: ScheduleEnv = defaultScheduleEnv()): Promise<void> {
const json = args.includes('--json');
const target = await detectScheduleTarget(env);
const paths = schedulePaths(env);
if (target === 'windows') {
const line = windowsScheduleCommand(env.gbrainCommand);
setCliExitVerdict(writeCliError(opError('schedule_unsupported', `gbrain maintain --schedule installs nothing on Windows. To schedule free upkeep by hand, run: ${line}`,
`Add the scheduled task yourself with: ${line}`, { reason: 'windows', detail: line }), 'maintain', { json }));
return;
}
if (target === 'container') {
setCliExitVerdict(writeCliError(opError('schedule_unsupported', 'This looks like a container or cloud sandbox, where an operating-system schedule does not survive a redeploy, so nothing was installed.',
'Keep gbrain serve running in the container (gbrain serve --http for a hosted brain): it runs free upkeep on its own while idle.', { reason: 'container' }), 'maintain', { json }));
return;
}
if (env.brainId && env.brainId !== HOST_BRAIN_ID && !args.includes('--unschedule')) {
setCliExitVerdict(writeCliError(opError('schedule_unsupported', `gbrain maintain --schedule covers the host brain only, and this command selects the mounted brain ${env.brainId}, so nothing was installed.`,
`Run gbrain maintain --schedule without --brain for the host brain. For ${env.brainId}, add gbrain --brain ${env.brainId} maintain --unattended to a scheduler yourself.`, { reason: 'mount', detail: env.brainId }), 'maintain', { json }));
return;
}
if (args.includes('--unschedule')) {
const result = await uninstallSchedule(target, env);
if (result.error) setCliExitVerdict(1);
print(json, { status: result.error ? 'error' : 'removed', target, removed: result.written, ...(result.error ? { error: result.error } : {}) },
[result.written.length ? `Removed the free upkeep schedule (${target}): ${result.written.join(', ')}.` : 'No free upkeep schedule was installed.', ...(result.error ? [result.error] : [])]);
return;
}
const writes = scheduleWrites(target, paths);
const what = `every ${SCHEDULE_INTERVAL_HOURS} hours, ${target === 'macos' ? 'a launchd agent' : target === 'linux-systemd' ? 'a systemd user timer' : 'a crontab line'} runs gbrain ${SCHEDULED_RUN_ARGS.join(' ')}`;
if (args.includes('--dry-run')) {
print(json, { status: 'dry_run', target, would_write: writes, interval_hours: SCHEDULE_INTERVAL_HOURS },
[`gbrain maintain --schedule --dry-run: nothing was written. On ${target}, ${what}.`, ' would write:', ...writes.map((w) => ` ${w}`), ' Install: gbrain maintain --schedule --yes (after the user agrees).']);
return;
}
try {
await requireConsent({
command: 'maintain',
effects: ['persistent_install'],
actor: 'agent',
what: 'Install an operating-system schedule for free gbrain upkeep',
why: `On ${target}, ${what}. Writes: ${writes.join(', ')}. A run calls no chat model and never purges a page; it exits at once while a gbrain serve owns the brain or upkeep is not due.`,
risk: 'A scheduled job keeps running after this session until gbrain maintain --unschedule removes it.',
user_message: `I'd like to add a small scheduled job that runs gbrain's free upkeep (links, timeline, facts index) every ${SCHEDULE_INTERVAL_HOURS} hours, so your brain stays tidy when no agent session is open. It deletes nothing and calls no chat model; with an embedding key it may embed new text, capped at $1 a day. You can remove it any time with gbrain maintain --unschedule. OK?`,
argv: ['gbrain', 'maintain', '--schedule', '--yes'],
preview_argv: ['gbrain', 'maintain', '--schedule', '--dry-run'],
args,
}, env.interactive === undefined ? {} : { interactive: env.interactive });
} catch (error) {
if (!isConsentRefusal(error)) throw error;
setCliExitVerdict(printConsentRefusal(error, { json }));
return;
}
const result = await installSchedule(target, env);
if (result.error) {
setCliExitVerdict(writeCliError(opError('schedule_install_failed', `The free upkeep schedule was written but the ${target} scheduler refused it: ${result.error}`,
'Read the error above, fix the scheduler, then run gbrain maintain --schedule --yes again.', { detail: result.error }), 'maintain', { json }));
return;
}
print(json, { status: 'installed', target, written: result.written, notes: result.notes, interval_hours: SCHEDULE_INTERVAL_HOURS },
[`Scheduled free upkeep: ${what}.`, ` Wrote: ${result.written.join(', ')}`, ` Log: ${paths.log}`, ...result.notes.map((n) => ` ${n}`),
' A run exits at once while a gbrain serve owns the brain or upkeep is not due.', ' Remove: gbrain maintain --unschedule']);
}
/**
* The engine-free part of `gbrain maintain`, routed before connectEngine: `--schedule` and
* `--unschedule`, and a scheduled run (`--unattended --runner schedule`) while a live serve
* owns the brain, which exits 0 without opening it (a PGLite open would wait on the serve's lock).
*/
export async function tryRunMaintainEngineFree(args: string[], deps: { liveServe?: () => Promise<boolean>; env?: ScheduleEnv } = {}): Promise<boolean> {
if (args.includes('--help') || args.includes('-h')) return false;
if (args.includes('--schedule') || args.includes('--unschedule')) {
await runMaintainSchedule(args, deps.env);
return true;
}
const runner = args.indexOf('--runner');
const scheduled = args.includes('--unattended') && runner >= 0 && args[runner + 1] === 'schedule';
if (!scheduled || !await (deps.liveServe ?? liveServeOwnsBrain)()) return false;
const message = 'A gbrain serve owns this brain and runs free upkeep while it is idle (serve owns upkeep), so the scheduled run did nothing.';
print(args.includes('--json'), { status: 'skipped', exit: 0, code: 'maintenance_owned_by_serve', message }, [message]);
return true;
}