Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

Wave B PR3 lane 3c: append goes direct within the connection part cap, upload only above it; cutter tests check raw frames

garrytan7fbfd2cf79f2
diff --git a/src/cli/commands/append.ts b/src/cli/commands/append.ts
index 08aeba60b5..e36fe18ed4 100644
--- a/src/cli/commands/append.ts
+++ b/src/cli/commands/append.ts
@@ -5,8 +5,10 @@
* gbrain put <slug> --file PATH replace or create a page from a file
*
* `append` calls append_page with a generated request_id (`--request-id`
- * replays one); text whose append_page request would not fit the smallest
- * transport cap goes through an upload session with mode `append`.
+ * replays one) whenever the call's encoded frame fits the connection's part
+ * cap (spec 6.2): 4 MiB less 4 KiB locally, on a remote brain the cap its
+ * begin_page_upload reports. Only a larger append goes through an upload
+ * session with mode `append`.
* `put --file` (and `capture --file`) send one request while the page fits
* it (the trusted local CLI: the page ceiling; a thin client: the smallest
* transport cap). A larger file on the trusted local CLI streams through the
@@ -40,6 +42,8 @@ import { callRemoteTool, stringUploadBody, toolCallFrameBytes, unpackToolResult,
/** The smallest inbound cap any transport has (legacy HTTP, 1 MiB) less the 4 KiB envelope reserve: a request this size reaches every brain. */
export const DIRECT_FRAME_MAX_BYTES = 1024 * 1024 - 4096;
+/** The part cap of a local or stdio connection (4 MiB less the 4 KiB reserve), the largest frame any connection takes in one call. */
+export const LOCAL_FRAME_MAX_BYTES = 4 * 1024 * 1024 - 4096;
/** Where a CLI write goes, plus the transient-failure test the upload driver resumes on. */
export interface PageWriteCaller {
@@ -172,8 +176,10 @@ Options:
--json Print the receipt as JSON
--help, -h Show this help
-Text over one request goes through an upload session (begin, parts, commit)
-and appends at the end of the page with region and separator auto.
+Text whose call is over the connection's part cap (4 MiB less 4 KiB locally;
+on a remote brain the cap it reports) goes through an upload session (begin,
+parts, commit), which appends at the end of the page with region and
+separator auto; --expect-tail, --region and --separator are refused there.
Examples:
echo "- 14:02 the next message" | gbrain append conversations/sessions/2026-10-19-standup
@@ -263,19 +269,31 @@ export async function run(args: string[], ctx: CliDispatchContext): Promise<void
...(parsed.region ? { region: parsed.region } : {}),
...(parsed.separator ? { separator: parsed.separator } : {}),
};
+ const frame = toolCallFrameBytes('append_page', params);
+ const begin = { slug: parsed.slug, mode: 'append', request_id: requestId, ...(parsed.expected_revision ? { expected_revision: parsed.expected_revision } : {}) };
+ const body = stringUploadBody(text);
+ let cap = caller.thin ? DIRECT_FRAME_MAX_BYTES : LOCAL_FRAME_MAX_BYTES;
+ let begun: Record<string, unknown> | undefined;
+ if (frame > cap && caller.thin && frame <= LOCAL_FRAME_MAX_BYTES) {
+ begun = await caller.call('begin_page_upload', { ...begin, total_bytes: body.bytes, sha256: body.sha256 });
+ cap = Number(begun.part_max_frame_bytes);
+ if (frame <= cap) {
+ await caller.call('abort_page_upload', { upload_id: begun.upload_id });
+ begun = undefined;
+ }
+ }
let result: Record<string, unknown>;
- if (toolCallFrameBytes('append_page', params) <= DIRECT_FRAME_MAX_BYTES) {
+ if (frame <= cap) {
result = await caller.call('append_page', params);
} else {
const unsupported = (['expected_tail_sha256', 'region', 'separator'] as const).filter(key => parsed[key] !== undefined);
if (unsupported.length) {
- throw usageError(`${unsupported.map(key => ({ expected_tail_sha256: '--expect-tail', region: '--region', separator: '--separator' })[key]).join(', ')} apply only to an append that fits one request (about ${DIRECT_FRAME_MAX_BYTES} bytes of JSON).`,
- 'A larger append goes through an upload session, which appends at the end with region and separator auto. Drop those flags, or split the text into appends under one request.');
+ if (begun) await caller.call('abort_page_upload', { upload_id: begun.upload_id }).catch(() => undefined);
+ throw usageError(`${unsupported.map(key => ({ expected_tail_sha256: '--expect-tail', region: '--region', separator: '--separator' })[key]).join(', ')} apply only to an append whose call fits this connection's ${cap}-byte part cap; this one is ${frame} bytes.`,
+ 'A larger append goes through an upload session, which appends at the end with region and separator auto and cannot check the tail. Drop those flags, or split the text into smaller appends.');
}
- result = await uploadPageBody(caller.call, {
- slug: parsed.slug, mode: 'append', request_id: requestId,
- ...(parsed.expected_revision ? { expected_revision: parsed.expected_revision } : {}),
- }, stringUploadBody(text), { transient: caller.transient, wait_ms: Math.min(currentCliWriteWait().waitMs, 30_000) });
+ result = await uploadPageBody(caller.call, begin, body,
+ { transient: caller.transient, wait_ms: Math.min(currentCliWriteWait().waitMs, 30_000), ...(begun ? { begun } : {}) });
}
await printAppendReceipt(result, parsed.json);
} catch (error) {
diff --git a/src/core/mcp-client.ts b/src/core/mcp-client.ts
index 7084bd5874..8b6129eff5 100644
--- a/src/core/mcp-client.ts
+++ b/src/core/mcp-client.ts
@@ -654,6 +654,8 @@ export interface UploadPageOptions {
retries?: number;
/** commit_page_upload's wait_ms. */
wait_ms?: number;
+ /** begin_page_upload's reply when the caller already began the session (with this body's total_bytes and sha256). */
+ begun?: Record<string, unknown>;
}
/** A body held as one string. */
@@ -683,7 +685,7 @@ export async function uploadPageBody(call: UploadToolCall, begin: Record<string,
try { return await fn(); } catch (error) { if (attempt >= retries || !transient(error)) throw error; }
}
};
- const session = await retry(() => call('begin_page_upload', { ...begin, total_bytes: body.bytes, sha256: body.sha256 }));
+ const session = opts.begun ?? await retry(() => call('begin_page_upload', { ...begin, total_bytes: body.bytes, sha256: body.sha256 }));
const uploadId = String(session.upload_id);
const maxFrame = Number(session.part_max_frame_bytes);
let part = Number(session.next_part);
diff --git a/test/cli-page-writes.test.ts b/test/cli-page-writes.test.ts
index 843c689812..a4176f1a43 100644
--- a/test/cli-page-writes.test.ts
+++ b/test/cli-page-writes.test.ts
@@ -133,18 +133,53 @@ for (const backend of testBackends()) {
expect(region.stderr).toContain('--region must be one of: auto, truth, timeline');
}, 60_000);
- test('append over one request goes through an upload session and lands whole', async () => {
- await cli(['put', 'notes/big-append', '--file', file('big-append.md', '# Big append\n\nstart\n')]);
+ const tailOf = async (slug: string) => {
+ const read = await cli(['get', slug, '--body', 'none', '--json']);
+ expect(read.code, read.stderr).toBe(0);
+ return /"tail_sha256":\s*"([0-9a-f]{64})"/.exec(read.stdout)![1]!;
+ };
+ const lines = (bytes: number) => {
const line = `- ${ESCAPE_HEAVY} message\n`;
- const text = line.repeat(Math.ceil((1.5 * 1024 * 1024) / Buffer.byteLength(line)));
- const appended = await cli(['append', 'notes/big-append', '--file', file('big-append-text.md', text), '--json']);
+ return line.repeat(Math.ceil(bytes / Buffer.byteLength(line)));
+ };
+
+ test('a 2 MiB local append is one direct append_page, with no upload session, and honours --expect-tail', async () => {
+ await cli(['put', 'notes/big-append', '--file', file('big-append.md', '# Big append\n\nstart\n')]);
+ const before = await uploads();
+ const tail = await tailOf('notes/big-append');
+ const text = lines(2 * 1024 * 1024);
+ const path = file('big-append-text.md', text);
+ const stale = await cli(['append', 'notes/big-append', '--file', path, '--expect-tail', 'f'.repeat(64)]);
+ expect(stale.code).not.toBe(0);
+ expect(stale.stderr).toContain('tail_changed');
+ expect(printedBody((await cli(['get', 'notes/big-append'])).stdout).trimEnd()).toBe('# Big append\n\nstart');
+ const appended = await cli(['append', 'notes/big-append', '--file', path, '--expect-tail', tail, '--region', 'truth', '--separator', 'auto', '--json']);
expect(appended.code, appended.stderr).toBe(0);
- expect(await stored('notes/big-append')).toMatchObject({ body_storage: 'segmented' });
+ expect(await uploads()).toBe(before);
const read = await cli(['get', 'notes/big-append']);
expect(read.code, read.stderr).toBe(0);
expect(printedBody(read.stdout).trimEnd()).toBe(`# Big append\n\nstart\n${text}`.trimEnd());
}, 300_000);
+ test('an append over the 4 MiB part cap goes through an upload session; --expect-tail, --region and --separator are refused there', async () => {
+ await cli(['put', 'notes/huge-append', '--file', file('huge-append.md', '# Huge append\n\nstart\n')]);
+ const before = await uploads();
+ const text = lines(4 * 1024 * 1024 + 64 * 1024);
+ const path = file('huge-append-text.md', text);
+ for (const flags of [['--expect-tail', await tailOf('notes/huge-append')], ['--region', 'truth'], ['--separator', 'none']]) {
+ const refused = await cli(['append', 'notes/huge-append', '--file', path, ...flags]);
+ expect(refused.code, refused.stderr).toBe(2);
+ expect(refused.stderr).toContain(`${flags[0]} apply only to an append whose call fits`);
+ }
+ expect(await uploads()).toBe(before);
+ const appended = await cli(['append', 'notes/huge-append', '--file', path, '--json']);
+ expect(appended.code, appended.stderr).toBe(0);
+ expect(await uploads()).toBe(before + 1);
+ const read = await cli(['get', 'notes/huge-append']);
+ expect(read.code, read.stderr).toBe(0);
+ expect(printedBody(read.stdout).trimEnd()).toBe(`# Huge append\n\nstart\n${text}`.trimEnd());
+ }, 300_000);
+
test('local put --file over the page ceiling on a managed brain goes through an upload session, byte-identical', async () => {
const managed = async () => (await sql<{ enabled: boolean }>('SELECT enabled FROM persistence_brain'))[0]!.enabled;
if (!await managed()) {
diff --git a/test/e2e/upload-transport.test.ts b/test/e2e/upload-transport.test.ts
index 98379b4023..9932810f6e 100644
--- a/test/e2e/upload-transport.test.ts
+++ b/test/e2e/upload-transport.test.ts
@@ -241,15 +241,26 @@ for (const backend of backends) describe(`upload sessions over every transport (
});
}, 600_000);
- test('OAuth /mcp: the thin client append over one request rides an upload session (mode append)', async () => {
+ test('OAuth /mcp: the thin client appends directly within the part cap the server reports (--expect-tail honoured), and through an upload session above it', async () => {
await withOAuthServe('append', async (_client, thinHome) => {
const big = escapeHeavy(2 * MIB);
+ const huge = escapeHeavy(4 * MIB + 64 * 1024);
writeFileSync(join(thinHome, 'big.md'), big);
+ writeFileSync(join(thinHome, 'huge.md'), huge);
writeFileSync(join(thinHome, 'start.md'), '# Thin append');
expect((await cli(['put', 'uploads/thin-append', '--file', join(thinHome, 'start.md')], thinHome)).code).toBe(0);
- const appended = await cli(['append', 'uploads/thin-append', '--file', join(thinHome, 'big.md'), '--json'], thinHome);
- expect(appended.code, appended.stdout + appended.stderr).toBe(0);
- expected.set('uploads/thin-append', `# Thin append\n${big}`);
+ const head = await cli(['get', 'uploads/thin-append', '--body', 'none', '--json'], thinHome);
+ expect(head.code, head.stdout + head.stderr).toBe(0);
+ const tail = /"tail_sha256":\s*"([0-9a-f]{64})"/.exec(head.stdout)?.[1];
+ expect(tail, head.stdout).toBeDefined();
+ const direct = await cli(['append', 'uploads/thin-append', '--file', join(thinHome, 'big.md'), '--expect-tail', tail!, '--json'], thinHome);
+ expect(direct.code, direct.stdout + direct.stderr).toBe(0);
+ const refused = await cli(['append', 'uploads/thin-append', '--file', join(thinHome, 'huge.md'), '--region', 'truth'], thinHome);
+ expect(refused.code).toBe(2);
+ expect(refused.stderr).toContain('--region apply only to an append whose call fits');
+ const uploaded = await cli(['append', 'uploads/thin-append', '--file', join(thinHome, 'huge.md'), '--json'], thinHome);
+ expect(uploaded.code, uploaded.stdout + uploaded.stderr).toBe(0);
+ expected.set('uploads/thin-append', `# Thin append\n${big}\n${huge}`);
});
}, 600_000);
diff --git a/test/upload-part-cutter.test.ts b/test/upload-part-cutter.test.ts
index 97443368a5..4570c20994 100644
--- a/test/upload-part-cutter.test.ts
+++ b/test/upload-part-cutter.test.ts
@@ -81,19 +81,31 @@ describe('cutUploadPart', () => {
test('the whole text when it fits; a refusal naming the cap when not one character fits', () => {
expect(cutUploadPart('short', FRAME, 1024 * 1024)).toBe(5);
expect(() => cutUploadPart('😀', FRAME, frameOf('') + 3)).toThrow(/cannot carry even one character/);
- try { cutUploadPart('abc', FRAME, 10); } catch (error) { expect((error as { code?: string }).code).toBe('payload_too_large'); }
+ let refusal: unknown;
+ try { cutUploadPart('abc', FRAME, 10); } catch (error) { refusal = error; }
+ expect(refusal).toBeDefined();
+ expect((refusal as { code?: string }).code).toBe('payload_too_large');
});
});
-/** A fake brain that stores parts the way spec 6.2 says: contiguous, replay-idempotent, sha-checked, frame-capped. */
+/**
+ * A fake brain that stores parts the way spec 6.2 says: contiguous, replay-idempotent, sha-checked, frame-capped.
+ * Every call reaches it as the serialized JSON-RPC request a transport would send (a real, growing id), and it
+ * checks that request's own UTF-8 byte length against the cap, independent of the client's frame measure.
+ */
function fakeUploadServer(opts: { maxFrame: number; dropReplyAfterStoring?: number[]; dropBeforeStoring?: number[]; refusePart?: number }) {
const parts: string[] = [];
const calls: string[] = [];
+ const partFrames: number[] = [];
+ let nextId = 1000;
let state: 'open' | 'committed' | 'aborted' = 'open';
let declared = { bytes: 0, sha256: '' };
const drop = () => new RemoteMcpError('network', 'connection reset', { kind: 'unreachable' });
const received = () => Buffer.byteLength(parts.join(''), 'utf8');
- const call: UploadToolCall = async (tool, args) => {
+ const call: UploadToolCall = async (tool, sent) => {
+ const raw = JSON.stringify({ jsonrpc: '2.0', id: nextId++, method: 'tools/call', params: { name: tool, arguments: sent } });
+ const request = JSON.parse(raw) as { params: { arguments: Record<string, unknown> } };
+ const args = request.params.arguments;
calls.push(tool);
if (tool === 'begin_page_upload') {
declared = { bytes: Number(args.total_bytes), sha256: String(args.sha256) };
@@ -102,7 +114,8 @@ function fakeUploadServer(opts: { maxFrame: number; dropReplyAfterStoring?: numb
if (tool === 'upload_page_part') {
const part = Number(args.part);
const text = String(args.text);
- expect(toolCallFrameBytes('upload_page_part', args)).toBeLessThanOrEqual(opts.maxFrame);
+ partFrames.push(Buffer.byteLength(raw, 'utf8'));
+ expect(Buffer.byteLength(raw, 'utf8')).toBeLessThanOrEqual(opts.maxFrame);
expect(createHash('sha256').update(text, 'utf8').digest('hex')).toBe(String(args.part_sha256));
if (part === opts.refusePart) throw opError('payload_too_large', 'part refused', 'smaller part');
if (opts.dropBeforeStoring?.includes(part)) { opts.dropBeforeStoring.splice(opts.dropBeforeStoring.indexOf(part), 1); throw drop(); }
@@ -122,7 +135,7 @@ function fakeUploadServer(opts: { maxFrame: number; dropReplyAfterStoring?: numb
}
throw new Error(`unexpected tool ${tool}`);
};
- return { call, parts, calls, state: () => state };
+ return { call, parts, calls, partFrames, state: () => state };
}
const transient = (error: unknown) => error instanceof RemoteMcpError && error.reason === 'network';
@@ -137,6 +150,8 @@ describe('uploadPageBody', () => {
expect(server.parts.join('')).toBe(text);
expect(server.parts.length).toBeGreaterThan(3);
expect(server.state()).toBe('committed');
+ expect(Math.max(...server.partFrames)).toBeLessThanOrEqual(8192);
+ expect(Math.max(...server.partFrames)).toBeGreaterThan(8192 - 1024 - 64);
});
test('a reply lost after the part landed resumes at get_page_upload next_part, without resending it', async () => {