Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

refactor(lane-h): keep ratcheted modules within ceilings (sibling helpers)

garrytan10569db948a5
diff --git a/src/cli.ts b/src/cli.ts
index f581100b7d..3576b1ac55 100755
--- a/src/cli.ts
+++ b/src/cli.ts
@@ -1611,9 +1611,6 @@ export function formatResult(
}
case 'get_page': {
const r = result as any;
- // `--json` leads (same as get_versions) so an ambiguous_slug envelope
- // stays machine-readable too.
- if (params.json === true) return JSON.stringify(r, null, 2) + '\n';
if (r.error === 'ambiguous_slug') {
return `Ambiguous slug. Did you mean:\n${r.candidates.map((c: string) => ` ${c}`).join('\n')}\n`;
}
@@ -1737,14 +1734,6 @@ export function formatResult(
}
case 'get_versions': {
const versions = result as any[];
- // `--json` is legal on every op lane (findUnknownOpFlag exempts it,
- // parseOpArgs populates params.json), and every other data-returning
- // verb consumes it. This one silently dropped it and printed the human
- // table instead. Same `params.json === true` shape as search/query
- // rather than the process.argv probe: it honors the `--json=false`
- // spelling parseOpArgs already supports and keeps the formatter free
- // of process globals.
- if (params.json === true) return JSON.stringify(versions, null, 2) + '\n';
if (versions.length === 0) return 'No versions.\n';
return versions.map(v => {
// Only elide when something was actually dropped — an unconditional
diff --git a/src/commands/import.ts b/src/commands/import.ts
index ca78ee94e8..dd72179115 100644
--- a/src/commands/import.ts
+++ b/src/commands/import.ts
@@ -187,6 +187,30 @@ export interface RunImportResult {
resealed?: { pages: number; pending_chunks: number; embedding_usd: number | null };
}
+/**
+ * D2 + A1: under `--json` a keyless brain's import refusal is the one document.
+ * The step the agent can take now is the same import with --no-embed (pages
+ * stay keyword-searchable; vectors come later), routed explicitly to the brain
+ * and source this run resolved; turning embeddings on asks the user.
+ */
+async function keylessImportRefusal(engine: BrainEngine, args: string[], e: unknown) {
+ 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);
+ return 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',
+ ...(target ? ['--source', target] : []), ...brainRoutingArgs()],
+ consent: [], actor: 'agent', requires_exclusive: true,
+ why: 'Imports the same files without computing vectors, which needs no provider key.',
+ },
+ });
+}
+
export async function runImport(
engine: BrainEngine,
args: string[],
@@ -261,29 +285,8 @@ export async function runImport(
try {
assertEmbeddingEnabled(loadConfig());
} catch (e) {
- // D2: under --json the refusal is the one document. The step the agent
- // 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',
- ...(target ? ['--source', target] : []), ...brainRoutingArgs()],
- consent: [], actor: 'agent', requires_exclusive: true,
- why: 'Imports the same files without computing vectors, which needs no provider key.',
- },
- });
- }
- console.error(`\n${e instanceof Error ? e.message : e}`);
- console.error('Tip: run `gbrain import <dir> --no-embed` to import without embedding now.');
+ if (jsonOutput) throw await keylessImportRefusal(engine, args, e);
+ console.error(`\n${e instanceof Error ? e.message : e}\nTip: run \`gbrain import <dir> --no-embed\` to import without embedding now.`);
throw new ImportAbortError('embedding disabled (deferred-setup sentinel)');
}
diff --git a/src/commands/init-first-run.ts b/src/commands/init-first-run.ts
index b438e47406..49b912f349 100644
--- a/src/commands/init-first-run.ts
+++ b/src/commands/init-first-run.ts
@@ -12,9 +12,9 @@
* `harness_wiring` (the A7 readiness fix). Extend `buildInitFirstRunNotices`
* rather than adding a second notice.
*/
-import type { Decision, Notice } from '../core/agent-output.ts';
+import { shellQuote, type Decision, type Notice } from '../core/agent-output.ts';
import type { GBrainConfig } from '../core/config.ts';
-import { configReadiness } from '../core/readiness.ts';
+import { configReadiness, embeddingEnablement } from '../core/readiness.ts';
import type { SearchMode } from '../core/search/mode.ts';
export interface InitFirstRunInputs {
@@ -72,3 +72,14 @@ export function buildInitFirstRunNotices(inputs: InitFirstRunInputs): Notice[] {
decisions,
}];
}
+
+/**
+ * The deferred-setup line init prints for `--no-embedding`: the same enable
+ * command readiness gives doctor, embed and MCP (A7 `embeddingEnablement`:
+ * resolved datastore, a provider that fits, pages and facts kept).
+ */
+export function deferredEmbeddingHint(cfg: GBrainConfig): string {
+ const enable = embeddingEnablement(cfg);
+ const step = enable.argv ? shellQuote(enable.argv) : 'gbrain doctor --only embeddings --json';
+ return ` --no-embedding: deferred setup — enable later with \`${step}\` (\`config set embedding_model\` is refused by design)`;
+}
diff --git a/src/commands/init.ts b/src/commands/init.ts
index 45fc0f273f..38a9517a20 100644
--- a/src/commands/init.ts
+++ b/src/commands/init.ts
@@ -17,9 +17,8 @@ import { resolveSourceId } from '../core/source-resolver.ts';
import type { BrainEngine } from '../core/engine.ts';
import { readPrimaryEmbeddingStores, readStoredEmbeddingIdentity } from '../core/stored-embedding-identity.ts';
import { deferInitJsonError, flushInitJsonResult, initJsonError, setInitJsonResult, writeDeferredInitJsonError } from './init-json.ts';
-import { buildInitFirstRunNotices } from './init-first-run.ts';
-import { renderNotice, cliRenderContext, shellQuote } from '../core/agent-output.ts';
-import { embeddingEnablement } from '../core/readiness.ts';
+import { buildInitFirstRunNotices, deferredEmbeddingHint } from './init-first-run.ts';
+import { renderNotice, cliRenderContext } from '../core/agent-output.ts';
import { exitCodeForCode } from '../core/error-catalogue.ts';
import { promptLineStderr } from '../core/interaction.ts';
import type { SearchMode as SearchModeName } from '../core/search/mode.ts';
@@ -1362,17 +1361,6 @@ export class InitPostgresFailure extends Error {
}
}
-/**
- * The deferred-setup line init prints for `--no-embedding`: the same enable
- * command readiness gives doctor, embed and MCP (A7 `embeddingEnablement`:
- * resolved datastore, a provider that fits, pages and facts kept).
- */
-function deferredEmbeddingHint(cfg: GBrainConfig): string {
- const enable = embeddingEnablement(cfg);
- const step = enable.argv ? shellQuote(enable.argv) : 'gbrain doctor --only embeddings --json';
- return ` --no-embedding: deferred setup — enable later with \`${step}\` (\`config set embedding_model\` is refused by design)`;
-}
-
/** Exit-preserving wrapper — direct invocations keep their contract. */
async function initPostgres(opts: Parameters<typeof initPostgresCore>[0]) {
try {
diff --git a/src/commands/serve-http-listen.ts b/src/commands/serve-http-listen.ts
new file mode 100644
index 0000000000..82bfab24ce
--- /dev/null
+++ b/src/commands/serve-http-listen.ts
@@ -0,0 +1,28 @@
+/**
+ * `gbrain serve --http`'s listen step (agent operator wave H2): a taken port
+ * fails the start with `serve_port_in_use` and a next step, instead of the
+ * server announcing itself and holding the brain lock while serving nothing
+ * (Bun runs a listen callback with `listening: false` and then emits `error`
+ * to no listener). Resolves only once the socket really listens.
+ */
+import type { Server } from 'node:http';
+import { opError } from '../core/ops/contract.ts';
+
+export async function listenOrRefuse(app: { listen(port: number, host: string): Server }, port: number, bind: string): Promise<Server> {
+ const server = app.listen(port, bind);
+ const failure = await new Promise<Error | null>(resolve => {
+ if (server.listening) return resolve(null);
+ server.once('listening', () => resolve(null));
+ server.once('error', (e: Error) => resolve(e));
+ });
+ if (!failure) return server;
+ try { server.close(); } catch { /* never listened */ }
+ throw opError('serve_port_in_use', `gbrain serve --http could not listen on ${bind}:${port}: ${failure.message}`,
+ 'Nothing was started and the brain is free again. Stop the process holding the port, or pass another --port (and point the harnesses at that URL).', {
+ why: 'Another process (often an earlier gbrain serve --http) already listens on that address.',
+ fix: {
+ argv: ['gbrain', 'serve', '--http', '--bind', bind, '--port', String(port + 1)], consent: ['persistent_install'], actor: 'user', requires_exclusive: true,
+ why: 'Starts the shared server on the next port; every harness must then use that URL.',
+ },
+ });
+}
diff --git a/src/commands/serve-http.ts b/src/commands/serve-http.ts
index d4b9c8062b..1626e23160 100644
--- a/src/commands/serve-http.ts
+++ b/src/commands/serve-http.ts
@@ -15,6 +15,7 @@
* is re-exported below.
*/
+import { listenOrRefuse } from './serve-http-listen.ts';
import express from 'express';
import type { Socket } from 'net';
import type { Request, RequestHandler, CookieOptions } from 'express';
@@ -847,27 +848,8 @@ export async function runServeHttp(engine: BrainEngine, options: ServeHttpOption
// ---------------------------------------------------------------------------
const clientCount = await sql`SELECT count(*)::int as count FROM oauth_clients`;
- const httpServer = app.listen(port, bind);
- // H2 mid-transition: a taken port must fail the start, never print the banner and keep
- // the brain lock while serving nothing (Bun runs the listen callback with listening=false
- // and emits 'error' to no listener). Wait for one outcome before announcing the server.
- const listenError = await new Promise<Error | null>(resolve => {
- if (httpServer.listening) return resolve(null);
- httpServer.once('listening', () => resolve(null));
- httpServer.once('error', (e: Error) => resolve(e));
- });
- if (listenError) {
- try { httpServer.close(); } catch { /* never listened */ }
- const { opError } = await import('../core/ops/contract.ts');
- throw opError('serve_port_in_use', `gbrain serve --http could not listen on ${bind}:${port}: ${listenError.message}`,
- 'Nothing was started and the brain is free again. Stop the process holding the port, or pass another --port (and point the harnesses at that URL).', {
- why: 'Another process (often an earlier gbrain serve --http) already listens on that address.',
- fix: { argv: ['gbrain', 'serve', '--http', '--bind', bind, '--port', String(port + 1)], consent: ['persistent_install'], actor: 'user', requires_exclusive: true,
- why: 'Starts the shared server on the next port; every harness must then use that URL.' },
- });
- }
- {
- console.error(`
+ const httpServer = await listenOrRefuse(app, port, bind);
+ console.error(`
╔══════════════════════════════════════════════════════╗
║ GBrain MCP Server v${VERSION.padEnd(37)}║
╠══════════════════════════════════════════════════════╣
@@ -890,7 +872,6 @@ ${bootstrapFromEnv
? '║ Admin Token: hidden (non-TTY log-leak guard) ║\n║ set $GBRAIN_ADMIN_BOOTSTRAP_TOKEN, or pass ║\n║ --print-admin-token on a trusted terminal. ║\n╚══════════════════════════════════════════════════════╝'
: `║ Admin Token (paste into /admin login): ║\n║ ${bootstrapToken.substring(0, 50)} ║\n║ ${bootstrapToken.substring(50).padEnd(50)} ║\n╚══════════════════════════════════════════════════════╝`}
`);
- }
// #4474: bind the resolve-IPC unix socket under --http too. This is the
// exact posture `gbrain bootstrap harness` targets — without the listener
diff --git a/src/core/remediation/run.ts b/src/core/remediation/run.ts
index ec8df8579b..01a25f5990 100644
--- a/src/core/remediation/run.ts
+++ b/src/core/remediation/run.ts
@@ -59,7 +59,23 @@ function planJobSteps(planned: RemediationStep[], manifest: { job_ids: string[]
};
}
-/** One submitted job, executed by an in-process worker until it is terminal (PGLite, no worker). */
+/**
+ * How a submitted step is awaited. PGLite has no background worker, and a
+ * Postgres queue may have none running: unless a registered worker serves the
+ * queue, the step runs in this process (as `jobs submit --follow` does)
+ * instead of waiting out its timeout for a worker that never comes.
+ */
+function stepWaiter(engine: BrainEngine, queue: InstanceType<typeof import('../minions/queue.ts').MinionQueue>) {
+ const worker = queueWorkerAlive('default');
+ const inline = engine.kind === 'pglite' ? worker !== true : worker === false;
+ return async (jobId: number, waitOpts: { pollMs: number; timeoutMs: number }) => {
+ if (inline) return runJobInline(engine, queue, jobId, waitOpts);
+ const { waitForCompletion } = await import('../minions/wait-for-completion.ts');
+ return waitForCompletion(queue, jobId, waitOpts);
+ };
+}
+
+/** One submitted job, executed by an in-process worker until it is terminal. */
async function runJobInline(
engine: BrainEngine,
queue: InstanceType<typeof import('../minions/queue.ts').MinionQueue>,
@@ -234,14 +250,9 @@ export async function runRemediation(
const repairResults: RepairStepResult[] = [];
const { MinionQueue } = await import('../minions/queue.ts');
- const { waitForCompletion } = await import('../minions/wait-for-completion.ts');
const isPGLite = engine.kind === 'pglite';
const queue = new MinionQueue(engine);
- // PGLite has no background worker, and a Postgres queue may have none running: unless a
- // registered worker serves the queue, run each submitted step in this process (as
- // `jobs submit --follow` does) instead of waiting out its timeout for a worker that never comes.
- const worker = queueWorkerAlive('default');
- const inlineWorker = isPGLite ? worker !== true : worker === false;
+ const waitStep = stepWaiter(engine, queue);
// A4 amended: install a BudgetTracker scope around the plan-step loop so
// any gateway.chat / embed / rerank inside a Minion handler (synthesize,
@@ -401,10 +412,7 @@ export async function runRemediation(
};
submitted.push(submittedResult);
- const waitOpts = { pollMs: isPGLite ? 250 : 1000, timeoutMs: (step.est_seconds + 60) * 1000 };
- const terminal = inlineWorker
- ? await runJobInline(engine, queue, job.id, waitOpts)
- : await waitForCompletion(queue, job.id, waitOpts);
+ const terminal = await waitStep(job.id, { pollMs: isPGLite ? 250 : 1000, timeoutMs: (step.est_seconds + 60) * 1000 });
submittedResult.status = terminal.status;
if (terminal.status !== 'completed') {
abortedIds.add(step.id);