Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(transcripts): stored part_bytes cannot be steered by a remote writer (Wave B PR 4 lane 4e, cso)

garrytanab6254bbada4
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index 1068b4fc4e..2f6505f745 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -1045,7 +1045,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;
// PR 4 recall (Wave B incremental derivation, transcripts). `since` is restamped at the merge slot.
{ since: 'TBD', text: 'Pages over 1 MiB (stored in segments) now cut a long passage that has to be split at a sentence or line end, so a sentence the old cut split across two chunks is found whole by keyword and vector search. Pages stored before keep serving their chunks: `gbrain reindex --segmented` lists them with the chunk counts that would change and writes nothing; `--apply` re-chunks only the segments that change and keeps the vectors of unchanged chunk texts, and `gbrain embed --stale` embeds the new ones. Nothing re-chunks on upgrade.' },
// PR 4 4e (Wave B incremental derivation, transcripts). `since` is restamped at the merge slot.
- { since: 'TBD', text: 'New transcript sessions import as one page; existing split sessions stop rewriting every part when a session grows. `gbrain transcripts ingest` writes a session with no part pages as one page up to the page ceiling (`pages.max_bytes` or the content-sanity block line, whichever is lower), at its base slug with the same `<id>-p1` identity; only a message or session over that ceiling continues into `-pN` pages. A session already split into parts keeps them and their grouping. The part count left hashed content (titles read `(part X)`, `transcript_import.of` is gone and `part_bytes` records the part size), so each part is rewritten once on its next import; after that a grown session changes only its last part or adds one. Nothing merges a split session into one page.' },
+ { since: 'TBD', text: 'New transcript sessions import as one page; existing split sessions stop rewriting every part when a session grows. `gbrain transcripts ingest` writes a session with no part pages as one page up to the page ceiling (`pages.max_bytes` or the content-sanity block line, whichever is lower), at its base slug with the same `<id>-p1` identity; only a message or session over that ceiling continues into `-pN` pages. A session already split into parts keeps them and their grouping. The part count left hashed content (titles read `(part X)`, `transcript_import.of` is gone and `part_bytes` records the part size), so each part is rewritten once on its next import; after that a grown session changes only its last part or adds one. Nothing merges a split session into one page. The part size is read only from parts the importer last wrote, so a remote edit of `transcript_import` cannot change how a session splits, and a session that would render over 2,000 parts is reported as an errored session with nothing written.' },
// PR 4 (Wave B incremental derivation, transcripts)
// PR 4 4b
{ since: 'TBD', text: 'Appending to a long conversation now re-extracts facts only for the new messages.' },
diff --git a/src/core/transcripts/ingest.ts b/src/core/transcripts/ingest.ts
index 42a916874f..60cec35ccd 100644
--- a/src/core/transcripts/ingest.ts
+++ b/src/core/transcripts/ingest.ts
@@ -664,6 +664,9 @@ async function transcriptPageCeiling(engine: BrainEngine): Promise<number> {
return Math.floor(Math.min(policy.maxBytes, block) * PAGE_CEILING_FILL);
}
+/** The provenance the importer stamps on every part it writes (importFromContent and the coordinated put_page). */
+const IMPORTER_INGESTED_VIA = 'cli:transcripts-ingest';
+
/**
* How a session renders, from what is stored (one query by the part 1 and
* part 2 identities, which also finds part 1's slug for adoption). The
@@ -672,17 +675,28 @@ async function transcriptPageCeiling(engine: BrainEngine): Promise<number> {
* `of`); it then keeps the part size its parts carry (`part_bytes`, else
* the pre-Wave-B PART_TARGET_BYTES). Otherwise it is one page under the page
* ceiling. A split session is never re-rendered as one page.
+ *
+ * `transcript_import` is ordinary frontmatter that any writer can set, so its
+ * `of` and `part_bytes` are read only from a part whose last provenance-stamped
+ * write was the importer's (`ingested_via` is the importer's or, for a page
+ * no provenance-stamped write touched, NULL). Every remote write stamps
+ * `mcp:<operation>` and keeps it until the importer writes the page again,
+ * so a remote edit can't choose the layout or the part size. A live part 2
+ * counts whoever wrote it last: ignoring it would merge a split session and
+ * delete its parts. A `part_bytes` is accepted only between PART_TARGET_BYTES
+ * (or the ceiling, when that is lower) and the current ceiling.
*/
async function storedTranscriptLayout(engine: BrainEngine, sourceId: string, meta: ParsedSession['meta'], pageCeiling: number):
Promise<{ layout: TranscriptLayout; partTargetBytes: number; existingSlug: string | null }> {
const [first, second] = [transcriptPartId(meta, 1), transcriptPartId(meta, 2)];
- const rows = await engine.executeRaw<{ slug: string; fid: string; ti: unknown }>(
- `SELECT slug, frontmatter->>'id' AS fid, frontmatter->'transcript_import' AS ti FROM pages
+ const rows = await engine.executeRaw<{ slug: string; fid: string; ti: unknown; via: string | null }>(
+ `SELECT slug, frontmatter->>'id' AS fid, frontmatter->'transcript_import' AS ti, ingested_via AS via FROM pages
WHERE source_id = $1 AND deleted_at IS NULL AND frontmatter->>'id' IN ($2, $3) ORDER BY pages.id`,
[sourceId, first, second],
);
- const importMeta = (row: { ti: unknown } | undefined) => {
- const ti = typeof row?.ti === 'string' ? JSON.parse(row.ti) : row?.ti;
+ const importMeta = (row: { ti: unknown; via: string | null } | undefined) => {
+ if (!row || (row.via !== null && row.via !== IMPORTER_INGESTED_VIA)) return null;
+ const ti = typeof row.ti === 'string' ? JSON.parse(row.ti) : row.ti;
return ti && typeof ti === 'object' ? ti as { of?: unknown; part_bytes?: unknown } : null;
};
const partOne = rows.find(row => row.fid === first);
@@ -690,8 +704,10 @@ async function storedTranscriptLayout(engine: BrainEngine, sourceId: string, met
const one = importMeta(partOne);
const split = partTwo !== undefined || (one !== null && !(Number(one.of) <= 1));
if (!split) return { layout: 'single', partTargetBytes: pageCeiling, existingSlug: partOne?.slug ?? null };
- const pinned = [one?.part_bytes, importMeta(partTwo)?.part_bytes].find(v => Number.isSafeInteger(v) && (v as number) > 0) as number | undefined;
- return { layout: 'split', partTargetBytes: pinned ?? PART_TARGET_BYTES, existingSlug: partOne?.slug ?? null };
+ const floor = Math.min(PART_TARGET_BYTES, pageCeiling);
+ const pinned = [one?.part_bytes, importMeta(partTwo)?.part_bytes]
+ .find(v => Number.isSafeInteger(v) && (v as number) >= floor && (v as number) <= pageCeiling) as number | undefined;
+ return { layout: 'split', partTargetBytes: pinned ?? floor, existingSlug: partOne?.slug ?? null };
}
/** Fold one file's adapter diagnostics into its outcome and the run result (drift, skipped lines, truncation). */
diff --git a/src/core/transcripts/render.ts b/src/core/transcripts/render.ts
index 5ae32802ca..7a6e7cba3a 100644
--- a/src/core/transcripts/render.ts
+++ b/src/core/transcripts/render.ts
@@ -73,6 +73,13 @@ const DATE_HEADING_RE = /^#{1,6}\s*\d{4}-\d{2}-\d{2}\b/;
* `part_bytes` keeps. New sessions no longer split at it.
*/
export const PART_TARGET_BYTES = Math.floor(DEFAULT_BYTES_WARN * 0.9);
+/**
+ * Most part pages one session renders to. A session over it is refused before
+ * any write (the session is errored and the scan is not clean): 2,000 parts is
+ * 90 MB at the pre-Wave-B part size, and a new session splits only past the
+ * page ceiling.
+ */
+export const TRANSCRIPT_MAX_PARTS = 2_000;
/** Share of the page ceiling a single-layout page's body may fill; the rest is frontmatter headroom. */
export const PAGE_CEILING_FILL = 0.9;
/** `single`: a new session, one page under the ceiling; `split`: a stored split session keeps its parts. */
@@ -431,6 +438,9 @@ export function renderSessionParts(
}
if (current.length) groups.push(current);
+ if (groups.length > TRANSCRIPT_MAX_PARTS) {
+ throw new Error(`session ${meta.sessionId} renders ${groups.length} parts at ${partTargetBytes} bytes per part, over the ${TRANSCRIPT_MAX_PARTS}-part cap; nothing was written for it`);
+ }
const single = (opts.layout ?? 'single') === 'single' && groups.length === 1;
const title = meta.title?.trim() || `${meta.harness} session ${meta.sessionId.slice(0, 12)}`;
diff --git a/test/helpers/transcripts-part-churn-cases.ts b/test/helpers/transcripts-part-churn-cases.ts
index 22af64a596..f7ab7520e7 100644
--- a/test/helpers/transcripts-part-churn-cases.ts
+++ b/test/helpers/transcripts-part-churn-cases.ts
@@ -28,6 +28,12 @@ import {
TRANSCRIPT_IMPORT_VERSION,
} from '../../src/core/transcripts/render.ts';
import { buildTranscriptSlug, transcriptFullId, type ParsedSession } from '../../src/core/transcripts/types.ts';
+import { dumpFrontmatterYaml } from '../../src/core/data-frontmatter.ts';
+import { dispatchToolCall } from '../../src/mcp/dispatch.ts';
+import { registerLocalWriter, withVerifiedLocalRegistration } from '../../src/core/persistence/identity.ts';
+import { disposePersistenceConsumer } from '../../src/core/persistence/service.ts';
+import { TRANSCRIPT_MAX_PARTS } from '../../src/core/transcripts/render.ts';
+import { withEnv } from './with-env.ts';
const NO_PATTERNS = { userPatternsPath: '/nonexistent-patterns.txt' };
const STARTED = '2026-08-10T08:00:00.000Z';
@@ -109,6 +115,31 @@ async function liveParts(engine: BrainEngine, base: string): Promise<LivePart[]>
.sort((a, b) => num(a.slug) - num(b.slug));
}
+/**
+ * A remote agent with read and write scope rewrites a page's `transcript_import` through MCP `put_page`
+ * (`remote: true`, a registered writer, bound to the revision `get_page` returned).
+ */
+async function remoteRewriteImportMeta(engine: BrainEngine, dir: string, slug: string, edit: (ti: Record<string, unknown>) => void): Promise<void> {
+ const page = await engine.getPage(slug, { sourceId: 'default' });
+ const fm = { ...(page!.frontmatter as Record<string, any>) };
+ fm.transcript_import = { ...fm.transcript_import };
+ edit(fm.transcript_import);
+ await withEnv({ GBRAIN_HOME: join(dir, 'home') }, async () => {
+ const registration = await registerLocalWriter(engine, 'stdio', { sourceIds: ['*'], operations: null, scopes: ['read', 'write'], slugPrefixes: null } as never);
+ const ctx = { remote: true, config: { engine: engine.kind }, sourceId: 'default', logger: { info() {}, warn() {}, error() {} },
+ auth: { token: 'fixture', clientId: 'remote-agent-example', scopes: ['read', 'write'], sourceId: 'default' } } as never;
+ const got = await withVerifiedLocalRegistration(engine, registration, () => dispatchToolCall(engine, 'get_page', { slug }, ctx));
+ const revision = JSON.parse((got as { content: Array<{ text: string }> }).content[0]!.text).revision;
+ expect(typeof revision).toBe('string');
+ const put = await withVerifiedLocalRegistration(engine, registration, () => dispatchToolCall(engine, 'put_page',
+ { slug, expected_revision: revision, request_id: randomUUID(), content: `---\n${dumpFrontmatterYaml(fm)}---\n${page!.compiled_truth}\n` }, ctx));
+ expect((put as { isError?: boolean }).isError ?? false).toBe(false);
+ });
+ await disposePersistenceConsumer(engine);
+ const stored = await engine.getPage(slug, { sourceId: 'default' });
+ expect((stored!.frontmatter as Record<string, any>).transcript_import).toEqual(fm.transcript_import);
+}
+
async function withDir(fn: (dir: string) => Promise<void>): Promise<void> {
const dir = mkdtempSync(join(tmpdir(), 'gb-part-churn-'));
try { await fn(dir); } finally { rmSync(dir, { recursive: true, force: true }); }
@@ -211,9 +242,9 @@ export function defineTranscriptPartChurnCases(opts: { getEngine: () => BrainEng
const engine = opts.getEngine();
const id = `ceiling-${randomUUID().slice(0, 8)}`;
const base = baseSlugOf(id);
- const text = Array.from({ length: 6_000 }, (_, i) => `tok-${String(i).padStart(4, '0')}`).join(',');
+ const text = Array.from({ length: 20_000 }, (_, i) => `tok-${String(i).padStart(5, '0')}`).join(',');
const path = writeSession(dir, id, [{ text }]);
- await engine.setConfig('pages.max_bytes', '20000');
+ await engine.setConfig('pages.max_bytes', '60000');
let parts: LivePart[];
try {
const r = await ingest(engine, path);
@@ -226,9 +257,9 @@ export function defineTranscriptPartChurnCases(opts: { getEngine: () => BrainEng
const anchor = '**User** (2026-08-10 8:00 AM): ';
const fragments: string[] = [];
for (const page of parts) {
- expect(page.frontmatter.transcript_import.part_bytes).toBe(18_000);
+ expect(page.frontmatter.transcript_import.part_bytes).toBe(54_000);
const body = (await engine.getPage(page.slug, { sourceId: 'default' }))!.compiled_truth;
- expect(Buffer.byteLength(body, 'utf8')).toBeLessThanOrEqual(18_000);
+ expect(Buffer.byteLength(body, 'utf8')).toBeLessThanOrEqual(54_000);
for (const block of body.split('\n\n')) if (block.startsWith(anchor)) fragments.push(block.slice(anchor.length));
}
expect(fragments.length).toBe(parts.length);
@@ -262,4 +293,83 @@ export function defineTranscriptPartChurnCases(opts: { getEngine: () => BrainEng
expect(after.slice(0, n - 1).map(p => p.frontmatter.transcript_import.imperatives_flagged)).toEqual(Array(n - 1).fill(undefined));
expect(after[n - 1]!.frontmatter.transcript_import.imperatives_flagged).toBe(1);
}), 180_000);
+
+ test('a remote put_page of transcript_import.part_bytes (120, 60, 40) never steers the layout of the next ingest', () => withDir(async (dir) => {
+ const engine = opts.getEngine();
+ const id = `remote-${randomUUID().slice(0, 8)}`;
+ const base = baseSlugOf(id);
+ let messages = regular(20);
+ expect((await ingest(engine, writeSession(dir, id, messages))).pages).toMatchObject({ imported: 1, errored: 0 });
+ for (const partBytes of [120, 60, 40]) {
+ await remoteRewriteImportMeta(engine, dir, base, ti => { ti.part_bytes = partBytes; delete ti.of; });
+ messages = [...messages, { text: `follow-up after ${partBytes}` }];
+ const r = await ingest(engine, writeSession(dir, id, messages));
+ expect({ pages: r.pages, sessionsErrored: r.sessionsErrored, partsDeleted: r.partsDeleted, cleanScan: r.cleanScan })
+ .toEqual({ pages: { imported: 1, skipped: 0, errored: 0, planned: 0, pending: 0 }, sessionsErrored: 0, partsDeleted: 0, cleanScan: true });
+ const pages = await liveParts(engine, base);
+ expect(pages.map(p => p.slug)).toEqual([base]);
+ expect(pages[0]!.frontmatter.transcript_import).toEqual({ harness: 'openclaw', session_id: id, version: 1, part: 1, of: 1 });
+ }
+ }), 180_000);
+
+ test('a remote part_bytes on a split part is ignored: parts 1..N-1 keep their content_hash', () => withDir(async (dir) => {
+ const engine = opts.getEngine();
+ const id = `remotesplit-${randomUUID().slice(0, 8)}`;
+ const base = baseSlugOf(id);
+ const s0 = regular(30);
+ const n = await seedLegacySplit(engine, writeSession(dir, id, s0));
+ const s1 = [...s0, { text: 'small follow-up A' }];
+ expect((await ingest(engine, writeSession(dir, id, s1))).pages).toMatchObject({ imported: n, errored: 0 });
+ const before = await liveParts(engine, base);
+ for (const slug of [partSlug(base, 1), partSlug(base, 2)]) await remoteRewriteImportMeta(engine, dir, slug, ti => { ti.part_bytes = 120; });
+ const r = await ingest(engine, writeSession(dir, id, [...s1, { text: 'small follow-up B' }]));
+ expect(r.pages).toMatchObject({ imported: 3, skipped: n - 3, errored: 0 });
+ const after = await liveParts(engine, base);
+ expect(after.map(p => p.slug)).toEqual(before.map(p => p.slug));
+ expect(after.slice(0, n - 1).map(p => p.hash)).toEqual(before.slice(0, n - 1).map(p => p.hash));
+ for (const page of after) expect(page.frontmatter.transcript_import.part_bytes).toBe(PART_TARGET_BYTES);
+ }), 180_000);
+
+ test('an importer-written part_bytes outside [45,000, ceiling] is not accepted', () => withDir(async (dir) => {
+ const engine = opts.getEngine();
+ const id = `bounds-${randomUUID().slice(0, 8)}`;
+ const base = baseSlugOf(id);
+ const s0 = regular(30);
+ const n = await seedLegacySplit(engine, writeSession(dir, id, s0));
+ const s1 = [...s0, { text: 'small follow-up' }];
+ expect((await ingest(engine, writeSession(dir, id, s1))).pages).toMatchObject({ imported: n, errored: 0 });
+ for (const part of [1, 2]) {
+ const page = await engine.getPage(partSlug(base, part), { sourceId: 'default' });
+ const fm = { ...(page!.frontmatter as Record<string, any>) };
+ fm.transcript_import = { ...fm.transcript_import, part_bytes: part === 1 ? 120 : 1024 ** 3 };
+ await importFromContent(engine, partSlug(base, part), renderPartContent(fm, page!.compiled_truth), {
+ noEmbed: true, sourceId: 'default', source_kind: 'transcript:openclaw', source_uri: 'fixture', ingested_via: 'cli:transcripts-ingest' });
+ }
+ const r = await ingest(engine, writeSession(dir, id, [...s1, { text: 'another follow-up' }]));
+ expect(r.pages).toMatchObject({ imported: 3, errored: 0 });
+ expect((await liveParts(engine, base)).map(p => p.frontmatter.transcript_import.part_bytes)).toEqual(Array(n).fill(PART_TARGET_BYTES));
+ }), 180_000);
+
+ test('a session that cannot render (no room at the ceiling, or over the part cap) is an errored session, nothing written', () => withDir(async (dir) => {
+ const engine = opts.getEngine();
+ const tiny = `tiny-${randomUUID().slice(0, 8)}`;
+ const many = `many-${randomUUID().slice(0, 8)}`;
+ const manyMessages = Array.from({ length: TRANSCRIPT_MAX_PARTS + 1 }, (_, i) => ({ text: `m${i} ${'y'.repeat(600)}` }));
+ const results = [];
+ for (const [id, maxBytes, messages] of [[tiny, 40, regular(2)], [many, 1_000, manyMessages]] as const) {
+ await engine.setConfig('pages.max_bytes', String(maxBytes));
+ try {
+ results.push(await ingest(engine, writeSession(dir, id, [...messages])));
+ } finally {
+ await engine.unsetConfig('pages.max_bytes');
+ }
+ }
+ for (const [i, r] of results.entries()) {
+ expect({ sessionsErrored: r.sessionsErrored, sessionsImported: r.sessionsImported, cleanScan: r.cleanScan, imported: r.pages.imported })
+ .toEqual({ sessionsErrored: 1, sessionsImported: 0, cleanScan: false, imported: 0 });
+ expect(r.files[0]!.sessions[0]!.error).toMatch(i === 0 ? /leaves no room/ : new RegExp(`over the ${TRANSCRIPT_MAX_PARTS}-part cap`));
+ }
+ expect(await liveParts(engine, baseSlugOf(tiny))).toEqual([]);
+ expect(await liveParts(engine, baseSlugOf(many))).toEqual([]);
+ }), 180_000);
}