Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
/**
* gbrain brainstorm — bisociation-style idea generation grounded in your
* own notes.
*
* v0.37.0 wave (D14 + D6 + D11 + D12). Pulls a small close-set via
* hybridSearch, a far-set via prefix-stratified domain-bank, crosses them
* via gateway.chat, and judges via the shared 5-axis rubric. Output cites
* close + far slugs with a 0-1 distance score (D6 transparency).
*
* For "Lateral Synaptic Drift" — the inverted-judge / stale-bias variant —
* see `src/commands/lsd.ts` which calls the same orchestrator with the
* LSD_PROFILE config object.
*/
import type { BrainEngine } from '../core/engine.ts';
import { setCliExitVerdict } from '../core/cli-force-exit.ts';
import {
runBrainstorm,
formatBrainstormMarkdown,
buildBrainstormFrontmatterObject,
BRAINSTORM_PROFILE,
LSD_PROFILE,
type BrainstormProfile,
} from '../core/brainstorm/orchestrator.ts';
import { loadConfig } from '../core/config.ts';
import { StructuredAgentError } from '../core/errors.ts';
import { parseMarkdown, serializeMarkdown } from '../core/markdown.ts';
import { importFromContent } from '../core/import-file.ts';
import { privateRequestRefusal } from '../core/persistence/visibility-request.ts';
import { isWriteThroughDisabled, resolvePageWriteTarget, writePageThrough, type WriteThroughResult } from '../core/write-through.ts';
import { fileDatabaseDriftToken, replaceableFile } from '../core/facts/file-body-guard.ts';
import { managedPersistenceEnabled } from '../core/persistence/ownership.ts';
import { submitPageMutation } from '../core/persistence/page-mutations.ts';
import { acceptPendingCovers, currentCliWriteWait, pendingReceiptOf, pollCommand } from '../core/persistence/write-wait.ts';
import { PENDING_WRITE_EXIT_CODE } from '../core/exit-codes.ts';
import { randomBytes } from 'crypto';
import { legacyNestedErrorDocument } from '../core/agent-output.ts';
import { CapFlagError, mergeCapFlag, parseCapFlag, type CapFlag } from '../core/budget/cap-flag.ts';
export interface BrainstormCliArgs {
question?: string;
json: boolean;
save?: boolean;
yes: boolean;
limit?: number;
/** Cost ceiling in USD (`--max-usd`, legacy `--max-cost`); null = off; undefined = the $5 default. */
maxCost?: number | null;
/** The cap flag spelling the user typed. */
maxCostFlag?: string;
/** Hard cap on far-set prefix sampling. Default 50. */
maxFarSet?: number;
/** When true, abort mid-run if running spend exceeds 5× estimate. */
strictBudget?: boolean;
/** Override the model used for the judge phase. */
judgeModel?: string;
/** Max ideas per judge LLM call. Default 100. */
maxIdeasPerJudgeCall?: number;
/** TX4: resume a crashed run by run_id. */
resume?: string;
/** Bypass the 7-day staleness gate on resume. */
forceResume?: boolean;
/** When true, print the list of saved runs + exit. */
listRuns?: boolean;
help: boolean;
error?: string;
}
export function parseBrainstormArgs(args: string[]): BrainstormCliArgs {
const out: BrainstormCliArgs = { json: false, yes: false, help: false };
const positional: string[] = [];
let cap: CapFlag | undefined;
let i = 0;
while (i < args.length) {
const arg = args[i];
if (arg === '--help' || arg === '-h') {
out.help = true;
} else if (arg === '--json') {
out.json = true;
} else if (arg === '--save') {
out.save = true;
} else if (arg === '--no-save') {
out.save = false;
} else if (arg === '--yes' || arg === '-y') {
out.yes = true;
} else if (arg === '--limit') {
const v = args[++i];
const n = v ? parseInt(v, 10) : NaN;
if (!Number.isFinite(n) || n <= 0) {
out.error = `--limit requires a positive integer (got ${v})`;
return out;
}
out.limit = n;
} else if (arg === '--max-usd' || arg === '--max-cost') {
try {
cap = mergeCapFlag(cap, parseCapFlag(arg, args[++i]));
} catch (err) {
if (!(err instanceof CapFlagError)) throw err;
out.error = err.message;
return out;
}
out.maxCost = cap.usd;
out.maxCostFlag = cap.flag;
} else if (arg === '--max-far-set') {
const v = args[++i];
const n = v ? parseInt(v, 10) : NaN;
if (!Number.isFinite(n) || n <= 0) {
out.error = `--max-far-set requires a positive integer (got ${v})`;
return out;
}
out.maxFarSet = n;
} else if (arg === '--strict-budget') {
out.strictBudget = true;
} else if (arg === '--judge-model') {
const v = args[++i];
if (!v) {
out.error = `--judge-model requires a model id (e.g. anthropic:claude-sonnet-4-6)`;
return out;
}
out.judgeModel = v;
} else if (arg === '--max-ideas-per-judge-call') {
const v = args[++i];
const n = v ? parseInt(v, 10) : NaN;
if (!Number.isFinite(n) || n <= 0) {
out.error = `--max-ideas-per-judge-call requires a positive integer (got ${v})`;
return out;
}
out.maxIdeasPerJudgeCall = n;
} else if (arg === '--resume') {
const v = args[++i];
if (!v || v.startsWith('--')) {
out.error = `--resume requires a run_id (use --list-runs to see saved runs)`;
return out;
}
out.resume = v;
} else if (arg === '--force-resume') {
out.forceResume = true;
} else if (arg === '--list-runs') {
out.listRuns = true;
} else if (arg.startsWith('--')) {
out.error = `unknown flag: ${arg}`;
return out;
} else {
positional.push(arg);
}
i++;
}
if (positional.length > 0) {
out.question = positional.join(' ');
}
return out;
}
const BRAINSTORM_HELP = `Usage: gbrain brainstorm <question> [options]
Bisociation idea generator grounded in your own notes. Pulls a close-set
via hybrid search and a far-set via prefix-stratified domain-bank, crosses
them, judges with a 5-axis rubric. Output cites close + far slugs with a
0-1 distance score so you can see how far each collision actually traveled.
Options:
--json Emit BrainstormResult as JSON (for agents)
--save Save to wiki/ideas/<date>-brainstorm-<slug>.md (default ON)
--no-save Don't save; print only
--yes, -y Skip the 10s cost-preview wait (TTY only)
--limit N Override the far-bank size (default 6 brainstorm / 12 LSD)
--max-usd USD|off Abort if estimated cost exceeds USD (default 5;
--max-cost is the legacy spelling). off runs
uncapped. A model with no price runs under the
default with a warning; an explicit cap refuses
it until you register its rate (gbrain pricing set)
--max-far-set N Cap domain bank prefix sampling (default 50)
--strict-budget Abort if running cost exceeds 5× the estimate
--judge-model MODEL Override the judge LLM (larger-context for big runs)
--max-ideas-per-judge-call N Max ideas per judge LLM call (default 100)
--resume RUN_ID Resume a previously-crashed run (uses --list-runs ids)
--force-resume Bypass the 7-day staleness gate on --resume
--list-runs Print saved run_ids and exit
--help, -h Show this help
Examples:
gbrain brainstorm "why are AI coding tools converging on the same UX?"
gbrain brainstorm "what's the real bottleneck on lab automation" --json
Cost: ~$0.05-0.15 per run. Set GBRAIN_NO_BRAINSTORM_PREVIEW=1 or pass --yes
to skip the TTY grace window in scripted callers.
See also: gbrain lsd — Lateral Synaptic Drift, the inverted-judge variant
that prefers forgotten pages and rejects ideas that are "too obvious."
`;
const LSD_HELP = `Usage: gbrain lsd <question> [options]
LSD = Lateral Synaptic Drift. Same bisociation engine as \`gbrain brainstorm\`
with the distance dial maxed: bigger far-bank (12 pages), smaller close-set
(2 pages), forgotten pages preferred via the stale-bias signal, inverted
judge that REJECTS ideas scoring too high on coherence ("too obvious — you'd
have thought of this without LSD"), every idea must invert at least one
implicit axiom. Output is ephemeral by default — pass --save if an idea lands.
Options:
--json Emit BrainstormResult as JSON
--save Persist to wiki/ideas/<date>-lsd-<slug>.md (default OFF)
--yes, -y Skip the 10s cost-preview wait (TTY only)
--limit N Override the far-bank size (default 12)
--max-usd USD|off Abort if estimated cost exceeds USD (default 5;
--max-cost is the legacy spelling). off runs
uncapped. A model with no price runs under the
default with a warning; an explicit cap refuses
it until you register its rate (gbrain pricing set)
--max-far-set N Cap domain bank prefix sampling (default 50)
--strict-budget Abort if running cost exceeds 5× the estimate
--judge-model MODEL Override the judge LLM (larger-context for big runs)
--max-ideas-per-judge-call N Max ideas per judge LLM call (default 100)
--resume RUN_ID Resume a previously-crashed run (uses --list-runs ids)
--force-resume Bypass the 7-day staleness gate on --resume
--list-runs Print saved run_ids and exit
--help, -h Show this help
Examples:
gbrain lsd "why are AI coding tools converging on the same UX?"
gbrain lsd "the unspoken assumption in venture pricing" --save
Cost: ~$0.20-0.40 per run.
See also: gbrain brainstorm — the sober, cite-heavy default variant.
`;
/** Shared body: brainstorm.ts → runBrainstormCli(BRAINSTORM_PROFILE); lsd.ts → runBrainstormCli(LSD_PROFILE). */
async function runBrainstormCli(
engine: BrainEngine,
args: string[],
profile: BrainstormProfile,
help: string,
): Promise<void> {
const parsed = parseBrainstormArgs(args);
if (parsed.help) {
console.log(help);
return;
}
if (parsed.error) {
console.error(`gbrain ${profile.label}: ${parsed.error}`);
console.error(help);
process.exit(2);
return;
}
if (parsed.listRuns) {
const { listRuns } = await import('../core/brainstorm/checkpoint.ts');
const runs = listRuns();
if (parsed.json) {
console.log(JSON.stringify(runs, null, 2));
} else if (runs.length === 0) {
console.log('No saved brainstorm runs.');
} else {
console.log('Saved runs (newest first):');
console.log('run_id | iso_date | question');
console.log('------------------+---------------------------+----------------');
for (const r of runs) {
const iso = new Date(r.mtime).toISOString();
console.log(`${r.run_id} | ${iso} | ${r.question.slice(0, 60)}`);
}
}
return;
}
if (!parsed.question || parsed.question.trim().length === 0) {
console.error(`gbrain ${profile.label}: question required`);
console.error(help);
process.exit(2);
return;
}
const config = loadConfig() ?? {};
// Honor env-var skip for scripted environments that can't easily pass --yes.
const skipPreview = parsed.yes || process.env.GBRAIN_NO_BRAINSTORM_PREVIEW === '1';
// --limit override: replace m_far on a shallow copy of the profile.
const effectiveProfile: BrainstormProfile = parsed.limit
? { ...profile, m_far: parsed.limit }
: profile;
// v0.39.3.0 WARN-10 + CV11 — catch StructuredAgentError 'brainstorm_timeout'
// surfaced by the orchestrator's outer wrap and format it like the
// cli.ts:188-191 OperationError block (Error [code]: message + Hint line
// + exit 1). Non-typed errors (including BudgetExhausted from v0.39.0.0
// T10's gateway-layer cap) fall through to the dispatcher's existing
// catch. Without this CLI formatter, the typed error reaches main()'s
// generic catch which prints `e.message` only — losing the structured
// `.hint` field that's the whole point of the orchestrator-level wrap.
// Save policy: brainstorm defaults to save-on; lsd defaults to save-off.
// CLI --save / --no-save overrides the default. The slug is minted BEFORE
// the run so the orchestrator can bank it in the checkpoint: a `--resume`
// after a judge failure then hands back the slug the failed run saved
// under, and the re-scored page overwrites it instead of forking a second
// page under a fresh nonce.
const shouldSave = parsed.save ?? profile.default_save;
const freshSlug = buildIdeaSlug(parsed.question, profile.label);
let result;
try {
result = await runBrainstorm(engine, config, {
question: parsed.question,
profile: effectiveProfile,
skipCostPreview: skipPreview,
ideaSlug: shouldSave ? freshSlug : undefined,
// v0.39.0.0 T10 cost-cap surface — wired in master, preserved here.
maxCostUsd: parsed.maxCost,
maxCostFlag: parsed.maxCostFlag,
maxFarSet: parsed.maxFarSet,
strictBudget: parsed.strictBudget,
judgeModel: parsed.judgeModel,
maxIdeasPerJudgeCall: parsed.maxIdeasPerJudgeCall,
resumeRunId: parsed.resume,
forceResume: parsed.forceResume,
});
} catch (err) {
if (err instanceof StructuredAgentError) {
if (parsed.json) {
// Agents reading --json get the structured envelope (matches
// serializeError shape from src/core/errors.ts).
console.log(JSON.stringify(legacyNestedErrorDocument(err.envelope), null, 2));
} else {
console.error(`Error [${err.envelope.code}]: ${err.envelope.message}`);
if (err.envelope.hint) console.error(` Hint: ${err.envelope.hint}`);
}
process.exit(1);
}
throw err; // not our error class — let the dispatcher handle it
}
if (parsed.json) {
console.log(JSON.stringify(result, null, 2));
return;
}
// Human-readable: render via formatBrainstormMarkdown. `onlyPassed: true`
// by default — passes-only output is the headline; failed ideas live in
// the JSON / saved page for triage.
const md = formatBrainstormMarkdown(result, { onlyPassed: true, includeMeta: true });
console.log(md);
if (shouldSave) {
const slug = result.idea_slug ?? freshSlug;
const title = `${profile.label === 'lsd' ? 'LSD' : 'Brainstorm'}: ${parsed.question.slice(0, 100)}`;
// Build ONE frontmatter object and render via the canonical serializer so
// the saved file round-trips through `gbrain sync` byte-for-byte. Include
// filtered ideas (onlyPassed:false) so a judge-failed run still shows every
// idea; `--resume <run_id>` re-scores and overwrites this same page.
const fmObj = { ...buildBrainstormFrontmatterObject(result), source_kind: profile.label };
const body = formatBrainstormMarkdown(result, { onlyPassed: false, includeMeta: true });
const content = serializeMarkdown(fmObj, body, '', { type: 'note', title, tags: [] });
const outcome = await persistSavedIdea(engine, { slug, content, provenanceVia: profile.label });
const msg = formatSaveOutcome(outcome, { profileLabel: profile.label, slug });
if (msg.stdout) console.log(msg.stdout);
for (const line of msg.stderr) console.error(line);
if (msg.exitCode) setCliExitVerdict(msg.exitCode);
}
}
/** Outcome of persisting a saved idea to both sinks. */
export interface SaveOutcome {
/** True when the canonical DB import (importFromContent) succeeded. */
dbSaved: boolean;
/** Set when the DB import threw. */
dbError?: string;
/** Disk write-through result (rendered from the saved row). */
writeThrough: WriteThroughResult;
/** Set when nothing was saved because the page's file holds content the database lacks (`file_database_drift`). */
held?: string;
/** G6: the door accepted the save and it was still pending when the CLI write wait ended; it may still commit. */
pending?: { requestId: string; poll: string; acceptPending: boolean };
}
export interface SaveMessage {
/** Human-readable success line for stdout (omitted when nothing persisted). */
stdout?: string;
/** Error / warning lines for stderr. */
stderr: string[];
/** Nonzero ONLY when nothing was persisted (no DB row AND no file). */
exitCode: number;
}
/**
* Persist a saved idea through the CANONICAL ingestion path: importFromContent
* (chunks + tags + content_hash + source_path, but `noEmbed` so we don't pay
* embedding cost at save time) writes the DB row, then the shared
* `writePageThrough` helper renders that row to disk. Rendering from the row
* means the two sinks cannot diverge, and the row matches what `gbrain sync`
* would produce — so a later sync doesn't churn it (the CLI puts `source_kind`
* in the content's frontmatter, so the row and the rendered file agree). The
* file is only attempted when the DB write landed (it's rendered from the row).
*
* #6982: before importing, the page's file (a `--resume` reuses the slug) must
* hold nothing the database lacks (`replaceableFile`); otherwise nothing is
* saved and `held` says why. The file write is bound to the bytes compared, so
* an edit landing during the save is kept (`skipped: 'file_changed'`).
*/
export async function persistSavedIdea(
engine: BrainEngine,
args: { slug: string; content: string; sourceId?: string; provenanceVia: string },
): Promise<SaveOutcome> {
const sourceId = args.sourceId ?? 'default';
const wait = currentCliWriteWait();
// G6: a managed brain refuses direct imports. put_page through the door publishes the file before the row; a --resume
// overwrite binds to the revision it read (expected_revision), and the door's compare-before-replace guards the file.
try {
if (await managedPersistenceEnabled(engine)) {
const snapshot = await engine.readPageSnapshot(args.slug, { sourceId, includeDeleted: true });
const response = await submitPageMutation({ engine, config: loadConfig() ?? { engine: engine.kind } as never, remote: false, dryRun: false, sourceId,
writeWaitMs: wait.waitMs,
logger: { info() {}, warn() {}, error() {} } }, { operation: 'put_page', params: { slug: args.slug, source_id: sourceId, content: args.content,
source_kind: args.provenanceVia, ...(snapshot ? { expected_revision: snapshot.revision } : {}) } });
const writeThrough = (response.write_through ?? { written: false }) as WriteThroughResult;
const target = writeThrough.written ? await resolvePageWriteTarget(engine, args.slug, sourceId) : null;
return { dbSaved: true, writeThrough: target?.ok ? { ...writeThrough, path: target.filePath } : writeThrough };
}
} catch (err) {
const receipt = pendingReceiptOf(err);
if (receipt) return { dbSaved: false, writeThrough: { written: false }, pending: { requestId: receipt.request_id,
poll: pollCommand(receipt.request_id, (err as { fix?: { argv?: readonly string[] } }).fix), acceptPending: wait.acceptPending && acceptPendingCovers(receipt) } };
return { dbSaved: false, dbError: err instanceof Error ? err.message : String(err), writeThrough: { written: false } };
}
let dbSaved = false;
let dbError: string | undefined;
let expectedFileBytes: string | null | undefined;
try {
const target = await isWriteThroughDisabled(engine) ? null : await resolvePageWriteTarget(engine, args.slug, sourceId);
const file = target?.ok ? await replaceableFile(engine, sourceId, args.slug, target.filePath) : null;
if (file && !file.ok) {
return { dbSaved: false, held: fileDatabaseDriftToken(args.slug, sourceId, 'before', 'the idea was not saved'), writeThrough: { written: false } };
}
expectedFileBytes = file?.expectedFileBytes;
const imported = await importFromContent(engine, args.slug, args.content, {
noEmbed: true,
sourceId,
sourcePath: `${args.slug}.md`,
holdNoncanonicalPrivate: true,
});
if (imported.refusal?.code === 'visibility_noncanonical') throw privateRequestRefusal({ slug: imported.slug, source_id: sourceId }, parseMarkdown(args.content, `${imported.slug}.md`).frontmatter);
if (imported.refusal) throw new Error(imported.refusal.message);
dbSaved = true;
} catch (err) {
dbError = err instanceof Error ? err.message : String(err);
}
const writeThrough: WriteThroughResult = dbSaved
? await writePageThrough(engine, args.slug, {
sourceId,
frontmatterOverrides: { source_kind: args.provenanceVia },
expectedFileBytes,
})
: { written: false, skipped: 'page_not_found_after_write' };
return { dbSaved, dbError, writeThrough };
}
/**
* Render an honest save message from the outcome. Every branch names the real
* state; the only nonzero exit is the total-failure case (nothing persisted),
* so scripts can't read a failed `--save` as success. A file-write failure when
* the DB row landed stays exit 0 — the row is durable and `gbrain sync`
* reconciles the disk file on the next run.
*/
export function formatSaveOutcome(
outcome: SaveOutcome,
ctx: { profileLabel: string; slug: string },
): SaveMessage {
const { dbSaved, dbError, writeThrough } = outcome;
const stderr: string[] = [];
if (outcome.held) {
stderr.push(`gbrain ${ctx.profileLabel}: save refused: ${outcome.held}. Rerun with --resume <run_id> once the page and its file agree.`);
return { stderr, exitCode: 1 };
}
if (outcome.pending) {
return {
stdout: `\n_Save of page \`${ctx.slug}\` accepted and still pending (request ${outcome.pending.requestId}); it may still commit. Check it with \`${outcome.pending.poll}\`._`,
stderr,
exitCode: outcome.pending.acceptPending ? 0 : PENDING_WRITE_EXIT_CODE,
};
}
if (dbError) stderr.push(`gbrain ${ctx.profileLabel}: DB save failed: ${dbError}`);
if (writeThrough.error) {
stderr.push(`gbrain ${ctx.profileLabel}: file write failed: ${writeThrough.error}`);
}
if (dbSaved && writeThrough.written) {
return {
stdout: `\n_Saved to DB page \`${ctx.slug}\` and file \`${writeThrough.path}\`._`,
stderr,
exitCode: 0,
};
}
if (dbSaved && writeThrough.skipped === 'no_repo_configured') {
return {
stdout: `\n_Saved to DB page \`${ctx.slug}\` (no \`sync.repo_path\` set — skipped file write)._`,
stderr,
exitCode: 0,
};
}
if (dbSaved && writeThrough.skipped === 'repo_not_found') {
return {
stdout: `\n_Saved to DB page \`${ctx.slug}\` (the source directory, \`sources.local_path\` or \`sync.repo_path\`, is relative or not a directory — skipped file write)._`,
stderr,
exitCode: 0,
};
}
if (dbSaved && writeThrough.skipped === 'file_changed') {
return {
stdout: `\n_Saved to DB page \`${ctx.slug}\` (its file changed during the save and was kept, not rewritten: file_changed; \`gbrain sync\` imports that edit, and page history keeps this save)._`,
stderr,
exitCode: 0,
};
}
if (dbSaved && writeThrough.skipped === 'mirror_read_only') {
return {
stdout: `\n_Saved to DB page \`${ctx.slug}\` (the source is a read-only mirror, \`gbrain sources mirror-readonly\` — kept database-only)._`,
stderr,
exitCode: 0,
};
}
if (dbSaved && writeThrough.skipped === 'url_clone') {
return {
stdout: `\n_Saved to DB page \`${ctx.slug}\` (the source is a clone gbrain pulls from upstream — kept database-only)._`,
stderr,
exitCode: 0,
};
}
if (dbSaved) {
// File write attempted but errored (already on stderr). Row is durable.
return {
stdout: `\n_Saved to DB page \`${ctx.slug}\` (file NOT written — see error above; \`gbrain sync\` will reconcile)._`,
stderr,
exitCode: 0,
};
}
// Nothing persisted — the silent-false-success bug class. Exit nonzero.
stderr.push(
`gbrain ${ctx.profileLabel}: save FAILED — neither DB page nor file was written. The idea is NOT persisted.`,
);
return { stderr, exitCode: 1 };
}
/**
* Slugify the question for the saved page path. Collision-resistant via a date
* prefix AND a random nonce suffix — two same-day runs whose questions share
* the first 60 slug chars (or both slugify to empty → `untitled`) would
* otherwise produce the same slug, and both the DB upsert and the file write
* would silently clobber the earlier idea. The nonce is injectable so tests are
* deterministic; production uses crypto random.
*/
export function buildIdeaSlug(
question: string,
label: 'brainstorm' | 'lsd',
nonce?: string,
): string {
const date = new Date().toISOString().slice(0, 10);
const stem = question
.toLowerCase()
.replace(/[^a-z0-9]+/g, '-')
.replace(/^-+|-+$/g, '')
.slice(0, 60)
.replace(/^-+|-+$/g, '');
const suffix = nonce ?? randomBytes(3).toString('hex');
return `wiki/ideas/${date}-${label}-${stem || 'untitled'}-${suffix}`;
}
/** CLI entry: `gbrain brainstorm`. */
export async function runBrainstormCommand(engine: BrainEngine, args: string[]): Promise<void> {
return runBrainstormCli(engine, args, BRAINSTORM_PROFILE, BRAINSTORM_HELP);
}
/** CLI entry: `gbrain lsd`. */
export async function runLsdCommand(engine: BrainEngine, args: string[]): Promise<void> {
return runBrainstormCli(engine, args, LSD_PROFILE, LSD_HELP);
}