Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
Wave B lane 1e: merge-1a follow-ups (segmented detection until the snapshot projects body_storage, page-body ratchet markers, budget junk-window test)
garrytan57d097b5347a
diff --git a/src/core/engine-sql/page-body.ts b/src/core/engine-sql/page-body.tsindex bcd222f1ec..a15a64328b 100644--- a/src/core/engine-sql/page-body.ts+++ b/src/core/engine-sql/page-body.ts@@ -175,6 +175,7 @@ export async function stageSegmentChunks(exec: SqlExecutor, pageId: number, gene// Lock-census: COMPLIANT — key is the page id, unique brain-wide.await tx.run(sqlFragment`SELECT pg_advisory_xact_lock(hashtextextended('gbrain:page-body-chunks:' || ${pageId}::text, 0))`);}+ // chunk-visibility-ok: chunk_index is never reused, so the next index is past every row, staged and retired includedconst { rows } = await tx.run<{ next: unknown }>(sqlFragment`SELECT COALESCE(MAX(chunk_index), -1) + 1 AS next FROM content_chunks WHERE page_id = ${pageId}`);const first = Number(rows[0]?.next ?? 0);const indexes = chunks.map((_, i) => first + i);@@ -269,6 +270,7 @@ export async function flipBodyGeneration(exec: SqlExecutor, input: BodyFlipInputc.occurrence_id = ANY(${[...input.retireChunkOccurrences]}::bigint[])OR (${input.retireInlineChunks === true}::boolean AND c.body_generation IS NULL)OR (c.body_generation = ${input.newGeneration}::bigint AND c.occurrence_id NOT IN ${stagedOccurrences}))`;+ // chunk-visibility-ok: the flip itself selects the rows it retires, across generationsconst { rows: counted } = await tx.run<{ n: unknown }>(sqlFragment`SELECT count(*)::bigint AS n FROM content_chunks c WHERE ${retire}`);const toRetire = Number(counted[0]?.n ?? 0);const retireDeferred = toRetire > input.retireMaxRows;diff --git a/src/core/page-state/projections.ts b/src/core/page-state/projections.tsindex f7c3a049cc..877e0c8909 100644--- a/src/core/page-state/projections.ts+++ b/src/core/page-state/projections.ts@@ -17,6 +17,7 @@ import { jsonRowBatches } from '../batch-rows.ts';import { refreshProjectionStatistics } from '../search/projection-statistics.ts';import { belowSafeChunkFence, movableChunkSql } from '../search/safe-chunks.ts';import { buildSegmentedProjection } from '../page-body/projection.ts';+import { isSegmentedSnapshotPage } from './versions.ts';import { acceptedEmbeddingInputHashes, embeddingInputHash, plainEmbeddingTier, synopsisBodyHash,type EmbeddingInputContext, type EmbeddingTier } from '../embedding-input-hash.ts';@@ -141,11 +142,6 @@ async function indexingContext(engine: BrainEngine, snapshot: PageSnapshot, maxCcorpusGeneration: projection?.corpus_generation ?? null };}-/** Wave B: a segmented page's snapshot carries no body strings (lane 1c's `isSegmentedPage` shape). */-function segmentedSnapshot(snapshot: PageSnapshot): boolean {- return (snapshot.page as { body_storage?: unknown }).body_storage === 'segmented';-}-/*** A short guarded read binds the exact chunk set and title/body revision.* Null for a segmented page: its projection is `buildSegmentedProjection` and@@ -163,7 +159,7 @@ export async function readProjectionSnapshot(engine: BrainEngine, slug: string,async function readGuardedProjectionSnapshot(tx: BrainEngine, slug: string, sourceId: string,opts: { allowUnsealed?: boolean; maxChunkTokens?: number; requireLiveSource?: boolean }): Promise<ProjectionSnapshot | null> {const snapshot = await tx.readPageSnapshot(slug, { sourceId, ...(opts.requireLiveSource && { requireLiveSource: true }) });- if (!snapshot || segmentedSnapshot(snapshot) || (!opts.allowUnsealed && snapshot.page.text_projection_revision !== snapshot.revision)) return null;+ if (!snapshot || isSegmentedSnapshotPage(snapshot.page) || (!opts.allowUnsealed && snapshot.page.text_projection_revision !== snapshot.revision)) return null;const context = await indexingContext(tx, snapshot, opts.maxChunkTokens);const fenceOverlay = context.pageKind === 'markdown' ? await loadFenceChunkOverlay(tx, { sourceId, slug, compiled_truth: snapshot.page.compiled_truth, timeline: snapshot.page.timeline }) : undefined;return { snapshot, chunks: await tx.getChunks(slug, { sourceId, includeUnsealed: true }), indexingContext: context.key,@@ -292,7 +288,7 @@ export async function installPageEmbeddings(engine: BrainEngine, prepared: Projeawait tx.lockPageKeys([{ sourceId, slug }]);const current = await tx.readPageSnapshot(slug, { sourceId });if (!current || current.page.deleted_at || current.sourceIncarnation !== snapshot.sourceIncarnation || current.page.id !== snapshot.page.id- || current.page.text_projection_revision !== current.revision || segmentedSnapshot(current)) return refused;+ || current.page.text_projection_revision !== current.revision || isSegmentedSnapshotPage(current.page)) return refused;const [source] = await tx.executeRaw<{ archived: boolean }>('SELECT archived FROM sources WHERE id=$1', [sourceId]);if (!source || source.archived) return refused;const context = await indexingContext(tx, current, prepared.maxChunkTokensOverride);diff --git a/src/core/page-state/versions.ts b/src/core/page-state/versions.tsindex 0f0c0c047e..14a1c41bd5 100644--- a/src/core/page-state/versions.ts+++ b/src/core/page-state/versions.ts@@ -16,7 +16,7 @@ export { LARGE_PAGE_VERSIONS_KEPT };export async function createPageVersion(engine: BrainEngine, slug: string, sourceId: string, preimage?: PageSnapshot): Promise<PageVersion> {const insert = async (tx: BrainEngine, snapshot: PageSnapshot) => {const { page, tags, revision } = snapshot;- if ((page as { body_storage?: unknown }).body_storage === 'segmented') return insertSegmentedVersion(tx, snapshot);+ if (isSegmentedSnapshotPage(page)) return insertSegmentedVersion(tx, snapshot);const rows = await tx.executeRaw<PageVersion>(`INSERT INTO page_versions(page_id,compiled_truth,frontmatter,knowledge_revision,timeline,title,type,tags,is_deleted,source_path)VALUES ($1,$2,$3::text::jsonb,$4::uuid,$5,$6,$7,$8::text::jsonb,$9,$10) RETURNING *`,@@ -37,6 +37,17 @@ export async function createPageVersion(engine: BrainEngine, slug: string, sourc});}+/**+ * A segmented page row: `body_storage` once the snapshot projects it (lane+ * 1c's page shape), else the NULL body only a segmented row stores+ * (`pages_body_storage_chk`). `body_storage` is read first, so lane 1c's body+ * getters never fire here.+ */+export function isSegmentedSnapshotPage(page: PageSnapshot['page']): boolean {+ const storage = (page as { body_storage?: unknown }).body_storage;+ return storage === undefined ? page.compiled_truth == null : storage === 'segmented';+}+/*** Wave B (spec 5): a segmented page's version is a reference, not a copy: the* page's live body generation (its manifest rows stay alive as a GC root),diff --git a/test/large-pages/segmented-embedding.test.ts b/test/large-pages/segmented-embedding.test.tsindex cda7449c4f..fa5004ec4d 100644--- a/test/large-pages/segmented-embedding.test.ts+++ b/test/large-pages/segmented-embedding.test.ts@@ -5,7 +5,9 @@* alone (chunk text, title, plain tier): never a segment or body read,* never a staged or retired row; an append's effect (`occurrenceIds`)* embeds only the new occurrences' rows; `embedStalePages` routes a- * segmented page here; each installed vector records its input hash.+ * segmented page here; each installed vector records its input hash; the+ * per-page budget meters a large segmented page by body_bytes and its junk+ * check samples windows from segments.* 2. Fails when: the sweep reads the body or every chunk of a segmented page,* embeds rows outside the live generation, or widens an append's effect.* 3. Runs on PGLite, and on Postgres when DATABASE_URL is set.@@ -49,6 +51,7 @@ for (const kind of testBackends()) {embedded = [];await engine.executeRaw('DELETE FROM pages');await engine.executeRaw('DELETE FROM page_segment_texts');+ await engine.executeRaw('DELETE FROM page_embedding_budget');await segmentPage(engine, SLUG, {generation: 2,title: TITLE,@@ -89,6 +92,21 @@ for (const kind of testBackends()) {expect(await vectored()).toEqual(['appended row', 'first live row', 'second live row']);});+ test('the per-page budget meters a large segmented page by body_bytes and samples junk from its segments', async () => {+ const markup = '<div class="x"><span data-a="1"></span></div>'.repeat(2000);+ await segmentPage(engine, 'notes/segmented-junk', { generation: 1, bodyBytes: 4 * 1024 * 1024,+ occurrences: [{ id: 1, byteStart: 0, genFrom: 1, chunks: [{ text: markup }] }] });+ const junk = (await readSegmentedEmbedPage(engine, { sourceId: 'default', slug: 'notes/segmented-junk' }))!;+ expect(await embedSegmentedPage(engine, junk, { embedFn })).toEqual({ embedded: 0, complete: false, stopped: 'budget' });+ const [held] = await engine.executeRaw<{ state: string }>('SELECT state FROM page_embedding_budget WHERE page_id = $1', [junk.id]);+ expect(held!.state).toBe('held');+ const prose = 'An ordinary paragraph about herons wading in the marsh at dawn. '.repeat(200);+ await segmentPage(engine, 'notes/segmented-prose', { generation: 1, bodyBytes: 4 * 1024 * 1024,+ occurrences: [{ id: 1, byteStart: 0, genFrom: 1, chunks: [{ text: prose }] }] });+ const page = (await readSegmentedEmbedPage(engine, { sourceId: 'default', slug: 'notes/segmented-prose' }))!;+ expect(await embedSegmentedPage(engine, page, { embedFn })).toEqual({ embedded: 1, complete: true });+ });+test('an inline page is not a segmented embed page', async () => {await engine.putPage('notes/inline-embed', { type: 'note', title: 'Inline', compiled_truth: 'Inline body.', timeline: '', frontmatter: {} });expect(await readSegmentedEmbedPage(engine, { sourceId: 'default', slug: 'notes/inline-embed' })).toBeNull();