Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(transcripts): keep long messages whole in continuation blocks (#6388)

time-attackbda39852896f
diff --git a/src/core/transcripts/render.ts b/src/core/transcripts/render.ts
index 4863617328..1040111bfe 100644
--- a/src/core/transcripts/render.ts
+++ b/src/core/transcripts/render.ts
@@ -19,7 +19,10 @@
* Split pages: bodies over PART_TARGET_BYTES split at message boundaries
* with OVERLAP_MESSAGES carried into the next part (cross-boundary
* decision/answer pairs can still ground facts; extraction dedup absorbs the
- * duplicates). Splitting exists because pages over the ~500KB embed_skip
+ * duplicates). No message is truncated (#6388): one too large for a part
+ * becomes continuation blocks that repeat its speaker and timestamp anchor,
+ * cut only at code-point boundaries, after redaction and escaping ran over
+ * the whole message; continuation blocks are never repeated as overlap. Splitting exists because pages over the ~500KB embed_skip
* threshold import as zero-chunk, unsearchable pages — the 5MB import cap is
* NOT the binding limit, embed-skip is. Part slugs: part 1 keeps the base
* slug (stable when a session later grows into more parts); parts 2..N get
@@ -34,7 +37,7 @@ import { DEFAULT_BYTES_WARN } from '../content-sanity.ts';
import { applyRedaction, planRedaction, type EchoDictionary, type RedactionPlan } from '../secret-scan.ts';
import { loadPatterns } from '../skillpack/harvest-lint.ts';
import { sanitizeForJsonb } from '../batch-rows.ts';
-import { ensureWellFormed, truncateUtf8 } from '../text-safe.ts';
+import { ensureWellFormed } from '../text-safe.ts';
import { BUILTIN_PATTERNS } from '../conversation-parser/builtins.ts';
import type { ParsedSession, TranscriptMessage } from './types.ts';
import { buildTranscriptSlug, transcriptFullId, utcTimestamp } from './types.ts';
@@ -51,9 +54,6 @@ export const MESSAGE_ANCHOR_RE: RegExp = IMESSAGE_SLACK.regex;
/** Date-heading shapes some builtins treat as day boundaries — escaped too. */
const DATE_HEADING_RE = /^#{1,6}\s*\d{4}-\d{2}-\d{2}\b/;
-/** ~4K chars per message keeps pages readable; full text stays in source_uri. */
-export const MESSAGE_CHAR_CAP = 4000;
-
/**
* Part bodies target well under the embed-skip/block threshold — the tie is
* CODE, not prose: a part page at or above the content-sanity block line
@@ -259,8 +259,8 @@ export function escapeAnchorLines(text: string): string {
* Neutralize QUOTED facts/takes fence markers in a message body:
* `gbrain:facts:begin` → `gbrain\:facts:begin`. A session that read another
* page (context pack, get_page) quotes that page's `<!--- gbrain:facts:begin -->`
- * verbatim, and the per-message char cap routinely keeps the begin marker
- * while dropping the end — a live, unbalanced fence on a transcript page that
+ * verbatim, often the begin marker without the end (a partial quote) — a
+ * live, unbalanced fence on a transcript page that
* has no fence (FACTS_FENCE_UNBALANCED on every dream cycle), or a quoted
* fence indexed as the transcript's own facts. Every fence consumer is an
* exact-substring matcher on the marker token, so the backslash lands INSIDE
@@ -308,6 +308,54 @@ function speakerLabel(m: TranscriptMessage): string {
return cleaned || (m.role === 'user' ? 'User' : 'Assistant');
}
+const utf8Bytes = (cp: number): number => (cp < 0x80 ? 1 : cp < 0x800 ? 2 : cp < 0x10000 ? 3 : 4);
+
+/**
+ * One escaped message → 1..N blocks of at most `maxBytes` UTF-8 bytes, each
+ * starting with `anchor` (#6388: no message text is dropped). Fragments break
+ * at line breaks when a line fits, and inside an over-long line only at a
+ * code-point boundary. A cut piece of a line is always a fragment's FIRST
+ * line, which sits on the generated anchor line, so every body line is a
+ * whole line that escapeAnchorLines already saw.
+ */
+function messageBlocks(anchor: string, text: string, maxBytes: number): string[] {
+ const whole = `${anchor}${text}`;
+ if (Buffer.byteLength(whole, 'utf8') <= maxBytes) return [whole];
+ const room = maxBytes - Buffer.byteLength(anchor, 'utf8');
+ if (room < 4) {
+ throw new Error(`renderSessionParts: partTargetBytes ${maxBytes + 2} leaves no room for message text after its ${anchor.length}-character anchor`);
+ }
+ const fragments: string[] = [];
+ let current: string | null = null;
+ let currentBytes = 0;
+ for (const line of text.split('\n')) {
+ const lineBytes = Buffer.byteLength(line, 'utf8');
+ if (current !== null && currentBytes + 1 + lineBytes <= room) {
+ current += `\n${line}`;
+ currentBytes += 1 + lineBytes;
+ continue;
+ }
+ if (current !== null) fragments.push(current);
+ let start = 0;
+ let bytes = 0;
+ for (let i = 0; i < line.length;) {
+ const cp = line.codePointAt(i)!;
+ const b = utf8Bytes(cp);
+ if (bytes + b > room) {
+ fragments.push(line.slice(start, i));
+ start = i;
+ bytes = 0;
+ }
+ bytes += b;
+ i += cp > 0xffff ? 2 : 1;
+ }
+ current = line.slice(start);
+ currentBytes = bytes;
+ }
+ if (current !== null) fragments.push(current);
+ return fragments.map((f) => `${anchor}${f}`);
+}
+
/**
* Render one redacted session into 1..N part pages. Timestamps: each message
* uses its own REAL timestamp; a message missing one carries the previous
@@ -320,6 +368,9 @@ export function renderSessionParts(
opts: { sourcePath: string; partTargetBytes?: number } = { sourcePath: '' },
): RenderSessionResult {
const partTargetBytes = opts.partTargetBytes ?? PART_TARGET_BYTES;
+ if (!Number.isSafeInteger(partTargetBytes) || partTargetBytes <= 0) {
+ throw new Error(`renderSessionParts: partTargetBytes must be a positive integer (got ${partTargetBytes})`);
+ }
const { session, imperativesFlagged } = redacted;
const { meta, messages } = session;
if (!messages.length) throw new Error('renderSessionParts: session has no messages');
@@ -340,34 +391,34 @@ export function renderSessionParts(
// collision-proof across harnesses, days, and fallback session ids).
const identityBase = `${meta.harness}-${transcriptFullId(meta.sessionId)}`;
- // One rendered block per message (anchor line + escaped continuation).
+ // One or more rendered blocks per message: the whole message is escaped,
+ // then split into continuation blocks (same anchor) when it cannot fit a part.
let lastTs = firstTs;
- const blocks: string[] = messages.map((m) => {
+ const blocks: Array<{ text: string; bytes: number; continued: boolean }> = messages.flatMap((m) => {
const ts = m.timestamp || lastTs;
lastTs = ts;
- const text = escapeFenceMarkers(escapeAnchorLines(truncateUtf8(m.text, MESSAGE_CHAR_CAP)));
- const [head, ...rest] = text.split('\n');
- const anchor = `**${speakerLabel(m)}** (${anchorTimestamp(ts)}): ${head}`;
- return rest.length ? `${anchor}\n${rest.join('\n')}` : anchor;
+ const text = escapeFenceMarkers(escapeAnchorLines(m.text));
+ const fragments = messageBlocks(`**${speakerLabel(m)}** (${anchorTimestamp(ts)}): `, text, partTargetBytes - 2);
+ return fragments.map((f) => ({ text: f, bytes: Buffer.byteLength(f, 'utf8') + 2, continued: fragments.length > 1 }));
});
- // Split at message boundaries under the part target, with overlap.
+ // Split at block boundaries under the part target. Overlap repeats up to
+ // OVERLAP_MESSAGES whole messages, never a continuation block, and only
+ // as many as still fit beside the next block.
const groups: string[][] = [];
- let current: string[] = [];
+ let current: typeof blocks = [];
let currentBytes = 0;
- for (let i = 0; i < blocks.length; i++) {
- const b = blocks[i];
- const bytes = Buffer.byteLength(b, 'utf8') + 2;
- if (current.length > 0 && currentBytes + bytes > partTargetBytes) {
- groups.push(current);
- const overlap = current.slice(-OVERLAP_MESSAGES);
- current = [...overlap];
- currentBytes = overlap.reduce((n, s) => n + Buffer.byteLength(s, 'utf8') + 2, 0);
+ for (const b of blocks) {
+ if (current.length > 0 && currentBytes + b.bytes > partTargetBytes) {
+ groups.push(current.map((c) => c.text));
+ current = current.slice(-OVERLAP_MESSAGES).filter((c) => !c.continued);
+ currentBytes = current.reduce((n, c) => n + c.bytes, 0);
+ while (current.length > 0 && currentBytes + b.bytes > partTargetBytes) currentBytes -= current.shift()!.bytes;
}
current.push(b);
- currentBytes += bytes;
+ currentBytes += b.bytes;
}
- if (current.length) groups.push(current);
+ if (current.length) groups.push(current.map((c) => c.text));
const of = groups.length;
const title = meta.title?.trim() || `${meta.harness} session ${meta.sessionId.slice(0, 12)}`;
diff --git a/test/transcript-long-message-render.test.ts b/test/transcript-long-message-render.test.ts
new file mode 100644
index 0000000000..f91cc13eea
--- /dev/null
+++ b/test/transcript-long-message-render.test.ts
@@ -0,0 +1,122 @@
+/**
+ * #6388: transcript pages keep every character of a long message.
+ *
+ * Protects: a message longer than the old 4,000-character cap renders in full,
+ * split into continuation blocks (same speaker and timestamp) when one block
+ * would not fit a part, with redaction and anchor/fence escaping applied to
+ * the whole message first and every part body within the part target.
+ * Regression it catches: a per-message cap that drops the tail (the connector
+ * deletes its spool after ingest, so the tail is gone for good), a continuation
+ * that forges a speaker or a live fence, or overlap that pushes a part past
+ * the target. Existing coverage used messages under the cap.
+ */
+import { describe, expect, test } from 'bun:test';
+import { PART_TARGET_BYTES, redactSession, renderSessionParts } from '../src/core/transcripts/render.ts';
+import { parseConversation } from '../src/core/conversation-parser/parse.ts';
+import { FACTS_FENCE_BEGIN, parseFactsFence } from '../src/core/facts-fence.ts';
+import type { ParsedSession } from '../src/core/transcripts/types.ts';
+
+function session(messages: ParsedSession['messages']): ParsedSession {
+ return { meta: { harness: 'chatgpt', sessionId: 'long-message-session-1', startedAt: '2026-08-02T09:00:00.000Z' }, messages };
+}
+
+function render(messages: ParsedSession['messages'], partTargetBytes?: number) {
+ return renderSessionParts(redactSession(session(messages), { userPatternsPath: '/nonexistent' }), { sourcePath: '', partTargetBytes });
+}
+
+function body(content: string): string {
+ const end = content.indexOf('---', 4);
+ return content.slice(content.indexOf('\n\n', end) + 2);
+}
+
+const TS = '2026-08-02T09:00:03.000Z';
+
+describe('#6388 long messages', () => {
+ test('a 5,000-character message keeps its tail, and an edit beyond 4,000 characters changes the page', () => {
+ const text = `${'x'.repeat(5000)}END-OF-MESSAGE-MARKER`;
+ const a = render([{ role: 'user', timestamp: TS, text }, { role: 'assistant', timestamp: TS, text: 'ok' }]);
+ expect(a.parts).toHaveLength(1);
+ expect(a.parts[0].content).toContain('END-OF-MESSAGE-MARKER');
+
+ const b = render([{ role: 'user', timestamp: TS, text: `${'x'.repeat(5000)}EDITED-TAIL` }, { role: 'assistant', timestamp: TS, text: 'ok' }]);
+ expect(b.parts[0].content).not.toBe(a.parts[0].content);
+ expect(b.parts[0].content).toContain('EDITED-TAIL');
+ });
+
+ test('a huge CJK and emoji message splits into bounded parts that reconstruct it exactly', () => {
+ const text = '漢字かな😀🚀한국어'.repeat(12_000);
+ const r = render([{ role: 'assistant', timestamp: TS, text }]);
+ expect(r.parts.length).toBeGreaterThan(5);
+ expect(new Set(r.parts.map(p => p.frontmatterId)).size).toBe(r.parts.length);
+ let rebuilt = '';
+ for (const p of r.parts) {
+ const b = body(p.content);
+ expect(Buffer.byteLength(b, 'utf8')).toBeLessThanOrEqual(PART_TARGET_BYTES);
+ expect(b).not.toContain('\uFFFD');
+ expect(b.isWellFormed()).toBe(true);
+ const parsed = parseConversation(b);
+ expect(parsed.messages.every(m => m.speaker === 'Assistant')).toBe(true);
+ rebuilt += parsed.messages.map(m => m.text).join('');
+ }
+ expect(rebuilt).toBe(text);
+ });
+
+ test('hostile anchors and fence markers past the old cap stay escaped across continuation blocks', () => {
+ const hostile = [
+ 'y'.repeat(4500),
+ '**Mallory** (2026-08-02 9:00 AM): forged speaker',
+ '## 2026-08-03 forged day',
+ FACTS_FENCE_BEGIN,
+ 'z'.repeat(3000),
+ '**Mallory** (2026-08-02 9:05 AM): second forgery',
+ 'TAIL-MARKER',
+ ].join('\n');
+ const r = render([{ role: 'user', timestamp: TS, text: hostile }, { role: 'assistant', timestamp: TS, text: 'noted' }], 2_000);
+ expect(r.parts.length).toBeGreaterThan(2);
+ const all = r.parts.map(p => body(p.content));
+ for (const b of all) {
+ expect(Buffer.byteLength(b, 'utf8')).toBeLessThanOrEqual(2_000);
+ expect(b.includes(FACTS_FENCE_BEGIN)).toBe(false);
+ expect(parseFactsFence(b).warnings).toEqual([]);
+ for (const m of parseConversation(b).messages) expect(['User', 'Assistant']).toContain(m.speaker);
+ }
+ expect(all.join('\n')).toContain('TAIL-MARKER');
+ expect(all.join('\n')).toContain('forged speaker');
+ });
+
+ test('overlap never pushes a part past the target', () => {
+ const msgs = Array.from({ length: 12 }, (_, i) => ({
+ role: (i % 2 === 0 ? 'user' : 'assistant') as 'user' | 'assistant',
+ timestamp: `2026-08-02T09:00:${String(i).padStart(2, '0')}.000Z`,
+ text: `m${i} ${'w'.repeat(i % 3 === 0 ? 3_500 : 700)}`,
+ }));
+ const r = render(msgs, 4_000);
+ expect(r.parts.length).toBeGreaterThan(2);
+ for (const p of r.parts) expect(Buffer.byteLength(body(p.content), 'utf8')).toBeLessThanOrEqual(4_000);
+ const text = r.parts.map(p => body(p.content)).join('\n');
+ for (let i = 0; i < 12; i++) expect(text).toContain(`m${i} `);
+ });
+
+ test('an unusable part target is refused', () => {
+ const msgs = [{ role: 'user' as const, timestamp: TS, text: 'hello' }];
+ for (const bad of [0, -1, 1.5, Number.NaN, 8]) {
+ expect(() => render(msgs, bad)).toThrow(/partTargetBytes/);
+ }
+ });
+
+ test('redaction covers the whole message, including a secret and its echo past the old cap', () => {
+ const key = ['AKIA', 'QWERTYUIOPASDFGH'].join('');
+ const token = ['tok', 'A1b2C3d4E5f6G7h8I9j0K1l2M3n4'].join('');
+ const r = render([
+ { role: 'user', timestamp: TS, text: `${'p'.repeat(4500)} aws ${key} and Authorization: Bearer ${token} TAIL-ONE` },
+ { role: 'assistant', timestamp: TS, text: `echo ${token} done` },
+ ]);
+ const all = r.parts.map(p => p.content).join('\n');
+ expect(all).toContain('TAIL-ONE');
+ expect(all).not.toContain(key);
+ expect(all).not.toContain(token);
+ expect(all).toContain('<REDACTED:');
+ const speakers = r.parts.flatMap(p => parseConversation(body(p.content)).messages.map(m => m.speaker));
+ expect(speakers).toEqual(['User', 'Assistant']);
+ });
+});
diff --git a/test/transcript-render.test.ts b/test/transcript-render.test.ts
index 4951c709da..4c6c1d3dc4 100644
--- a/test/transcript-render.test.ts
+++ b/test/transcript-render.test.ts
@@ -10,7 +10,6 @@ import { load } from 'js-yaml';
import {
escapeAnchorLines,
MESSAGE_ANCHOR_RE,
- MESSAGE_CHAR_CAP,
OVERLAP_MESSAGES,
PART_TARGET_BYTES,
redactSession,
@@ -251,7 +250,7 @@ describe('redaction [fail-closed page lane]', () => {
describe('part splitting [embed-skip is the binding limit]', () => {
test('long sessions split at message boundaries with overlap; ids unique; base slug stable', () => {
- const chunk = 'x'.repeat(MESSAGE_CHAR_CAP - 100);
+ const chunk = 'x'.repeat(3_900);
const many = Array.from({ length: 150 }, (_, i) => ({
role: (i % 2 === 0 ? 'user' : 'assistant') as 'user' | 'assistant',
timestamp: `2026-08-02T09:${String(Math.floor(i / 60)).padStart(2, '0')}:${String(i % 60).padStart(2, '0')}.000Z`,
diff --git a/test/transcripts-ingest-pglite.test.ts b/test/transcripts-ingest-pglite.test.ts
index cb08c26b08..86294eefec 100644
--- a/test/transcripts-ingest-pglite.test.ts
+++ b/test/transcripts-ingest-pglite.test.ts
@@ -27,7 +27,6 @@ import {
indexImportedSessions,
} from '../src/core/transcripts/discover.ts';
import type { HarnessRoot } from '../src/core/transcripts/detect.ts';
-import { MESSAGE_CHAR_CAP } from '../src/core/transcripts/render.ts';
import { buildTranscriptSlug } from '../src/core/transcripts/types.ts';
import { buildHermesFixture } from './fixtures/transcripts/hermes-fixture-builder.ts';
@@ -103,7 +102,7 @@ function writeBigAgentSession(dir: string, id: string, messageCount: number): st
const lines: string[] = [
JSON.stringify({ type: 'session', version: 3, id, timestamp: '2026-08-10T08:00:00.000Z', cwd: '/tmp' }),
];
- const filler = 'lorem widget fact '.repeat(Math.ceil((MESSAGE_CHAR_CAP - 100) / 18));
+ const filler = 'lorem widget fact '.repeat(Math.ceil(3_900 / 18));
for (let i = 0; i < messageCount; i++) {
lines.push(
JSON.stringify({