Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(transcripts): trust stored layout only on a live revision the importer wrote (Wave B PR 4 lane 4e, round 3)
garrytan6d6a92be3689
diff --git a/src/core/transcripts/ingest.ts b/src/core/transcripts/ingest.tsindex 60cec35ccd..61a2682a2d 100644--- a/src/core/transcripts/ingest.ts+++ b/src/core/transcripts/ingest.ts@@ -677,11 +677,21 @@ const IMPORTER_INGESTED_VIA = 'cli:transcripts-ingest';* 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+ * `of` and `part_bytes` are read only from a part whose LIVE revision the+ * importer wrote. `pages.ingested_via` can't say that: a managed write keeps+ * the first write's stamp (persistence/page-prepare.ts), so a remote put_page+ * over an imported page still reads `cli:transcripts-ingest`. The live+ * revision's writer is the write attribution (`revision_write_request_id`):+ * - a journaled request wrote it: trusted when that request is the local+ * CLI's and its own intent carries the importer's provenance (a remote+ * request's intent is always server-stamped `mcp:<operation>`);+ * - its request has left the journal: trusted when the revision's principal+ * is the local CLI and the page carries the importer's stamp;+ * - no request wrote it (the direct importer on an unmanaged brain, a write+ * from before attribution): trusted when `ingested_via` is the importer's+ * or NULL; a remote write is always a journaled request, and on this path+ * it also replaces the stamp with `mcp:<operation>`.+ * 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.@@ -689,13 +699,17 @@ const IMPORTER_INGESTED_VIA = 'cli:transcripts-ingest';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; 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 rows = await engine.executeRaw<{ slug: string; fid: string; ti: unknown; trusted: boolean }>(+ `SELECT p.slug, p.frontmatter->>'id' AS fid, p.frontmatter->'transcript_import' AS ti,+ CASE WHEN p.revision_write_request_id IS NULL THEN p.ingested_via IS NULL OR p.ingested_via = $4+ WHEN r.id IS NOT NULL THEN r.principal_kind = 'local_cli' AND r.intent->>'ingested_via' IS NOT DISTINCT FROM $4+ ELSE p.revision_principal_kind IS NOT DISTINCT FROM 'local_cli' AND p.ingested_via IS NOT DISTINCT FROM $4 END AS trusted+ FROM pages p LEFT JOIN persistence_requests r ON r.id = p.revision_write_request_id+ WHERE p.source_id = $1 AND p.deleted_at IS NULL AND p.frontmatter->>'id' IN ($2, $3) ORDER BY p.id`,+ [sourceId, first, second, IMPORTER_INGESTED_VIA],);- const importMeta = (row: { ti: unknown; via: string | null } | undefined) => {- if (!row || (row.via !== null && row.via !== IMPORTER_INGESTED_VIA)) return null;+ const importMeta = (row: { ti: unknown; trusted: boolean } | undefined) => {+ if (!row || row.trusted !== true) 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;};diff --git a/test/e2e/transcripts-part-churn-postgres.test.ts b/test/e2e/transcripts-part-churn-postgres.test.tsindex 648dc0b832..d6efbc60c4 100644--- a/test/e2e/transcripts-part-churn-postgres.test.ts+++ b/test/e2e/transcripts-part-churn-postgres.test.ts@@ -11,5 +11,5 @@ import { hasDatabase, setupDB, teardownDB } from './helpers.ts';let engine: PostgresEngine;beforeAll(async () => { engine = await setupDB(); }, 120_000);afterAll(async () => { await teardownDB(); });- defineTranscriptPartChurnCases({ getEngine: () => engine });+ defineTranscriptPartChurnCases({ getEngine: () => engine, databaseUrl: process.env.DATABASE_URL });});diff --git a/test/helpers/transcripts-part-churn-cases.ts b/test/helpers/transcripts-part-churn-cases.tsindex f7ab7520e7..a7920e64df 100644--- a/test/helpers/transcripts-part-churn-cases.ts+++ b/test/helpers/transcripts-part-churn-cases.ts@@ -34,6 +34,7 @@ import { registerLocalWriter, withVerifiedLocalRegistration } from '../../src/coimport { disposePersistenceConsumer } from '../../src/core/persistence/service.ts';import { TRANSCRIPT_MAX_PARTS } from '../../src/core/transcripts/render.ts';import { withEnv } from './with-env.ts';+import { managedBrain } from './managed-brain.ts';const NO_PATTERNS = { userPatternsPath: '/nonexistent-patterns.txt' };const STARTED = '2026-08-10T08:00:00.000Z';@@ -117,14 +118,15 @@ async function liveParts(engine: BrainEngine, base: string): Promise<LivePart[]>/*** 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).+ * (`remote: true`, a registered writer, bound to the revision `get_page` returned). `dir` null: the current+ * GBRAIN_HOME (a managed brain's, whose host owns the worktree), and its persistence consumer stays up.*/-async function remoteRewriteImportMeta(engine: BrainEngine, dir: string, slug: string, edit: (ti: Record<string, unknown>) => void): Promise<void> {+async function remoteRewriteImportMeta(engine: BrainEngine, dir: string | null, 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 write = 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;@@ -133,9 +135,13 @@ async function remoteRewriteImportMeta(engine: BrainEngine, dir: string, slug: sexpect(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);+ expect((put as { isError?: boolean }).isError ? (put as { content: Array<{ text: string }> }).content[0]!.text : 'ok').toBe('ok');+ };+ if (dir === null) await write();+ else {+ await withEnv({ GBRAIN_HOME: join(dir, 'home') }, write);+ await disposePersistenceConsumer(engine);+ }const stored = await engine.getPage(slug, { sourceId: 'default' });expect((stored!.frontmatter as Record<string, any>).transcript_import).toEqual(fm.transcript_import);}@@ -145,7 +151,7 @@ async function withDir(fn: (dir: string) => Promise<void>): Promise<void> {try { await fn(dir); } finally { rmSync(dir, { recursive: true, force: true }); }}-export function defineTranscriptPartChurnCases(opts: { getEngine: () => BrainEngine }): void {+export function defineTranscriptPartChurnCases(opts: { getEngine: () => BrainEngine; databaseUrl?: string }): void {test('a split session that grows rewrites every part once; after that parts 1..N-1 keep their content_hash', () => withDir(async (dir) => {const engine = opts.getEngine();const id = `churn-${randomUUID().slice(0, 8)}`;@@ -372,4 +378,43 @@ export function defineTranscriptPartChurnCases(opts: { getEngine: () => BrainEngexpect(await liveParts(engine, baseSlugOf(tiny))).toEqual([]);expect(await liveParts(engine, baseSlugOf(many))).toEqual([]);}), 180_000);++ test('on a managed brain with a checkout, a remote put_page of transcript_import (first-write provenance kept) never steers the layout', () =>+ managedBrain(async ({ engine, ctx }) => withDir(async (dir) => {+ const managedIngest = (path: string) => runTranscriptsIngest(engine, { paths: [path], sourceId: 'default', context: ctx, ...NO_PATTERNS });+ const one = `managed-one-${randomUUID().slice(0, 8)}`;+ const split = `managed-split-${randomUUID().slice(0, 8)}`;+ const oneMessages = regular(30);+ const splitText = Array.from({ length: 20_000 }, (_, i) => `tok-${String(i).padStart(5, '0')}`).join(',');+ expect((await managedIngest(writeSession(dir, one, oneMessages))).pages).toMatchObject({ imported: 1, errored: 0 });+ await engine.setConfig('pages.max_bytes', '60000');+ try {+ expect((await managedIngest(writeSession(dir, split, [{ text: splitText }]))).pages).toMatchObject({ imported: 4, errored: 0 });+ } finally {+ await engine.unsetConfig('pages.max_bytes');+ }+ const splitBefore = await liveParts(engine, baseSlugOf(split));+ expect(splitBefore.map(p => p.frontmatter.transcript_import.part_bytes)).toEqual([54_000, 54_000, 54_000, 54_000]);++ await remoteRewriteImportMeta(engine, null, baseSlugOf(one), ti => { ti.part_bytes = 45_000; delete ti.of; });+ await remoteRewriteImportMeta(engine, null, baseSlugOf(split), ti => { ti.part_bytes = 240_000; });+ const stamps = await engine.executeRaw<{ via: string }>(+ 'SELECT ingested_via AS via FROM pages WHERE slug = ANY($1::text[]) ORDER BY slug', [[baseSlugOf(one), baseSlugOf(split)]]);+ expect(stamps).toEqual([{ via: 'cli:transcripts-ingest' }, { via: 'cli:transcripts-ingest' }]);++ const grownOne = await managedIngest(writeSession(dir, one, [...oneMessages, { text: 'small follow-up' }]));+ expect({ pages: grownOne.pages, partsDeleted: grownOne.partsDeleted, sessionsErrored: grownOne.sessionsErrored })+ .toEqual({ pages: { imported: 1, skipped: 0, errored: 0, planned: 0, pending: 0 }, partsDeleted: 0, sessionsErrored: 0 });+ const onePages = await liveParts(engine, baseSlugOf(one));+ expect(onePages.map(p => p.slug)).toEqual([baseSlugOf(one)]);+ expect(onePages[0]!.frontmatter.transcript_import).toEqual({ harness: 'openclaw', session_id: one, version: 1, part: 1, of: 1 });++ const grownSplit = await managedIngest(writeSession(dir, split, [{ text: splitText }, { text: 'small follow-up' }]));+ expect({ pages: grownSplit.pages, partsDeleted: grownSplit.partsDeleted, sessionsErrored: grownSplit.sessionsErrored })+ .toEqual({ pages: { imported: 2, skipped: 2, errored: 0, planned: 0, pending: 0 }, partsDeleted: 0, sessionsErrored: 0 });+ const splitAfter = await liveParts(engine, baseSlugOf(split));+ expect(splitAfter.map(p => p.slug)).toEqual(splitBefore.map(p => p.slug));+ expect(splitAfter.map(p => p.frontmatter.transcript_import.part_bytes)).toEqual([54_000, 54_000, 54_000, 54_000]);+ expect(splitAfter.slice(1, 3).map(p => p.hash)).toEqual(splitBefore.slice(1, 3).map(p => p.hash));+ }), { databaseUrl: opts.databaseUrl }), 300_000);}