Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(lane-h): live-serve two-step plans, explicit --brain/--source in journey fixes, op-lane --json, usage envelopes

garrytanff39a91307f0
diff --git a/src/cli.ts b/src/cli.ts
index b71c7faad6..f581100b7d 100755
--- a/src/cli.ts
+++ b/src/cli.ts
@@ -1584,6 +1584,12 @@ export function formatResult(
result: unknown,
params: Record<string, unknown> = {},
): string {
+ // D2: `--json` on the op lane is the result document for every op. Only
+ // search/query render it themselves (retrieval redaction + stderr notice);
+ // list/stats/health/tags/timeline used to print their human table instead.
+ if (params.json === true && opName !== 'search' && opName !== 'query') {
+ return JSON.stringify(result, bigintToStringReplacer, 2) + '\n';
+ }
switch (opName) {
case 'volunteer_context': {
const r = result as any;
diff --git a/src/cli/cli-error.ts b/src/cli/cli-error.ts
index d5080e4de0..1f838c0869 100644
--- a/src/cli/cli-error.ts
+++ b/src/cli/cli-error.ts
@@ -22,6 +22,7 @@ import { redactUrlsInText } from '../core/url-redact.ts';
import { redactConnectionInfo } from '../core/audit/redact-connection-info.ts';
import { suggestNearest } from '../core/levenshtein.ts';
import { isConsentRefusal, printConsentRefusal } from '../core/consent.ts';
+import { exclusiveFix, liveServeOwner } from '../core/exclusive-fix.ts';
export interface CliErrorWriteOpts {
/** Raw argv (defaults to process.argv.slice(2)); decides `--json`. */
@@ -135,8 +136,17 @@ export function writeFatalCliError(e: unknown, opts: { argv?: readonly string[];
const busy = e as { code?: unknown; reason?: unknown; message?: unknown } | null;
if (busy?.code === 'pglite_busy') {
const next = 'Wait for the current command or server to close, then retry. Do not remove a live lock.';
- const err = opError('pglite_busy', String(busy.message ?? 'The brain is busy.'), next, {
+ // A7: a live serve owns the brain (usually an agent session's stdio serve), so
+ // waiting never ends; the fix is the two-step plan: stop that serve, then re-run this command.
+ const owner = liveServeOwner(e);
+ const fix = owner ? exclusiveFix({ argv: ['gbrain', ...argv], consent: [], actor: 'agent', requires_exclusive: true,
+ why: 'Re-runs this command once it has the brain to itself.' }, owner) : undefined;
+ const suggestion = fix
+ ? 'A live gbrain serve owns this brain, so waiting does not end. Ask the user to stop it (fix), then re-run this command (fix.then). Do not remove a live lock.'
+ : next;
+ const err = opError('pglite_busy', String(busy.message ?? 'The brain is busy.'), suggestion, {
...(typeof busy.reason === 'string' ? { reason: busy.reason } : {}),
+ ...(fix ? { fix } : {}),
});
return writeCliError(err, command, { argv, legacy: { error: 'pglite_busy', retryable: true, reason: busy.reason, next_action: next } });
}
diff --git a/src/commands/doctor/check-fix.ts b/src/commands/doctor/check-fix.ts
index b93853bc2d..4cadc4a156 100644
--- a/src/commands/doctor/check-fix.ts
+++ b/src/commands/doctor/check-fix.ts
@@ -13,6 +13,7 @@ import { cliRenderContext, redactForTransport, renderAction, type Action, type R
import { embeddingEnablement, type ReadinessEntry, type ReadinessState } from '../../core/readiness.ts';
import { loadConfig } from '../../core/config.ts';
import { classifyPgAccessError } from '../../core/pg-access-classify.ts';
+import { brainRoutingArgs } from '../../core/brain-resolver.ts';
import type { Check } from '../doctor.ts';
/**
@@ -57,7 +58,7 @@ export function agentFix(argv: string[], why: string, verifyCheck: string, extra
* the highest score this brain can reach (a keyless brain's embed share stays 0).
*/
export function brainScorePlanFix(): Action {
- return agentFix(['gbrain', 'doctor', '--remediation-plan', '--json'],
+ return agentFix(['gbrain', 'doctor', '--remediation-plan', '--json', ...brainRoutingArgs()],
'The plan lists which steps raise each score component, what they cost and the reachable maximum; it changes nothing.', 'brain_score');
}
diff --git a/src/commands/doctor/checks/db-connection.ts b/src/commands/doctor/checks/db-connection.ts
index 2d4322363d..ead18da7ac 100644
--- a/src/commands/doctor/checks/db-connection.ts
+++ b/src/commands/doctor/checks/db-connection.ts
@@ -13,6 +13,7 @@
import { loadConfig, gbrainPath, configPath, getDbUrlSource, type DbUrlSource } from '../../../core/config.ts';
import type { Action } from '../../../core/agent-output.ts';
import { agentFix, doctorVerify } from '../check-fix.ts';
+import { exclusiveFix, liveServeOwner } from '../../../core/exclusive-fix.ts';
import { startHeartbeat } from '../../../core/progress.ts';
import { checkPgliteScratchProbe } from './core-health.ts';
import { computePgliteDataDirCheck } from './pglite-worker.ts';
@@ -137,6 +138,18 @@ async function pgbouncerPrepareCheck(): Promise<Check | null> {
* the very DB that's down (db-repair is the engine-free applier here).
*/
function classifiedConnectionCheck(e: unknown, dbSource?: DbUrlSource): Check {
+ // A7: a live `gbrain serve` owns this PGLite brain (usually an agent session's stdio serve).
+ // The brain is not broken; doctor needs it to itself: stop that serve, then re-run doctor.
+ const owner = liveServeOwner(e);
+ if (owner) {
+ return {
+ name: 'connection', status: 'warn', readiness_state: 'unknown',
+ message: `${e instanceof Error ? e.message : String(e)} The database checks did not run.`,
+ details: { reason: 'live_serve', lock_owner_pid: owner.pid, lock_owner_transport: owner.transport },
+ fix: exclusiveFix(agentFix(['gbrain', 'doctor', '--json'], 'Runs the database checks once doctor has the brain to itself.', 'connection',
+ { requires_exclusive: true }), owner),
+ };
+ }
const d = classifyPgAccessError(e, { url: loadConfig()?.database_url ?? null });
const source = describeUrlSource(dbSource ?? getDbUrlSource());
return {
diff --git a/src/commands/doctor/checks/pglite-worker.ts b/src/commands/doctor/checks/pglite-worker.ts
index 227bf974ec..5674f93948 100644
--- a/src/commands/doctor/checks/pglite-worker.ts
+++ b/src/commands/doctor/checks/pglite-worker.ts
@@ -8,6 +8,8 @@ import * as db from '../../../core/db.ts';
import type { BrainEngine } from '../../../core/engine.ts';
import type { Check } from '../../doctor.ts';
import { agentFix } from '../check-fix.ts';
+import { exclusiveFix } from '../../../core/exclusive-fix.ts';
+import { peekLock } from '../../../core/pglite-lock.ts';
/** Read-only diagnosis; it prints the plan-bound repair command the user approves. */
function pgliteRepairPreview() {
@@ -60,6 +62,9 @@ export function computePgliteDataDirCheck(
`Could not connect, and the PGLite data-dir lock is held by live PID ${diagnosis.lockHolderPid} — ` +
`another gbrain process (often \`gbrain serve\`) has the brain open. Stop it and re-run.${backupNote}`,
remediation_status: 'human_only',
+ ...(diagnosis.lockHolderPid ? { fix: exclusiveFix(agentFix(['gbrain', 'doctor', '--json'],
+ 'Re-runs doctor once it has the brain to itself.', 'pglite_data_dir', { requires_exclusive: true }),
+ { pid: diagnosis.lockHolderPid, transport: peekLock(dataDir).http ? 'http' : 'stdio', is_self: false }) } : {}),
};
case 'missing':
return {
diff --git a/src/commands/doctor/remediate-consent.ts b/src/commands/doctor/remediate-consent.ts
index e85421ab7a..dc4645cd80 100644
--- a/src/commands/doctor/remediate-consent.ts
+++ b/src/commands/doctor/remediate-consent.ts
@@ -21,6 +21,7 @@ import type { Authorization, PlanSelection } from '../../core/consent.ts';
import { computePlanHash } from '../../core/consent.ts';
import { consentGate, engineConsentEnv } from '../../core/consent-cli.ts';
import type { Effect } from '../../core/agent-output.ts';
+import { brainRoutingArgs } from '../../core/brain-resolver.ts';
import type { BrainEngine } from '../../core/engine.ts';
import type { RemediationPlan } from '../../core/remediation/types.ts';
@@ -84,11 +85,11 @@ export function remediateArgv(args: readonly string[]): string[] {
for (let i = 0; i < args.length; i++) {
const a = args[i]!;
if (a === '--yes') continue;
- if (a === '--expect') { i++; continue; }
- if (a.startsWith('--expect=')) continue;
+ if (a === '--expect' || a === '--brain') { i++; continue; }
+ if (a.startsWith('--expect=') || a.startsWith('--brain=')) continue;
out.push(a);
}
- return out;
+ return [...out, ...brainRoutingArgs()];
}
function planSummary(plan: RemediationPlan | null, flags: RemediateFlags, estUsd: number | null): string {
@@ -124,7 +125,7 @@ export async function remediateConsent(engine: BrainEngine, args: readonly strin
const selection = flags.includeRepairs && !flags.resumeMode ? await boundSelection(engine, plan, flags) : undefined;
const planHash = selection ? computePlanHash(selection) : undefined;
const summary = planSummary(plan, flags, estUsd);
- const preview = ['gbrain', 'doctor', '--remediation-plan', '--target-score', String(flags.targetScore), ...(flags.noEmbed ? ['--no-embed'] : []), '--json'];
+ const preview = ['gbrain', 'doctor', '--remediation-plan', '--target-score', String(flags.targetScore), ...(flags.noEmbed ? ['--no-embed'] : []), '--json', ...brainRoutingArgs()];
return consentGate({
command: 'doctor --remediate',
effects,
diff --git a/src/commands/import.ts b/src/commands/import.ts
index 3ba00f3cdd..ca78ee94e8 100644
--- a/src/commands/import.ts
+++ b/src/commands/import.ts
@@ -265,12 +265,18 @@ export async function runImport(
// can take now is this import with --no-embed (pages stay keyword-
// searchable; vectors come later); enabling embeddings asks the user.
if (jsonOutput) {
+ // A1 explicit routing: the fix names the brain and source this run resolved.
+ const { brainRoutingArgs } = await import('../core/brain-resolver.ts');
+ const { resolveSourceWithTier } = await import('../core/source-resolver.ts');
+ const named = args.some(a => a === '--source' || a === '--source-id' || a.startsWith('--source=') || a.startsWith('--source-id='));
+ const target = named ? undefined : await resolveSourceWithTier(engine, null).then(r => r.source_id, () => undefined);
throw opError('embedding_disabled', String(e instanceof Error ? e.message.split('\n')[0] : e),
'Embeddings are off by choice on this brain, so import needs --no-embed; turning embeddings on needs the user\'s consent (gbrain doctor --only embeddings --json shows the command).', {
reason: 'disabled_by_choice',
why: 'This brain was set up keyword-only. Importing with --no-embed keeps every page keyword-searchable; `gbrain embed --stale` adds vectors once embeddings are enabled.',
fix: {
- argv: ['gbrain', 'import', ...args.filter(a => a !== '--json' && a !== '--no-embed'), '--no-embed', '--json'],
+ argv: ['gbrain', 'import', ...args.filter(a => a !== '--json' && a !== '--no-embed'), '--no-embed', '--json',
+ ...(target ? ['--source', target] : []), ...brainRoutingArgs()],
consent: [], actor: 'agent', requires_exclusive: true,
why: 'Imports the same files without computing vectors, which needs no provider key.',
},
diff --git a/src/commands/transcripts.ts b/src/commands/transcripts.ts
index 1a7829fa19..2757f11bab 100644
--- a/src/commands/transcripts.ts
+++ b/src/commands/transcripts.ts
@@ -596,6 +596,11 @@ export async function runTranscripts(engine: BrainEngine, args: string[]): Promi
return;
}
if (sub !== 'recent') {
+ if (sub !== '--help' && sub !== '-h' && args.includes('--json')) {
+ const { exitCliError, usageError } = await import('../cli/cli-error.ts');
+ exitCliError(usageError(sub && !sub.startsWith('-') ? `Unknown transcripts subcommand: ${sub}` : 'gbrain transcripts needs a subcommand: ingest, status or recent.',
+ 'Run `gbrain transcripts recent --json` to list recent transcripts, or `gbrain transcripts --help`.'), 'transcripts', { json: true });
+ }
console.log(HELP);
if (sub && sub !== '--help' && sub !== '-h') setCliExitVerdict(2);
return;
diff --git a/src/commands/whoknows.ts b/src/commands/whoknows.ts
index 122fa0ef8a..77c99c418e 100644
--- a/src/commands/whoknows.ts
+++ b/src/commands/whoknows.ts
@@ -320,6 +320,10 @@ export async function runWhoknows(
return;
}
if ('error' in parsed) {
+ if (args.includes('--json')) {
+ const { exitCliError, usageError } = await import('../cli/cli-error.ts');
+ exitCliError(usageError(`gbrain whoknows: ${parsed.error}`, 'Pass the topic as the positional argument, e.g. gbrain whoknows "lab automation" --json.'), 'whoknows', { json: true });
+ }
console.error(`gbrain whoknows: ${parsed.error}`);
console.error(HELP);
process.exit(2);
diff --git a/src/core/brain-resolver.ts b/src/core/brain-resolver.ts
index ac7ff2802c..cbe779fcaa 100644
--- a/src/core/brain-resolver.ts
+++ b/src/core/brain-resolver.ts
@@ -23,6 +23,7 @@ import { readFileSync, lstatSync, type Stats } from 'fs';
import { join, dirname, resolve } from 'path';
import { HOST_BRAIN_ID, loadMounts, validateMountId, type MountEntry } from './brain-registry.ts';
import { isTrustedDotfile, realpathOrResolve } from './path-confine.ts';
+import { getCliOptions } from './cli-options.ts';
const DOTFILE = '.gbrain-mount';
/** Same regex as brain-registry. Kept in sync. */
@@ -135,6 +136,20 @@ export function resolveBrainId(
}
/** Exposed for tests. */
+/**
+ * A1 explicit routing for a recovery command: `--brain <id>` naming the brain
+ * this process resolved, so the fix acts on that brain when it is run later
+ * from another directory or under a different GBRAIN_BRAIN_ID / .gbrain-mount.
+ * Empty when resolution fails (the fix then keeps today's ambient routing).
+ */
+export function brainRoutingArgs(): string[] {
+ try {
+ return ['--brain', resolveBrainId(getCliOptions().brain)];
+ } catch {
+ return [];
+ }
+}
+
export const __testing = {
readDotfileWalk,
longestPathPrefixMount,
diff --git a/src/core/exclusive-fix.ts b/src/core/exclusive-fix.ts
new file mode 100644
index 0000000000..121970065b
--- /dev/null
+++ b/src/core/exclusive-fix.ts
@@ -0,0 +1,45 @@
+/**
+ * A7 lock ownership for exclusive fixes, split out of readiness.ts so the CLI
+ * error path (fatal seam, doctor's connection check) can wrap a fix without
+ * loading readiness's provider/recipe graph. readiness.ts re-exports it.
+ */
+import type { Action } from './agent-output.ts';
+import type { LockOwner } from './readiness.ts';
+
+/** CLI commands that route themselves through a live owner (`runDelegatedCliOperation` and the persistence delegates). */
+const OWNER_DELEGATED_COMMANDS: ReadonlySet<string> = new Set(['reindex-code', 'sync']);
+
+/**
+ * Wrap an exclusive fix for the current lock owner. No owner, or a command
+ * that delegates to the owner → unchanged. Otherwise a two-step plan: step one
+ * (actor `user`) stops the owning serve, `then` the original command.
+ */
+export function exclusiveFix(action: Action, lockOwner: LockOwner | null): Action {
+ if (!action.requires_exclusive || !lockOwner) return action;
+ if (action.argv?.[0] === 'gbrain' && OWNER_DELEGATED_COMMANDS.has(action.argv[1] ?? '')) return action;
+ const who = lockOwner.transport === 'http'
+ ? `the shared \`gbrain serve --http\` (PID ${lockOwner.pid})`
+ : `the stdio \`gbrain serve\` an agent session started (PID ${lockOwner.pid})`;
+ const restart = lockOwner.transport === 'http'
+ ? 'Start `gbrain serve --http` again afterwards.'
+ : 'Reopen the agent session afterwards so it restarts its gbrain server.';
+ return {
+ argv: ['kill', String(lockOwner.pid)],
+ consent: [],
+ actor: 'user',
+ why: `${who} holds this brain's single-writer lock and the next command needs it exclusively. Stop that server first (quit the session or run this), then run the next step. ${restart}`,
+ user_message: `This needs gbrain's database to itself. Please stop ${who}, then I'll run the next step. ${restart}`,
+ requires_exclusive: false,
+ then: action,
+ };
+}
+
+/**
+ * The owner named by a live-serve lock refusal (`LiveServeLockError` carries
+ * the holder's pid and transport), or null for any other error.
+ */
+export function liveServeOwner(e: unknown): LockOwner | null {
+ const busy = e as { code?: unknown; reason?: unknown; ownerPid?: unknown; ownerTransport?: unknown } | null;
+ if (busy?.code !== 'pglite_busy' || busy.reason !== 'live_serve' || typeof busy.ownerPid !== 'number') return null;
+ return { pid: busy.ownerPid, transport: busy.ownerTransport === 'http' ? 'http' : 'stdio', is_self: busy.ownerPid === process.pid };
+}
diff --git a/src/core/pglite-lock.ts b/src/core/pglite-lock.ts
index 600b53b047..f48f9db72d 100644
--- a/src/core/pglite-lock.ts
+++ b/src/core/pglite-lock.ts
@@ -21,7 +21,14 @@ export class PgliteBusyError extends Error {
}
}
export class LiveServeLockError extends PgliteBusyError {
- constructor(message: string) { super(message, 'live_serve'); this.name = 'LiveServeLockError'; }
+ /** The live serve holding the lock, for the two-step recovery plan (A7 `exclusiveFix`). */
+ readonly ownerPid?: number;
+ readonly ownerTransport?: 'stdio' | 'http';
+ constructor(message: string, owner: { pid?: number; transport?: 'stdio' | 'http' } = {}) {
+ super(message, 'live_serve'); this.name = 'LiveServeLockError';
+ this.ownerPid = owner.pid;
+ this.ownerTransport = owner.transport;
+ }
}
export interface LockHandle {
@@ -242,7 +249,9 @@ function startHeartbeat(path: string, ownerToken: string): ReturnType<typeof set
function busy(lockDir: string): PgliteBusyError {
const metadata = readMetadata(lockDir);
if (metadata && isServeCommand(metadata) && isProcessAlive(metadata.pid!)) {
- return new LiveServeLockError(`GBrain's local database is already open through \`gbrain serve\` (MCP, PID ${metadata.pid ?? 'unknown'}). Use the live serve's IPC/MCP tools or stop it before opening this PGLite datastore. Never remove a live holder's lock.`);
+ const args = Array.isArray(metadata.argv) ? metadata.argv : (metadata.command ?? '').split(/\s+/);
+ return new LiveServeLockError(`GBrain's local database is already open through \`gbrain serve\` (MCP, PID ${metadata.pid ?? 'unknown'}). Use the live serve's IPC/MCP tools or stop it before opening this PGLite datastore. Never remove a live holder's lock.`,
+ { pid: metadata.pid, transport: args.includes('--http') ? 'http' : 'stdio' });
}
return new PgliteBusyError(`GBrain: Timed out waiting for PGLite data-dir lock at ${lockDir}. Retry after the holder finishes. Stop all older GBrain processes before upgrading this datastore's lock protocol; unreadable legacy ownership is never stolen. Never remove a live holder's lock. This lock is separate from \`gbrain sync --break-lock\`.`);
}
diff --git a/src/core/readiness.ts b/src/core/readiness.ts
index 7d255db14f..9c8eb54488 100644
--- a/src/core/readiness.ts
+++ b/src/core/readiness.ts
@@ -344,33 +344,9 @@ function syncConfigEntry(cfg: GBrainConfig): ReadinessEntry | null {
// ── lock ownership + exclusive fixes ───────────────────────────────────────
-/** CLI commands that route themselves through a live owner (`runDelegatedCliOperation` and the persistence delegates). */
-const OWNER_DELEGATED_COMMANDS: ReadonlySet<string> = new Set(['reindex-code', 'sync']);
+import { exclusiveFix } from './exclusive-fix.ts';
-/**
- * Wrap an exclusive fix for the current lock owner. No owner, or a command
- * that delegates to the owner → unchanged. Otherwise a two-step plan: step one
- * (actor `user`) stops the owning serve, `then` the original command.
- */
-export function exclusiveFix(action: Action, lockOwner: LockOwner | null): Action {
- if (!action.requires_exclusive || !lockOwner) return action;
- if (action.argv?.[0] === 'gbrain' && OWNER_DELEGATED_COMMANDS.has(action.argv[1] ?? '')) return action;
- const who = lockOwner.transport === 'http'
- ? `the shared \`gbrain serve --http\` (PID ${lockOwner.pid})`
- : `the stdio \`gbrain serve\` an agent session started (PID ${lockOwner.pid})`;
- const restart = lockOwner.transport === 'http'
- ? 'Start `gbrain serve --http` again afterwards.'
- : 'Reopen the agent session afterwards so it restarts its gbrain server.';
- return {
- argv: ['kill', String(lockOwner.pid)],
- consent: [],
- actor: 'user',
- why: `${who} holds this brain's single-writer lock and the next command needs it exclusively. Stop that server first (quit the session or run this), then run the next step. ${restart}`,
- user_message: `This needs gbrain's database to itself. Please stop ${who}, then I'll run the next step. ${restart}`,
- requires_exclusive: false,
- then: action,
- };
-}
+export { exclusiveFix };
let peekOverride: ((dataDir: string) => LockPeekResult) | null = null;
/** Test seam: count or fake the config plane's one lock read (null restores `peekLock`). */