Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(transcripts): an unchanged transcript part takes no write request id on a managed brain (#6741)

garrytan288a46aca77a
diff --git a/src/core/persistence/put-page-screen.ts b/src/core/persistence/put-page-screen.ts
new file mode 100644
index 0000000000..fa714f83b4
--- /dev/null
+++ b/src/core/persistence/put-page-screen.ts
@@ -0,0 +1,54 @@
+/**
+ * #6741 B: the request-free no-op screen for a trusted local `put_page`
+ * (the managed transcript import). It builds the admission the write would
+ * take, without admitting it, runs the page publication preparer on that
+ * unadmitted request and asks the #5470 no-op kernel (noop-kernel.ts), as the
+ * managed file import does (import-mutations.ts unchangedManagedImport). The
+ * write skips admission, and so takes no permanent request id, only when the
+ * preparer finds a genuine no-op and the kernel finds no work the publication
+ * would still do: no safe-chunk re-seal or text projection behind the
+ * revision, the page still at the screened revision, its recorded source path
+ * the one the publication would record, and its canonical file present. The
+ * file may differ in bytes from the serialized page only as the preparer
+ * already accepted it (it parses to this page; key order from the stored
+ * frontmatter differs), which a no-op publication never rewrites, so that one
+ * kernel waiver applies; a missing file always admits. The preparer's own
+ * `validate` must hold. Anything else is submitted as before:
+ * - a page with a request still pending or recovering (the stored page is
+ * not yet what that request will publish);
+ * - a segmented (large) page: its publication decides the no-op;
+ * - a missing, deleted or changed page, or any failure of the screen.
+ */
+import type { OperationContext } from '../ops/contract.ts';
+import type { PageSnapshot } from '../page-state/types.ts';
+import { isSegmentedPage } from '../page-body/page-shape.ts';
+import { loadConfig } from '../config.ts';
+import { scannerSlugRootMode, scannerSourcePath } from '../write-through.ts';
+import { inspectUnchanged, screeningRequest } from './noop-kernel.ts';
+import { preparePageAdmission } from './page-mutations.ts';
+import { preparePageMutation } from './page-prepare.ts';
+
+export async function unchangedPutPage(ctx: OperationContext, params: Record<string, unknown> & { slug: string; source_id: string },
+ snapshot: PageSnapshot | null): Promise<boolean> {
+ if (!snapshot || snapshot.page.deleted_at || isSegmentedPage(snapshot.page)) return false;
+ try {
+ const [pending] = await ctx.engine.executeRaw(`SELECT 1 FROM persistence_requests WHERE source_id=$1 AND slug=$2 AND intent IS NOT NULL AND NOT compacted
+ AND (state NOT IN ('committed','conflict','failed','cancelled') OR recovery IS NOT NULL) LIMIT 1`, [params.source_id, params.slug.toLowerCase()]);
+ if (pending) return false;
+ const prepared = await preparePageAdmission(ctx, { operation: 'put_page', params });
+ if (prepared.prior) return false;
+ const { admission } = prepared;
+ const row = screeningRequest({ source_id: admission.sourceId, source_incarnation: admission.sourceIncarnation, slug: admission.slug,
+ page_id: admission.pageId ?? null, worktree_id: admission.worktreeId ?? null, authority: admission.authority, intent: admission.intent, operation: 'put_page' });
+ const mutation = await preparePageMutation(ctx.engine, row, ctx.config ?? loadConfig() ?? { engine: ctx.engine.kind });
+ if (mutation.noop !== true) return false;
+ const file = row.worktree_id ? mutation.file : undefined;
+ const sourcePath = file ? scannerSourcePath(file.root, file.path, await scannerSlugRootMode(ctx.engine, admission.sourceId, file.root)) : null;
+ const verdict = await inspectUnchanged(ctx.engine, { prepared: mutation, snapshot, sourcePath, databaseOnly: !file, waive: ['canonical_file_differs'] });
+ if (verdict.admitReason) return false;
+ await mutation.validate?.(ctx.engine);
+ return true;
+ } catch {
+ return false;
+ }
+}
diff --git a/src/core/transcripts/ingest.ts b/src/core/transcripts/ingest.ts
index fb3495a0d4..c3b2bc119a 100644
--- a/src/core/transcripts/ingest.ts
+++ b/src/core/transcripts/ingest.ts
@@ -33,6 +33,7 @@ import { importFromContent } from '../import-file.ts';
import type { OperationContext } from '../ops/contract.ts';
import { managedPersistenceEnabled } from '../persistence/ownership.ts';
import { submitPageMutation } from '../persistence/page-mutations.ts';
+import { unchangedPutPage } from '../persistence/put-page-screen.ts';
import { canonicalJson } from '../remediation-step.ts';
import type { FileDiagnostics, TranscriptAdapter, TranscriptFormat } from './types.ts';
import { detectAdapter } from './detect.ts';
@@ -478,7 +479,9 @@ export async function runTranscriptsIngest(
* submitted as a `put_page` write request: the same importer runs behind the
* coordinator, naming the current revision so a replacement is never a blind
* overwrite (no revision means create-only). Embedding is deferred there, as
- * for every coordinated page write.
+ * for every coordinated page write. #6741 B: a part whose publication would
+ * change nothing takes no admission (put-page-screen.ts), so an unchanged
+ * re-ingest burns no permanent request id.
*/
async function submitTranscriptPart(
ctx: OperationContext,
@@ -488,11 +491,10 @@ async function submitTranscriptPart(
provenance: { source_kind: string; source_uri: string; ingested_via: string },
): Promise<{ slug: string; status: 'imported' | 'skipped' | 'error' }> {
const snapshot = await engine.readPageSnapshot(part.slug, { sourceId, includeDeleted: true });
- const receipt = await submitPageMutation(ctx, {
- operation: 'put_page',
- params: { slug: part.slug, content: part.content, source_id: sourceId, ...provenance,
- ...(snapshot?.revision ? { expected_revision: snapshot.revision } : {}) },
- });
+ const params = { slug: part.slug, content: part.content, source_id: sourceId, ...provenance,
+ ...(snapshot?.revision ? { expected_revision: snapshot.revision } : {}) };
+ if (await unchangedPutPage(ctx, params, snapshot)) return { slug: part.slug, status: 'skipped' };
+ const receipt = await submitPageMutation(ctx, { operation: 'put_page', params });
const slug = typeof receipt.slug === 'string' && receipt.slug ? receipt.slug : part.slug;
if (receipt.state !== 'committed') return { slug, status: 'error' };
return { slug, status: receipt.noop === true || receipt.status === 'skipped' ? 'skipped' : 'imported' };
diff --git a/test/transcripts-managed-noop.test.ts b/test/transcripts-managed-noop.test.ts
new file mode 100644
index 0000000000..03f3f973e5
--- /dev/null
+++ b/test/transcripts-managed-noop.test.ts
@@ -0,0 +1,153 @@
+/**
+ * #6741 B: on a writer-claimed brain, a transcript part whose page would not
+ * change takes no admission, so it burns no permanent request id. The screen is
+ * the publication preparer on an unadmitted request judged by the #5470 no-op
+ * kernel; anything the publication would still do admits as before.
+ *
+ * Fails when: an unchanged re-ingest admits a put_page (one permanent id per
+ * part per run), or when the skip hides pending work: a text projection behind
+ * the page revision, chunks below the safe-chunk fence, a missing canonical file,
+ * a recorded source path the publication would not record, or a canonical file
+ * edited outside coordination.
+ */
+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
+import { mkdirSync, mkdtempSync, readFileSync, rmSync, unlinkSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { makeContext } from '../src/cli/main.ts';
+import { runTranscriptsIngest } from '../src/core/transcripts/ingest.ts';
+import { claimWorktree } from '../src/core/persistence/ownership.ts';
+import { registerLocalWriter } from '../src/core/persistence/identity.ts';
+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
+import { rebuildPendingPageProjections } from '../src/core/page-state/projections.ts';
+import { resetPgliteState } from './helpers/reset-pglite.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+const SOURCE = 'transcripts-managed';
+let engine: PGLiteEngine;
+let dir: string;
+let root: string;
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+}, 120_000);
+
+afterAll(async () => {
+ await disposePersistenceConsumer(engine);
+ await engine.disconnect();
+});
+
+const env = () => ({ GBRAIN_HOME: dir, GBRAIN_SOURCE: undefined, DATABASE_URL: undefined, GBRAIN_DATABASE_URL: undefined,
+ OPENAI_API_KEY: undefined, VOYAGE_API_KEY: undefined, ANTHROPIC_API_KEY: undefined });
+
+beforeEach(async () => {
+ await disposePersistenceConsumer(engine);
+ await resetPgliteState(engine);
+ dir = mkdtempSync(join(tmpdir(), 'gb-transcript-noop-'));
+ root = join(dir, 'brain');
+ mkdirSync(root);
+ await withEnv(env(), async () => {
+ await engine.executeRaw('INSERT INTO sources(id,name,local_path) VALUES($1,$1,$2)', [SOURCE, root]);
+ await registerLocalWriter(engine, 'cli');
+ await claimWorktree(engine, SOURCE, root);
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');
+ });
+ return () => rmSync(dir, { recursive: true, force: true });
+});
+
+function exportFile(): string {
+ const message = (role: string, t: number, text: string) => ({ author: { role }, create_time: t, content: { content_type: 'text', parts: [text] } });
+ const mapping = {
+ root: { id: 'root', parent: null, children: ['n1'], message: null },
+ n1: { id: 'n1', parent: 'root', children: ['n2'], message: message('user', 1786080005, 'A question about widget-co.') },
+ n2: { id: 'n2', parent: 'n1', children: [], message: message('assistant', 1786080015, 'An answer.') },
+ };
+ const path = join(dir, 'export.json');
+ writeFileSync(path, JSON.stringify([{ title: 'Managed no-op', create_time: 1786080000, update_time: 1786080015,
+ conversation_id: 'cgpt-noop-1', current_node: 'n2', mapping }]));
+ return path;
+}
+
+const ingest = (writeWaitMs?: number) => withEnv(env(), async () => {
+ const context = await makeContext(engine, { source: SOURCE, dry_run: false });
+ if (writeWaitMs !== undefined) context.writeWaitMs = writeWaitMs;
+ return runTranscriptsIngest(engine, { paths: [exportFile()], sourceId: SOURCE, format: 'chatgpt', context });
+});
+const admissions = async () => (await engine.executeRaw<{ n: number }>(
+ "SELECT count(*)::int AS n FROM persistence_requests WHERE source_id=$1 AND operation='put_page'", [SOURCE]))[0]!.n;
+const page = async () => (await engine.executeRaw<{ slug: string; source_path: string }>(
+ "SELECT slug, source_path FROM pages WHERE source_id=$1 AND deleted_at IS NULL AND slug LIKE 'conversations/%'", [SOURCE]))[0]!;
+async function drainProjections(): Promise<void> {
+ await disposePersistenceConsumer(engine);
+ for (let attempt = 0; attempt < 10; attempt++) {
+ const [{ n }] = await engine.executeRaw<{ n: number }>('SELECT count(*)::int AS n FROM page_projection_jobs');
+ if (n === 0) return;
+ await withEnv(env(), () => rebuildPendingPageProjections(engine));
+ }
+}
+async function imported(): Promise<{ slug: string; file: string }> {
+ expect((await ingest()).pages).toMatchObject({ imported: 1, errored: 0 });
+ expect(await admissions()).toBe(1);
+ await drainProjections();
+ const { slug, source_path } = await page();
+ return { slug, file: join(root, source_path) };
+}
+
+describe('#6741 B: an unchanged transcript part takes no admission', () => {
+ test('a current no-op re-ingest makes zero admissions', async () => {
+ await imported();
+ expect((await ingest()).pages).toMatchObject({ imported: 0, skipped: 1, errored: 0 });
+ expect((await ingest()).pages).toMatchObject({ imported: 0, skipped: 1, errored: 0 });
+ expect(await admissions()).toBe(1);
+ }, 120_000);
+
+ test('a page with a request still pending (not yet published) still submits', async () => {
+ const { slug } = await imported();
+ await engine.executeRaw("UPDATE persistence_requests SET state='queued', completed_at=NULL WHERE source_id=$1 AND slug=$2", [SOURCE, slug]);
+ // The new request waits behind the pending one; a short wait leaves it pending, which is enough here.
+ await ingest(1).catch(() => undefined);
+ expect(await admissions()).toBe(2);
+ }, 120_000);
+
+ test('a text projection behind the page revision still submits', async () => {
+ const { slug } = await imported();
+ await engine.executeRaw('UPDATE pages SET text_projection_revision=gen_random_uuid() WHERE source_id=$1 AND slug=$2', [SOURCE, slug]);
+ await ingest();
+ expect(await admissions()).toBe(2);
+ }, 120_000);
+
+ test('chunks below the safe-chunk fence still submit', async () => {
+ const { slug } = await imported();
+ await engine.executeRaw('UPDATE pages SET chunker_version=1 WHERE source_id=$1 AND slug=$2', [SOURCE, slug]);
+ await ingest();
+ expect(await admissions()).toBe(2);
+ }, 120_000);
+
+ test('a missing canonical file still submits', async () => {
+ const { file } = await imported();
+ unlinkSync(file);
+ // The publication refuses the write (the file was removed outside coordination); it is admitted, never skipped.
+ await ingest().catch(() => undefined);
+ expect(await admissions()).toBe(2);
+ }, 120_000);
+
+ test('canonical metadata drift (the page no longer records its file path) still submits', async () => {
+ const { slug } = await imported();
+ await engine.executeRaw('UPDATE pages SET source_path=NULL WHERE source_id=$1 AND slug=$2', [SOURCE, slug]);
+ await ingest().catch(() => undefined);
+ expect(await admissions()).toBe(2);
+ }, 120_000);
+
+ test('a canonical file edited outside coordination still submits', async () => {
+ const { file } = await imported();
+ const bytes = readFileSync(file, 'utf8');
+ const [, front, body] = /^---\n([\s\S]*?)\n---\n([\s\S]*)$/.exec(bytes)!;
+ // The frontmatter lines reversed: no longer the page the database holds.
+ writeFileSync(file, `---\n${front!.split('\n').reverse().join('\n')}\n---\n${body}`);
+ await ingest().catch(() => undefined);
+ expect(await admissions()).toBe(2);
+ }, 120_000);
+});