Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix: pre-landing review fixes

garrytan038fceeaaaef
diff --git a/src/cli/main.ts b/src/cli/main.ts
index 90242eb225..3f0b2324a1 100755
--- a/src/cli/main.ts
+++ b/src/cli/main.ts
@@ -850,6 +850,12 @@ async function runThinClientRouted(
// Awaited delivery (#3423) — same contract as the local-engine path.
if (output) await writeStdoutFinal(output);
if (stampText) process.stderr.write(stampText);
+ // GST-1387: an in-band failure (a remember batch with a failed item) exits 1 here too, as on the local path.
+ if (typeof result === 'object' && result !== null && !Array.isArray(result) && (result as { status?: unknown }).status === 'error') {
+ const detail = (result as { message?: unknown; error?: unknown }).message ?? (result as { error?: unknown }).error;
+ console.error(`gbrain ${command}: operation reported status 'error'` + (typeof detail === 'string' && detail ? ` — ${detail}` : '') + '.');
+ setCliExitVerdict(1);
+ }
markEntityMiss(op.name, result);
maybePrintConceptNudge(op.name, params);
} catch (e: unknown) {
diff --git a/src/core/mcp-client.ts b/src/core/mcp-client.ts
index b6dfe6e092..baf3b290ba 100644
--- a/src/core/mcp-client.ts
+++ b/src/core/mcp-client.ts
@@ -179,6 +179,10 @@ export function extractToolErrorCode(message: string): string | undefined {
}
/** Keep only validated public receipt fields from a tool's JSON error body. */
+function isBatchErrorBody(text: string): boolean {
+ try { const body = JSON.parse(text) as { items?: unknown; status?: unknown }; return Array.isArray(body?.items) && body.status === 'error'; } catch { return false; }
+}
+
export function extractToolErrorDetail(message: string): RemoteMcpErrorDetail {
const code = extractToolErrorCode(message);
const detail: RemoteMcpErrorDetail = code ? { code } : {};
@@ -430,6 +434,8 @@ export async function callRemoteTool(
// block from a newer server never joins the body.
const first = Array.isArray(res.content) ? (res.content[0] as { text?: unknown } | undefined) : undefined;
const message = typeof first?.text === 'string' ? first.text : 'unknown tool error';
+ // GST-1387: a remember batch with a failed item is an error whose body keeps every item's receipt; the caller renders it.
+ if (isBatchErrorBody(message)) return res;
// v0.31.1: extract structured error code (e.g. 'missing_scope') so
// the dispatcher can produce a pinpoint hint instead of a generic
// "tool error" message.
diff --git a/src/core/persistence/journal.ts b/src/core/persistence/journal.ts
index 8e7d1972f3..566d8a1e61 100644
--- a/src/core/persistence/journal.ts
+++ b/src/core/persistence/journal.ts
@@ -299,7 +299,7 @@ async function prepareAdmission(engine: BrainEngine, input: WriteAdmission, over
const [, , , , , counters, topology, prior] = await pipelined(tx, [
() => assertGraduationAdmission(tx),
async () => assertMutationProtocol({ target_kind: input.targetKind, protocol_version: input.protocolVersion }),
- async () => { if (input.worktreeId) await assertWorktreeAdmission(tx, input); },
+ async () => { if (input.worktreeId) await assertWorktreeAdmission(tx, input, true); },
// Source membership is locked before principal/counter/request guards. A
// deleted/recreated source never receives work accepted for its old identity.
async () => {
@@ -590,7 +590,7 @@ export async function chargePreparationAttempt(engine: SqlEngine, row: WriteRequ
* binding (#6007: both read in one statement after the lock; the fence is
* judged first, as before).
*/
-async function assertWorktreeAdmission(tx: BrainEngine, input: WriteAdmission): Promise<void> {
+async function assertWorktreeAdmission(tx: BrainEngine, input: WriteAdmission, replayable = false): Promise<void> {
// Sent together: the server takes the share lock before it reads the fence and the binding.
const [[worktree], [state]] = await pipelined(tx, [
() => tx.executeRaw<{ state: string; owner_epoch: string }>('SELECT state,owner_epoch::text AS owner_epoch FROM persistence_worktrees WHERE id=$1::uuid FOR SHARE', [input.worktreeId]),
@@ -602,14 +602,14 @@ async function assertWorktreeAdmission(tx: BrainEngine, input: WriteAdmission):
[input.sourceId, input.sourceIncarnation, input.worktreeId, input.topologyGeneration]),
]) as [Array<{ state: string; owner_epoch: string }>, Array<{ refresh: { id: string; state: string; source_ids: string[] } | string | null; bound: boolean }>];
const refresh = typeof state?.refresh === 'string' ? JSON.parse(state.refresh) as { id: string; state: string; source_ids: string[] } : state?.refresh ?? null;
- if (refresh) await assertWorktreeNotRefreshing(tx, input, refresh);
+ if (refresh) await assertWorktreeNotRefreshing(tx, input, refresh, replayable);
// #6741 C: a background producer never takes a permanent request id against a worktree in recovery (a draining owner still replays).
if (worktree?.state === 'recovering' && resolveAdmissionOrigin(input.origin) === 'background') throw backgroundWorktreeInactive(input.sourceId, worktree.state, ownerStatusFix(input.sourceId));
if (!state?.bound || input.ownerEpoch != null && worktree && worktree.owner_epoch !== String(input.ownerEpoch)) throw opError('source_changed', 'The source binding changed during admission.',
`Source ${input.sourceId}'s worktree binding changed (a claim, transfer or lifecycle change) while this write was being admitted, so nothing was accepted. Check the owner with the command in fix, then submit the write again; reusing the same request_id is safe because nothing was recorded.`,
{ fix: ownerStatusFix(input.sourceId) });
}
-async function assertWorktreeNotRefreshing(tx: BrainEngine, input: WriteAdmission, refresh: { id: string; state: string; source_ids: string[] }): Promise<void> {
+async function assertWorktreeNotRefreshing(tx: BrainEngine, input: WriteAdmission, refresh: { id: string; state: string; source_ids: string[] }, replayable: boolean): Promise<void> {
const managedSync = input.operation === 'submit_job' && String(input.intent.kind ?? '').startsWith('managed_sync_');
if (refresh.state === 'syncing' && managedSync) return;
if (refresh.state === 'syncing') {
@@ -624,8 +624,9 @@ async function assertWorktreeNotRefreshing(tx: BrainEngine, input: WriteAdmissio
const error = catalogueError('worktree_refreshing',
`Source ${input.sourceId}'s checkout is being fast-forwarded by refresh ${refresh.id} (${refresh.state}); this write was not journaled.`,
`Retry the same request_id after retry_after_ms: 1000. Check progress with gbrain sources writer status ${input.sourceId}.`);
- // A replay of a request already accepted (its acknowledgement lost before the fence) reconciles to its receipt instead.
- if (input.requestId && await getWriteRequest(tx, input.principal, input.requestId)) return;
+ // A single write's replay of a request already accepted (its acknowledgement lost before the fence) reconciles to its
+ // receipt instead; a group admission never bypasses, since its other items may be new.
+ if (replayable && input.requestId && await getWriteRequest(tx, input.principal, input.requestId)) return;
error.detail = 'retry_after_ms=1000';
error.retryable = true;
// GST-1387: nothing was recorded, so the same call is retried after the delay (actor provider renders next: wait).
diff --git a/src/core/persistence/provider.ts b/src/core/persistence/provider.ts
index 728076cb2a..441362768e 100644
--- a/src/core/persistence/provider.ts
+++ b/src/core/persistence/provider.ts
@@ -90,6 +90,8 @@ export async function createPersistenceIpcProvider(engine: BrainEngine, config:
});
const body = JSON.parse(result.content[0].text) as Record<string, unknown>;
if (!result.isError) return body;
+ // GST-1387: a remember batch with a failed item keeps every item's receipt; the CLI exits 1 on its status.
+ if (Array.isArray(body.items) && body.status === 'error') return body;
const error = new OperationError(typeof body.error === 'string' ? body.error : 'unavailable',
typeof body.message === 'string' ? body.message : 'The local operation could not complete.',
typeof body.suggestion === 'string' ? body.suggestion : undefined);
diff --git a/src/core/remember-batch.ts b/src/core/remember-batch.ts
index be807ebf93..e6b5aa2d8b 100644
--- a/src/core/remember-batch.ts
+++ b/src/core/remember-batch.ts
@@ -123,7 +123,7 @@ export async function runRememberBatch(ctx: OperationContext, p: Record<string,
// GST-1387: a batch that saved nothing is a refusal on every surface (CLI exit non-zero, MCP isError), never a success
// envelope; its first item's error keeps that item's code and fix. An item with a receipt (accepted, or its outcome
// unknown) keeps the per-item envelope so its child request_id is never lost.
- if (failures.length && failed === results.length && failures.every(f => !f.error.writeRequest)) {
+ if (failures.length && failed === results.length && failures.every(f => !f.error.writeRequest && f.error.writeError !== 'write_outcome_unknown')) {
const [{ index, error }] = failures as [{ index: number; error: OperationError }];
error.message = `items[${index}]: ${error.message} None of the ${results.length} item(s) was saved.`;
throw error;
diff --git a/src/mcp/dispatch.ts b/src/mcp/dispatch.ts
index cebdc43153..b5439d279b 100644
--- a/src/mcp/dispatch.ts
+++ b/src/mcp/dispatch.ts
@@ -1295,13 +1295,13 @@ async function dispatchResolvedCall(
} catch { /* a pointer, never a failure */ }
}
maybeBackupNotice(notices, opts);
- if (opts.transport === 'stdio' && opts.remote !== false) { const up = takePostUpgradeMcpNotice(); if (up) notices.push(up); } // F7
+ // GST-1387: a remember batch with a failed item is an MCP error; its body keeps every item's receipt.
+ const batchError = name === 'remember' && typeof result === 'object' && result !== null && (result as { status?: unknown }).status === 'error' && Array.isArray((result as { items?: unknown }).items);
+ if (opts.transport === 'stdio' && opts.remote !== false && !batchError) { const up = takePostUpgradeMcpNotice(); if (up) notices.push(up); } // F7
if (opts.transport === 'stdio' && opts.remote !== false) notices.push(...await mcpOnboardingNotices({ engine, op: name, result, meta: responseMeta, config: ctx.config, render: dispatchRenderContext(opts) }));
- if (opts.transport === 'stdio' && opts.remote !== false) { const drain = takeFactsDrainNotice(); if (drain) notices.push(drain); } // Lane D facts drain
+ if (opts.transport === 'stdio' && opts.remote !== false && !batchError) { const drain = takeFactsDrainNotice(); if (drain) notices.push(drain); } // Lane D facts drain
notices.push(...await sessionSafetyNotices(engine, opts, ctx.config));
notices.push(...await grantBlockedNotices(engine, opts, false));
- // GST-1387: a remember batch with a failed item is an MCP error; its body keeps every item's receipt.
- const batchError = name === 'remember' && typeof result === 'object' && result !== null && (result as { status?: unknown }).status === 'error' && Array.isArray((result as { items?: unknown }).items);
const out: ToolResult = batchError ? toolErrorResult(result as never) : toolResultWithNotices(result, admitNotices(notices, opts), dispatchRenderContext(opts));
if (evidenceBlocks.length > 0) out.content.splice(1, 0, ...evidenceBlocks.map(text => ({ type: 'text' as const, text })));
if (opts.transport === 'stdio') {
diff --git a/test/agent-error-surfaces.serial.test.ts b/test/agent-error-surfaces.serial.test.ts
index 1409d37131..143931cf68 100644
--- a/test/agent-error-surfaces.serial.test.ts
+++ b/test/agent-error-surfaces.serial.test.ts
@@ -78,7 +78,7 @@ import { CredentialError } from '../src/core/creds/errors.ts';
import { BudgetTracker } from '../src/core/budget/budget-tracker.ts';
import { catalogueError } from '../src/core/error-catalogue.ts';
import { SourceTargetError } from '../src/core/source-resolver.ts';
-import { callRemoteTool, RemoteMcpError } from '../src/core/mcp-client.ts';
+import { callRemoteTool, RemoteMcpError, unpackToolResult } from '../src/core/mcp-client.ts';
import { dispatchToolCall } from '../src/mcp/dispatch.ts';
import { keylessBrainEnv } from './helpers/provider-env.ts';
import {
@@ -474,3 +474,19 @@ describe('a real OperationError built with opError round-trips the thin client u
expect(JSON.parse(renderCliError(remote, { json: true, command: 'h3', tty: false }).stdout!)).toMatchObject({ error: 'invalid_params', code: 'not_found' });
}, 60_000);
});
+
+describe('#8621: a partly failed remember batch over HTTP and the thin client', () => {
+ test('is an MCP error whose body keeps every item receipt; the thin client returns it for the CLI to render', async () => {
+ const batch = { status: 'error', error: 'invalid_params', code: 'invalid_params', protocol_version: 1,
+ message: '1 of 2 item(s) failed (first: items[0] invalid_params); see items[].error. Items not marked failed are stored.',
+ items: [{ index: 0, request_id: 'r0', status: 'failed', error: { code: 'invalid_params', message: 'refused' } }, { index: 1, request_id: 'r1', status: 'inserted', id: 7 }],
+ saved: 1, failed: 1, partial: true };
+ const handler: Operation['handler'] = async () => batch;
+ const args = { items: ['alice-example likes tea', 'alice-example likes jazz'], provenance: 'test' };
+ const http = await withOpHandler('remember', handler, () => callTool(serve.base, adminToken, 'remember', args));
+ expect(http.isError).toBe(true);
+ expect(JSON.parse(http.content[0]!.text!)).toMatchObject({ status: 'error', saved: 1, items: [{ status: 'failed' }, { status: 'inserted', id: 7 }] });
+ const remote = await withOpHandler('remember', handler, () => callRemoteTool(thinClientConfig(serve, oauth), 'remember', args, { timeoutMs: 30_000 }));
+ expect(unpackToolResult(remote)).toMatchObject({ status: 'error', saved: 1, items: [{ status: 'failed' }, { status: 'inserted', id: 7 }] });
+ }, 60_000);
+});
diff --git a/test/mcp-notice-channels.test.ts b/test/mcp-notice-channels.test.ts
index 71c9a5d6f2..de5c9db850 100644
--- a/test/mcp-notice-channels.test.ts
+++ b/test/mcp-notice-channels.test.ts
@@ -268,6 +268,35 @@ describe('F7 coaching reaches agents', () => {
__resetPostUpgradeNoticeForTests();
}
});
+
+ test('#8621: a partly failed remember batch (an MCP error) leaves the one-shot post-upgrade notice for the next call', async () => {
+ const { mkdtempSync, mkdirSync, writeFileSync, rmSync } = await import('node:fs');
+ const { join } = await import('node:path');
+ const { tmpdir } = await import('node:os');
+ const { VERSION } = await import('../src/version.ts');
+ const { takePostUpgradeMcpNotice, __resetPostUpgradeNoticeForTests } = await import('../src/core/post-upgrade-notice.ts');
+ const { operations } = await import('../src/core/operations.ts');
+ const op = operations.find(o => o.name === 'remember')! as { handler: unknown };
+ const original = op.handler;
+ const home = mkdtempSync(join(tmpdir(), 'gbrain-postup-batch-'));
+ try {
+ mkdirSync(join(home, '.gbrain'), { recursive: true });
+ writeFileSync(join(home, '.gbrain', 'upgrade-state.json'), JSON.stringify({ last_upgrade: { from: '0.0.1.0', to: VERSION } }));
+ await withEnv({ HOME: home, GBRAIN_HOME: home, GBRAIN_NO_ONBOARD_NUDGE: undefined }, async () => {
+ __resetPostUpgradeNoticeForTests();
+ op.handler = async () => ({ status: 'error', error: 'invalid_params', code: 'invalid_params', message: '1 of 2 item(s) failed.',
+ items: [{ index: 0, request_id: 'r0', status: 'failed', error: { code: 'invalid_params', message: 'refused' } }, { index: 1, request_id: 'r1', status: 'inserted', id: 7 }],
+ saved: 1, failed: 1, partial: true });
+ const res = await dispatchToolCall(engine as any, 'remember', { items: ['alice-example likes tea', 'alice-example likes jazz'], provenance: 'test' }, { remote: true, transport: 'stdio', sourceId: 'default' });
+ expect(res.isError).toBe(true);
+ expect(takePostUpgradeMcpNotice()?.code).toBe('post_upgrade');
+ });
+ } finally {
+ op.handler = original;
+ rmSync(home, { recursive: true, force: true });
+ __resetPostUpgradeNoticeForTests();
+ }
+ });
});
describe('onboarding notices on the stdio channel', () => {
diff --git a/test/pending-write-exit-owner.test.ts b/test/pending-write-exit-owner.test.ts
index f4ab0fcc3f..b5b15bf7d3 100644
--- a/test/pending-write-exit-owner.test.ts
+++ b/test/pending-write-exit-owner.test.ts
@@ -96,6 +96,30 @@ describe('paused writers and the CLI exit contract', () => {
});
}, 180_000);
+ test('#8621 resident owner: a partly failed remember batch exits 1 and keeps every item receipt', async () => {
+ await withEnv({ GBRAIN_HOME: dir, GBRAIN_BRAIN_ID: 'host', GBRAIN_SOURCE: undefined, DATABASE_URL: undefined, GBRAIN_DATABASE_URL: undefined }, async () => {
+ const provider = await createPersistenceIpcProvider(engine, config);
+ const binding = await startPersistenceIpcServer(persistenceSocketPathForConfig(config)!, provider);
+ try {
+ const claim = { fact: 'acme-example signed the pilot', provenance: 'call notes' };
+ const saved = await cli(['remember', '--items', JSON.stringify([claim]), '--json']);
+ expect({ code: saved.code, stderr: saved.stderr }).toMatchObject({ code: 0 });
+ const id = JSON.parse(saved.stdout).items[0].id;
+ const forgot = await cli(['call', 'forget', JSON.stringify({ id, reason: 'withdrawn for the test' })]);
+ expect({ code: forgot.code, stderr: forgot.stderr }).toMatchObject({ code: 0 });
+ const batch = await cli(['remember', '--items', JSON.stringify([claim, { fact: 'acme-example opened a second office', provenance: 'call notes' }]), '--json']);
+ expect({ code: batch.code }).toMatchObject({ code: 1 });
+ const body = JSON.parse(batch.stdout);
+ expect(body).toMatchObject({ status: 'error', saved: 1, failed: 1, partial: true });
+ expect(body.items[0].status).toBe('failed');
+ expect(body.items[1].id).toBeDefined();
+ } finally {
+ if (binding) { const closed = once(binding.server, 'close'); binding.close(); await closed; }
+ await disposePersistenceConsumer(engine);
+ }
+ });
+ }, 180_000);
+
test('direct path: the CLI that opens the brain itself waits its --wait, then exits 10 or 0', async () => {
await withEnv({ GBRAIN_HOME: dir, GBRAIN_BRAIN_ID: 'host' }, async () => {
const lock = await holdWorktree();
diff --git a/test/remember-batch.test.ts b/test/remember-batch.test.ts
index 3cccb2ccd4..e808f781b6 100644
--- a/test/remember-batch.test.ts
+++ b/test/remember-batch.test.ts
@@ -111,7 +111,7 @@ describe('remember items[] batch', () => {
const handler = async (c: OperationContext, p: Record<string, unknown>) => {
if (p.fact !== 'lost' || c.dryRun) return base(c, p);
const e = ve('unavailable', 'The write outcome is unknown.', 'Poll get_write_request.');
- Object.assign(e, { writeError: 'write_outcome_unknown', writeRequest: { request_id: p.request_id, state: 'unknown' } });
+ Object.assign(e, { writeError: 'write_outcome_unknown' });
throw e;
};
const root = '22222222-2222-4222-8222-222222222222';
diff --git a/test/write-refusal-refresh-fence-8621.test.ts b/test/write-refusal-refresh-fence-8621.test.ts
index 606d08923a..155c362b1b 100644
--- a/test/write-refusal-refresh-fence-8621.test.ts
+++ b/test/write-refusal-refresh-fence-8621.test.ts
@@ -23,6 +23,7 @@ import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
import { refreshWorktree } from '../src/core/persistence/worktree-refresh.ts';
import { submitPageMutation } from '../src/core/persistence/page-mutations.ts';
import { admitWrite, type WriteAdmission } from '../src/core/persistence/journal.ts';
+import { admitBatch } from '../src/core/persistence/page-batch.ts';
import { _setRefreshFenceWaitForTests } from '../src/core/persistence/admission-retry.ts';
import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
import { testBackends } from './helpers/test-backends.ts';
@@ -137,6 +138,29 @@ test('an admission retried after its accepted commit lost its ack reconciles to
}));
}), 120_000);
+test('a page group whose first item replays an accepted request but whose next item is new stays fenced', () => each(async f => {
+ _setRefreshFenceWaitForTests(0);
+ const requestId = crypto.randomUUID();
+ const content = page('Accepted', 'accepted before the fence');
+ await f.put(f.alpha, 'notes/accepted', content, requestId);
+ const [row] = await f.engine.executeRaw<Record<string, any>>('SELECT * FROM persistence_requests WHERE request_id=$1::uuid', [requestId]);
+ const [src] = await f.engine.executeRaw<{ incarnation: string }>('SELECT incarnation FROM sources WHERE id=$1', [f.alpha]);
+ const [bind] = await f.engine.executeRaw<{ g: string }>('SELECT topology_generation::text AS g FROM persistence_source_bindings WHERE source_id=$1', [f.alpha]);
+ const base = { principal: { kind: row!.principal_kind, id: row!.principal_id }, operation: 'put_page', sourceId: f.alpha, sourceIncarnation: src!.incarnation,
+ worktreeId: f.worktreeId, topologyGeneration: bind!.g, authority: row!.authority, origin: 'interactive' as const };
+ const fresh = page('Fresh', 'new during the fence');
+ const group: WriteAdmission[] = [
+ { ...base, slug: row!.slug, requestId, callerIntent: { slug: 'notes/accepted', content }, intent: row!.intent },
+ { ...base, slug: 'notes/fresh', requestId: crypto.randomUUID(), callerIntent: { slug: 'notes/fresh', content: fresh }, intent: { ...row!.intent, content: fresh } },
+ ];
+ await (await duringRefresh(f, async () => {
+ const before = await f.requestCount();
+ const error = await admitBatch({ ...f.ctx(f.alpha), admissionOrigin: 'interactive' }, crypto.randomUUID(), group).then(() => null, e => e as { code?: string });
+ expect(error?.code).toBe('worktree_refreshing');
+ expect(await f.requestCount()).toBe(before);
+ }));
+}), 120_000);
+
test('an interactive write waits out a short refresh fence and commits once the refresh finishes', () => each(async f => {
let write: Promise<Record<string, unknown>> | undefined;
const refresh = await duringRefresh(f, async release => {