Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
/** Source mutations use authenticated resident ingress before any PGLite open. */
import type { BrainEngine } from '../core/engine.ts';
import { OperationError } from '../core/ops/contract.ts';
import { getCliOptions } from '../core/cli-options.ts';
import { loadConfig } from '../core/config.ts';
import { resolveBrainId } from '../core/brain-resolver.ts';
import { loadMounts } from '../core/brain-registry.ts';
import { writeStdoutFinal, setCliExitVerdict } from '../core/cli-force-exit.ts';
import { maybeDelegateLocalAdministration, persistenceConfigForBrain } from '../core/persistence/local-client.ts';
import { runPersistenceAdministration } from '../core/persistence/administration.ts';
import { managedPersistenceEnabled } from '../core/persistence/ownership.ts';
import { assertTopologyCommitted } from '../core/persistence/managed-sources.ts';
import { parseSourceLifecycleArgs, type ParsedSourceLifecycle } from './sources-lifecycle-args.ts';
import { reportPersistenceCliError } from './persistence-delegate.ts';
import { adminHostConfig } from './persistence-admin.ts';
import type { AddSourceOpts } from '../core/sources-ops.ts';
export const SOURCE_LIFECYCLE_HELP = `Managed source administration:
gbrain sources add <id> [--path <directory> | --url <https-url> | --kind github|google|meetings|slack|imessage]
gbrain sources archive <id>
gbrain sources restore <id> [--no-federate]
gbrain sources remove <id> --confirm-destructive
gbrain sources purge <archived-id> --confirm-destructive
gbrain sources set-path <id> <verified-directory>
gbrain sources set-path <id> --clear (connector sources, or any relative local_path: clear it)
gbrain sources reclone <id>
All commands accept --request-id <uuid>, --expected-incarnation <uuid>, --dry-run,
--brain <id>, and --json. Retain the returned request ID across retries. Rebind
requires an exact canonical manifest, including deletions; --force cannot bypass
ownership. Remove and purge retain local storage for explicit operator cleanup.
Unmanaged installations retain their existing source command behavior.`;
function checkManagedOptions(parsed: ParsedSourceLifecycle): void {
if (parsed.legacyOnly) throw new OperationError('writer_coordinator_required',
'Source creation cannot also install legacy Git hardening on a managed worktree.',
'Create the source without --pat-file. Configure supported postpublication Git effects separately.');
}
/** A slack source is checked against Slack (token, scopes, every channel) before it is registered. */
async function preflightSlack(parsed: ParsedSourceLifecycle): Promise<void> {
const options = parsed.operation === 'source_add' && parsed.params.dry_run !== true ? parsed.params.options as AddSourceOpts | undefined : undefined;
if (options?.slack) await (await import('../core/slack/source-add.ts')).preflightSlackAdd(options.id, options.slack);
}
export async function executeSourceLifecycle(engine: BrainEngine, parsed: ParsedSourceLifecycle): Promise<Record<string, unknown>> {
checkManagedOptions(parsed);
await preflightSlack(parsed);
return runPersistenceAdministration(engine, parsed.operation, parsed.params);
}
/** GST-2732: what a committed add means for default search and a plain folder, on stderr and as `notices`. */
async function addOutcome(result: Record<string, unknown>, parsed?: ParsedSourceLifecycle, engine?: BrainEngine): Promise<Record<string, unknown>> {
const options = parsed?.operation === 'source_add' ? parsed.params.options as AddSourceOpts | undefined : undefined;
if (!options || result.dry_run === true || result.state !== 'committed') return result;
let federated = (result.config as Record<string, unknown> | undefined)?.federated;
if (federated === undefined && engine) {
const rows = await engine.executeRaw<{ f: unknown }>(`SELECT config->'federated' AS f FROM sources WHERE id = $1`, [options.id]).catch(() => []);
federated = rows[0]?.f ?? (rows.length ? false : undefined);
}
if (federated === undefined) return result;
const connector = !!(options.github || options.google || options.meetings || options.slack);
const notices = await (await import('./sources-add-next.ts')).reportAddOutcome({ id: options.id, chosen: connector ? true : options.federated,
federated: federated === true,
path: options.localPath && typeof result.local_path === 'string' ? result.local_path : null, json: false, say: line => console.error(line.trim()) });
return notices ? { ...result, notices } : result;
}
async function render(result: Record<string, unknown>, parsed?: ParsedSourceLifecycle, engine?: BrainEngine): Promise<void> {
result = await addOutcome(result, parsed, engine);
await writeStdoutFinal(JSON.stringify(result, null, 2) + '\n');
if (result.dry_run !== true) {
try { assertTopologyCommitted(result); }
catch { setCliExitVerdict(1); }
}
}
/** Also called by connected command users so no legacy raw DELETE/UPDATE slips through. */
export async function runConnectedSourceLifecycle(engine: BrainEngine, args: string[]): Promise<boolean> {
if (!await managedPersistenceEnabled(engine)) return false;
const parsed = parseSourceLifecycleArgs(args);
await render(await executeSourceLifecycle(engine, parsed), parsed, engine);
return true;
}
export async function runSourceLifecycleCli(args: string[], getEngine: () => Promise<BrainEngine>): Promise<void> {
if (args.some(arg => arg === '--help' || arg === '-h')) { console.log(SOURCE_LIFECYCLE_HELP); return; }
try {
let parsed: ParsedSourceLifecycle | undefined;
let parseError: unknown;
try { parsed = parseSourceLifecycleArgs(args); } catch (error) { parseError = error; }
// Global CLI routing has already consumed --brain; parsing retains it for direct callers too.
const brainId = resolveBrainId(parsed?.brain ?? getCliOptions().brain);
const config = adminHostConfig(persistenceConfigForBrain(loadConfig(), brainId, brainId === 'host' ? [] : loadMounts()), brainId,
'Source administration', `sources ${args[0] ?? ''}`.trim());
if (args[0] === 'set-path' && args.includes('--clear')) {
const { runSetPath } = await import('./sources-set-path.ts');
await runSetPath(await getEngine(), args.slice(1));
return;
}
if (parsed) {
// --pat-file must refuse before the resident owner can create anything.
await preflightSlack(parsed);
const delegated = await maybeDelegateLocalAdministration(parsed.operation,
{ ...parsed.params, ...(parsed.legacyOnly ? { legacy_hardening: true } : {}) }, config,
{ timeoutMs: getCliOptions().timeoutMs ?? undefined });
if (delegated.handled) { await render(delegated.result as Record<string, unknown>, parsed); return; }
} else {
// An invalid mutation must not attempt another datastore open while its owner is live.
const { inspectLockHolder } = await import('../core/pglite-lock.ts');
if (config.engine === 'pglite' && config.database_path && inspectLockHolder(config.database_path).held) throw parseError;
}
const engine = await getEngine();
if (await managedPersistenceEnabled(engine)) {
if (!parsed) throw parseError;
await render(await executeSourceLifecycle(engine, parsed), parsed, engine);
} else {
const { runSources } = await import('./sources.ts');
await runSources(engine, args);
}
} catch (error) {
if (!await reportPersistenceCliError(error, args.includes('--json'))) throw error;
}
}