Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(hooks): a serve-backstop context pack returns what it assembled and records degraded/server_budget (GBRA-95 row)

garrytan2da3b85fc5f8
diff --git a/src/commands/hook.ts b/src/commands/hook.ts
index 868b433a4d..174d844116 100644
--- a/src/commands/hook.ts
+++ b/src/commands/hook.ts
@@ -566,6 +566,7 @@ async function hookSessionStart(io: HookIo): Promise<number> {
serveNotReady = res.serveNotReady;
const pack = res.pack;
if (pack && !pack.ok && pack.error === 'source_mismatch' && outcome === 'ok') { outcome = 'degraded'; reason = 'source_mismatch'; } // #5941
+ if (pack?.ok && pack.degradedReason === 'server_budget' && outcome === 'ok') { outcome = 'degraded'; reason = 'server_budget'; }
if (pack?.ok && pack.block?.text) out.push(pack.block.text);
if (pack?.ok && pack.block?.core && process.env.GBRAIN_CORE !== '0') coreBox.core = pack.block.core;
else if (pack?.ok && !pack.block?.core) coreBox.reason = 'stale_serve_no_core';
@@ -1212,7 +1213,7 @@ async function hookUserPrompt(io: HookIo): Promise<number> {
// Context-pressure notice (pressure.ts) leads the block so the cap loop never trims it.
const pressure = transcriptPath && io.harness !== 'codex' ? claudeCodePressure(resp.block?.pressure, transcriptPath, sessionId) : null;
const text = [pressure?.notice, resp.block?.text].filter(Boolean).join('\n\n');
- if (!text) return { outcome: 'ok', reason: 'empty_block', turns: turns.length };
+ if (!text) return resp.degradedReason === 'server_budget' ? { outcome: 'degraded', reason: 'server_budget', turns: turns.length } : { outcome: 'ok', reason: 'empty_block', turns: turns.length };
// [ENG-1] The 10000-char harness cap applies to the WHOLE stdout payload;
// the block is budgeted ≤8KB server-side, but JSON escaping inflates, so
diff --git a/src/core/context/resolve-ipc.ts b/src/core/context/resolve-ipc.ts
index bbf19080d8..3f7727e3ec 100644
--- a/src/core/context/resolve-ipc.ts
+++ b/src/core/context/resolve-ipc.ts
@@ -270,7 +270,11 @@ export interface ContextPackResponse {
export type ResolveHandler = (req: ResolveRequest) => Promise<PointerBlock | null>;
export type TurnContextHandler = (req: TurnContextRequest) => Promise<TurnContextResult | null>;
-export type ContextPackHandler = (req: ContextPackRequest) => Promise<TurnContextResult | null>;
+/**
+ * `progress.assembled` is set by a handler once its pack is assembled; the transport's backstop returns that pack
+ * (marked `server_budget`) instead of nothing when the handler's later work (core, session state, brief) runs past it.
+ */
+export type ContextPackHandler = (req: ContextPackRequest, progress?: { assembled?: TurnContextResult | null }) => Promise<TurnContextResult | null>;
export type SyncStartIpcHandler = (req: SyncStartRequest) => SyncStartResponse | Promise<SyncStartResponse>;
export type SyncStatusIpcHandler = (req: SyncStatusRequest) => SyncStatusResponse | Promise<SyncStatusResponse>;
@@ -1006,9 +1010,10 @@ async function handleContextPack(
const t = setTimeout(() => r('__budget__'), CONTEXT_PACK_SERVER_BUDGET_MS + 200);
t.unref?.();
});
- const result = await Promise.race([handlers.context_pack(req), budget]);
+ const progress: { assembled?: TurnContextResult | null } = {};
+ const result = await Promise.race([handlers.context_pack(req, progress), budget]);
if (result === '__budget__') {
- return { ok: true, protocol: 2, block: null, degradedReason: 'server_budget' };
+ return { ok: true, protocol: 2, block: progress.assembled ?? null, degradedReason: 'server_budget' };
}
return {
ok: true,
diff --git a/src/mcp/context-pack-handler.ts b/src/mcp/context-pack-handler.ts
index 1e02e62cbc..4c8f8999f7 100644
--- a/src/mcp/context-pack-handler.ts
+++ b/src/mcp/context-pack-handler.ts
@@ -69,7 +69,7 @@ export function makeContextPackIpcHandler(
engine: BrainEngine,
defaultSource: string,
): ContextPackHandler {
- return async (req) => {
+ return async (req, progress) => {
const startedAt = Date.now();
const sessionId =
typeof req.sessionId === 'string' && req.sessionId.trim() ? req.sessionId : null;
@@ -201,6 +201,8 @@ export function makeContextPackIpcHandler(
? { checkpointLinks: (await getCheckpointManifest(engine, sessionSource, null, sessionId)) ?? [] }
: {}),
});
+ // The transport's backstop returns this pack if the work below runs past it (core lands on it when it arrives).
+ if (progress) progress.assembled = result;
const core = typeof req.trigger === 'string' && req.trigger.startsWith('session-start') ? await coreForSession(engine, sessionSource) : null;
if (core) result.core = core;
if (sessionId) {
diff --git a/test/ambient-recall-hooks.serial.test.ts b/test/ambient-recall-hooks.serial.test.ts
index 074e0a435f..a7eb1c9df5 100644
--- a/test/ambient-recall-hooks.serial.test.ts
+++ b/test/ambient-recall-hooks.serial.test.ts
@@ -187,6 +187,27 @@ describe('context_pack over IPC', () => {
expect(resp.degradedReason).toBe('server_budget');
}, 10_000);
+ test('a pack assembled before the backstop is returned with server_budget when later handler work runs past it', async () => {
+ const dataDir = join(tmp, 'data');
+ mkdirSync(dataDir, { recursive: true });
+ const secret = ensureIpcSecret(dataDir);
+ const server = await startResolveIpcServer(
+ resolveSocketPath(dataDir),
+ {
+ resolve: async () => null,
+ context_pack: async (_req, progress) => {
+ if (progress) progress.assembled = { text: 'ASSEMBLED-PACK', pointers: [], factsCount: 0 };
+ await new Promise((r) => setTimeout(r, 60_000));
+ return { text: 'late', pointers: [], factsCount: 0 };
+ },
+ },
+ { secret },
+ );
+ servers.push(server!);
+ const resp = await requestContextPack(resolveSocketPath(dataDir), { secret }, { timeoutMs: 5000 }) as ContextPackResponse;
+ expect({ ok: resp.ok, text: resp.block?.text, degradedReason: resp.degradedReason }).toEqual({ ok: true, text: 'ASSEMBLED-PACK', degradedReason: 'server_budget' });
+ }, 10_000);
+
test('handler throw → ok:false error, connection survives', async () => {
const dataDir = join(tmp, 'data');
mkdirSync(dataDir, { recursive: true });
diff --git a/test/hook-command.serial.test.ts b/test/hook-command.serial.test.ts
index 954e377ba4..fa788634a9 100644
--- a/test/hook-command.serial.test.ts
+++ b/test/hook-command.serial.test.ts
@@ -103,6 +103,8 @@ async function startServer(opts: {
secretOverride?: string;
boundSourceId?: string;
onRequest?: (req: TurnContextRequest) => void;
+ /** Answer only after this long, so the serve's backstop answers first. */
+ hangMs?: number;
}): Promise<void> {
mkdirSync(opts.dataDir, { recursive: true });
const secret = opts.secretOverride ?? ensureIpcSecret(opts.dataDir);
@@ -113,6 +115,7 @@ async function startServer(opts: {
resolve: async () => null,
turn_context: async (req) => {
opts.onRequest?.(req);
+ if (opts.hangMs) await new Promise((r) => setTimeout(r, opts.hangMs));
if (opts.blockText == null) return null;
return { text: opts.blockText, pointers: [], factsCount: 0 };
},
@@ -197,6 +200,19 @@ describe('user-prompt source routing (#5941)', () => {
});
});
+describe('serve backstop (GBRA-95 row)', () => {
+ test('a turn_context cut short by the serve backstop records a degraded server_budget heartbeat, never a silent ok', async () => {
+ const dataDir = join(tmp, 'data');
+ writePgliteConfig(dataDir);
+ await startServer({ dataDir, blockText: 'LATE-CONTEXT', hangMs: 3000 });
+ const out = collectStdout();
+ await runHook(['user-prompt', '--harness', 'codex'], { ...out.io, userPromptDeadlineMs: 2000, stdin: JSON.stringify({ prompt: 'hello Acme', cwd: tmp }) });
+ expect(out.get()).not.toContain('LATE-CONTEXT');
+ const hb = await lastHeartbeat();
+ expect({ outcome: hb?.outcome, reason: hb?.reason }).toEqual({ outcome: 'degraded', reason: 'server_budget' });
+ }, 10_000);
+});
+
describe('dispatch', () => {
test('GBRAIN_HOOKS=0 short-circuits every event: exit 0, no output, no heartbeat', async () => {
process.env.GBRAIN_HOOKS = '0';