Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(get_page): as_of reads segmented pages through the segment reader; verify guards (GBRA-217)
garrytan27473a0dcf7d
diff --git a/plugin-variants/gbrain-coding/skills/conventions/brain-first.md b/plugin-variants/gbrain-coding/skills/conventions/brain-first.mdindex 85c3071246..ce933bb8cd 100644--- a/plugin-variants/gbrain-coding/skills/conventions/brain-first.md+++ b/plugin-variants/gbrain-coding/skills/conventions/brain-first.md@@ -59,7 +59,7 @@ When you edit a page whose text takes effect on a date, keep its `valid_from`for a correction, or set a new quoted `valid_from` for a new edition. Read thewrite result's `valid_time` advisory and ask the user when it asks a question.Which record to use for a change in effect (edit in place, amendment record,-`supersedes` link): [page history](../../docs/guides/page-history.md#valid-time).+`supersedes` link): the page history guide (`docs/guides/page-history.md`, Valid time).## Identity needs an exact matchdiff --git a/plugin-variants/gbrain-daily/skills/conventions/brain-first.md b/plugin-variants/gbrain-daily/skills/conventions/brain-first.mdindex 85c3071246..ce933bb8cd 100644--- a/plugin-variants/gbrain-daily/skills/conventions/brain-first.md+++ b/plugin-variants/gbrain-daily/skills/conventions/brain-first.md@@ -59,7 +59,7 @@ When you edit a page whose text takes effect on a date, keep its `valid_from`for a correction, or set a new quoted `valid_from` for a new edition. Read thewrite result's `valid_time` advisory and ask the user when it asks a question.Which record to use for a change in effect (edit in place, amendment record,-`supersedes` link): [page history](../../docs/guides/page-history.md#valid-time).+`supersedes` link): the page history guide (`docs/guides/page-history.md`, Valid time).## Identity needs an exact matchdiff --git a/plugin/skills/conventions/brain-first.md b/plugin/skills/conventions/brain-first.mdindex 85c3071246..ce933bb8cd 100644--- a/plugin/skills/conventions/brain-first.md+++ b/plugin/skills/conventions/brain-first.md@@ -59,7 +59,7 @@ When you edit a page whose text takes effect on a date, keep its `valid_from`for a correction, or set a new quoted `valid_from` for a new edition. Read thewrite result's `valid_time` advisory and ask the user when it asks a question.Which record to use for a change in effect (edit in place, amendment record,-`supersedes` link): [page history](../../docs/guides/page-history.md#valid-time).+`supersedes` link): the page history guide (`docs/guides/page-history.md`, Valid time).## Identity needs an exact matchdiff --git a/scripts/check-core-guard-coverage.mjs b/scripts/check-core-guard-coverage.mjsindex 2c29ed7e7e..70f6bd101d 100644--- a/scripts/check-core-guard-coverage.mjs+++ b/scripts/check-core-guard-coverage.mjs@@ -35,6 +35,7 @@ const EXEMPT = {'src/core/persistence/connector-google-receipts.ts': 'connector receipt rows, not page text','src/core/persistence/projection-reindex.ts': 'rebuilds derived projections; page text is unchanged','src/core/persistence/change-reason.ts': 'wraps the PreparedMutation preparePageMutation returned (service.ts) in place: the core guard, exclusiveSources and every other field are the guarded object\'s own',+ 'src/core/persistence/valid-time-advisory.ts': 'wraps the PreparedMutation withChangeReason returned (service.ts) in place: its apply only adds the read-only valid_time advisory to the outcome after the guarded apply; the core guard, exclusiveSources and every other field are the guarded object\'s own','src/core/persistence/noop-kernel.ts': 'decides that nothing would change; publishes nothing','src/core/generations/repair.ts': 'the managed restore of a database-only generation (chronicle event pages, never core pages) revives and retires derived items through the adapter inside the coordinated request','src/core/generations/managed.ts': 'the generation activation flips the derived ledger; it writes no page text (its member page writes go through preparePageMutation)',diff --git a/scripts/check-engine-sql-dynamic.ts b/scripts/check-engine-sql-dynamic.tsindex 05f94b03cc..5ab68b5d2f 100644--- a/scripts/check-engine-sql-dynamic.ts+++ b/scripts/check-engine-sql-dynamic.ts@@ -56,6 +56,7 @@ const VETTED_BUILDERS: Record<string, string> = {buildRecencyComponentSql: 'src/core/search/sql-ranking.ts: inlines LIKE literals + numeric coefficients from the decay map, as master (planner behavior)',privatePagesFilterFragment: 'src/core/search/private-visibility.ts: constant visibility predicate over a caller alias',replacedBecauseSql: 'src/core/engine-sql/pages.ts: constant GBRA-217 reason projection over a caller alias; the boolean picks one of two constant texts',+ validDateSql: 'src/core/valid-time.ts: constant GBRA-217 date normaliser over a caller column expression; engine-sql passes only constant pv.frontmatter keys',quarantineFilterFragment: 'src/core/quarantine.ts: constant quarantine predicate over a caller alias',currentCodeEdgeFilter: 'src/core/code-intel/read-scope.ts: constant current-edge predicate over a caller alias',buildCJKKeywordSql: 'src/core/search/cjk-keyword-sql.ts: binds the query as params; shared by both engines',diff --git a/scripts/page-body-readers-baseline.tsv b/scripts/page-body-readers-baseline.tsvindex c356a98ed5..e20a4d042d 100644--- a/scripts/page-body-readers-baseline.tsv+++ b/scripts/page-body-readers-baseline.tsv@@ -12,6 +12,7 @@# lead (boundedBodyPrefixSql), body_bytes or content_hash instead.# docs/TESTING.md#page-body-readerssrc/cli/main.ts formatResult field STREAM renders a get_page result body; segmented bodies stream in PR 2+src/cli/page-render.ts asOfExitCode field NONE not the page body: tests whether a get_page as_of reply carries compiled_truth (a wire result, not a Page); a segmented edition replies with window, tested firstsrc/cli/page-render.ts formatGetPage call:serializeMarkdown SEGWsrc/cli/page-render.ts formatGetPage field STREAMsrc/commands/brainstorm.ts runBrainstormCli call:serializeMarkdown SEGW@@ -350,6 +351,13 @@ src/core/ops/get-page-projection.ts projectGetPage field STREAM segmented page:src/core/ops/known-as-of.ts getVersionsKnownAsOf field STREAM known_as_of read: a segmented version or page returns body segmented with body_ref (window read via get_page version_id), never a body string; inline bodies onlysrc/core/ops/known-as-of.ts intervalView field STREAM known_as_of read: a segmented version or page returns body segmented with body_ref (window read via get_page version_id), never a body string; inline bodies onlysrc/core/ops/pages.ts stripPrivacyFencesForRemoteReader field STREAM segmented page: getter throws page_body_segmented+src/core/ops/valid-time-read.ts bodyKey sql META body identity in SQL only: md5 over an inline row's body columns, content_hash for a segmented row (its body columns are NULL); no text leaves the database+src/core/ops/valid-time-read.ts editionView call:pageDocument INLINE inline editions only; a segmented edition is windowed through openSegmentedBody / segmentedReadDocument+src/core/ops/valid-time-read.ts editionView field INLINE inline editions only; a segmented edition is windowed through openSegmentedBody / segmentedReadDocument+src/core/ops/valid-time-read.ts loadEdition field INLINE the text branch runs only for an inline current page (isSegmentedPage); a segmented edition carries its generation for the segment reader+src/core/ops/valid-time-read.ts loadEdition sql INLINE a segmented version's body columns are NULL; it is read by generation through the segment reader in editionView+src/core/ops/valid-time-read.ts pick sql META size only: octet_length of an inline version's body columns (segmented versions are counted by body_storage); no text leaves the database+src/core/ops/valid-time-read.ts validFromEdit call:serializePageToMarkdown NONE not the page body: renders only the frontmatter head of an object built from slug, type, title and frontmatter with empty body fields, so a segmented page's getters are never readsrc/core/output/post-write.ts runPostWriteLint field INLINEsrc/core/output/validators/link.ts linkValidator field INLINEsrc/core/output/validators/triple-hr.ts tripleHrValidator field INLINE@@ -498,6 +506,8 @@ src/core/persistence/sync-prepare.ts prepareManagedSyncCode field INLINE code pasrc/core/persistence/sync-prepare.ts prepareSyncMutation call:serializePageToMarkdown SEGW lane 1d filesrc/core/persistence/sync-prepare.ts prepareSyncMutation field SEGW lane 1d file: preserveProtectedTakes over fenceBody (an unread body is fence-free)src/core/persistence/takes-prepare.ts prepare call:serializePageToMarkdown SEGW+src/core/persistence/valid-time-advisory.ts bodyKey field INLINE text compare for inline pages only; a segmented page compares content_hash, which also covers frontmatter, so its date-only edit reads as a body change+src/core/persistence/valid-time-advisory.ts withValidTimeAdvisory sql INLINE reads the written page's body columns, NULL for a segmented page (bodyKey then compares content_hash)src/core/persistence/writer-guard-schema.ts MANAGED_WRITER_GUARD_FUNCTION_SQL sql STREAM managed-writer guard tuple (lane 1a adds body_generation)src/core/pglite-engine.ts PGLiteEngine.putPage call:putPage SEGW delegation to engine-sql putPagesrc/core/pglite-engine.ts PGLiteEngine.refreshPageBody call:refreshPageBody SEGW delegation to engine-sql refreshPageBodydiff --git a/skills/conventions/brain-first.md b/skills/conventions/brain-first.mdindex 85c3071246..ce933bb8cd 100644--- a/skills/conventions/brain-first.md+++ b/skills/conventions/brain-first.md@@ -59,7 +59,7 @@ When you edit a page whose text takes effect on a date, keep its `valid_from`for a correction, or set a new quoted `valid_from` for a new edition. Read thewrite result's `valid_time` advisory and ask the user when it asks a question.Which record to use for a change in effect (edit in place, amendment record,-`supersedes` link): [page history](../../docs/guides/page-history.md#valid-time).+`supersedes` link): the page history guide (`docs/guides/page-history.md`, Valid time).## Identity needs an exact matchdiff --git a/skills/skills.lock.json b/skills/skills.lock.jsonindex 3cfe5eefcb..c250fb3d1d 100644--- a/skills/skills.lock.json+++ b/skills/skills.lock.json@@ -45,7 +45,7 @@"context-audit/SKILL.md": "6d786629d40544ddaab4f4e6e333569d270bcb8b581589dc16fb9f8bcb4f6207","context-audit/routing-eval.jsonl": "fb1832e24cc1b04163a74c5cde72bca53050a66246ca902e1a5f40303f52b5ab","conventions/agent-operator-protocol.md": "6ea87d9c0f1084e2982399064b6604bb77ee8aefcdefc45fe34f4e4ca9479020",- "conventions/brain-first.md": "b5cdb455336c69219423d1815fabbe119f3fb955dd9b8466c6fcdebc46d3daa1",+ "conventions/brain-first.md": "38dddff3a830de260183181a676ba1bf59f712375461ca0b9455b9d6d0a2845b","conventions/brain-routing.md": "392998d9a109b330c9225af4ca5c8798b0ff02eba4d441c93fdb7c263687d0c6","conventions/calibration.md": "500dc26bd7c8400f50dc4c16fd83f1a588f3e7e68c59050a21fd8a0f69e4d198","conventions/cron-via-minions.md": "badb1cd6cd825d6f1ac0b6b28cc47e5d80facc783a3e59a14146ae901ee0f933",diff --git a/src/core/ops/valid-time-read.ts b/src/core/ops/valid-time-read.tsindex 8c70fc5d24..08719b727b 100644--- a/src/core/ops/valid-time-read.ts+++ b/src/core/ops/valid-time-read.ts@@ -25,6 +25,7 @@ import { serializePageToMarkdown } from '../markdown.ts';import { pageDocument } from '../page-window/document.ts';import { DEFAULT_WINDOW_BYTES, MAX_WINDOW_BYTES, decodeCursor, encodeCursor, totalLines, windowFrom, type WindowSlice } from '../page-window/window.ts';import { openSegmentedBody } from '../page-body/read-range.ts';+import { isSegmentedPage } from '../page-body/page-shape.ts';import { segmentedReadDocument } from '../page-window/segmented.ts';import { PAGE_INLINE_MAX_BYTES } from '../page-size-policy.ts';import { LARGE_PAGE_VERSIONS_KEPT } from '../page-body/limits.ts';@@ -179,7 +180,7 @@ async function amendmentsNotApplied(tx: BrainEngine, pageId: number, editionFrom/** The serialized frontmatter edit that sets valid_from to the `<DATE>` placeholder: the existing line, or a new first key. */function validFromEdit(page: Page, tags: string[]): { old_text: string; new_text: string } | null {- const head = serializePageToMarkdown({ ...page, compiled_truth: '', timeline: '' }, tags);+ const head = serializePageToMarkdown({ slug: page.slug, type: page.type, title: page.title, frontmatter: page.frontmatter, compiled_truth: '', timeline: '' } as Page, tags);const close = head.indexOf('\n---', 4);const fm = head.slice(0, close < 0 ? head.length : close + 1);const line = fm.split('\n').find(l => l.startsWith('valid_from:'));@@ -226,9 +227,9 @@ async function loadEdition(tx: BrainEngine, identity: Identity, row: PickRow): Pif (!snap) return null;const current = { page: snap.page, tags: snap.tags, revision: snap.revision };if (row.version_id === null) {- const p = snap.page;+ const p = snap.page, segmented = isSegmentedPage(p);return { current, edition: { versionId: null, title: p.title, type: p.type, tags: snap.tags, frontmatter: (p.frontmatter ?? {}) as Record<string, unknown>,- compiled_truth: p.compiled_truth ?? '', timeline: p.timeline ?? '', revision: snap.revision, segmented: row.segmented, generation: snap.bodyGeneration } };+ compiled_truth: segmented ? '' : p.compiled_truth ?? '', timeline: segmented ? '' : p.timeline ?? '', revision: snap.revision, segmented, generation: snap.bodyGeneration } };}const [v] = await tx.executeRaw<Record<string, unknown>>(`SELECT id, title, type, tags, frontmatter, compiled_truth, timeline, knowledge_revision::text AS revision,body_storage, body_generation FROM page_versions WHERE id = $1 AND page_id = $2`, [row.version_id, identity.id]);diff --git a/test/valid-time-gbra217.test.ts b/test/valid-time-gbra217.test.tsindex 2798c3bf29..10626e59ad 100644--- a/test/valid-time-gbra217.test.ts+++ b/test/valid-time-gbra217.test.ts@@ -26,6 +26,7 @@ import { exitCodeForCode } from '../src/core/error-catalogue.ts';import { asOfExitCode, formatGetPage, validTimeLine } from '../src/cli/page-render.ts';import { utcToday } from '../src/core/link-validity.ts';import { testBackends, requirePostgresTestDatabase } from './helpers/test-backends.ts';+import { importSegmented } from './helpers/segmented-privacy-fixture.ts';type R = Record<string, any>;const outcomeOf = (r: R) => (r.outcome ?? r) as R;@@ -378,6 +379,7 @@ for (const backend of testBackends()) {await engine.executeRaw("INSERT INTO page_versions (page_id, compiled_truth, frontmatter, timeline, title, type, tags) SELECT $1, 'Edition ' || g, jsonb_build_object('valid_from', to_char(date '2000-01-01' + g * 7, 'YYYY-MM-DD')), '', 'Policy', 'note', '[]'::jsonb FROM generate_series(1, 500) g", [id]);const seen: string[] = [];const transaction = engine.transaction.bind(engine);+ const own = Object.getOwnPropertyDescriptor(engine, 'transaction');(engine as { transaction: unknown }).transaction = (fn: (tx: BrainEngine) => Promise<unknown>) => transaction(async tx => {const exec = tx.executeRaw.bind(tx);(tx as { executeRaw: unknown }).executeRaw = (sql: string, params?: unknown[]) => { seen.push(sql); return exec(sql, params as never); };@@ -390,11 +392,35 @@ for (const backend of testBackends()) {const t0 = performance.now();r = await read(slug, '2005-06-01');ms = performance.now() - t0;- } finally { (engine as { transaction: unknown }).transaction = transaction; }+ } finally {+ if (own) Object.defineProperty(engine, 'transaction', own);+ else delete (engine as { transaction?: unknown }).transaction;+ }expect(seen.filter(s => s.includes('WITH rows AS'))).toHaveLength(1);const days = Math.floor((Date.UTC(2005, 5, 1) - Date.UTC(2000, 0, 1)) / 86_400_000 / 7) * 7;expect(r.valid_time).toMatchObject({ status: 'in_force', valid_from: new Date(Date.UTC(2000, 0, 1) + days * 86_400_000).toISOString().slice(0, 10) });expect(ms).toBeLessThan(2_000);}, 60_000);++ test('B-T9: a page stored in segments reads its edition through the segment reader and gets the date fix', async () => {+ const big = (fm: string[]) => page(Array.from({ length: 12_000 }, (_, i) => `Clause ${i}: refunds follow the policy of acme-example. ${'x'.repeat(40)}`).join('\n'), fm);+ const dated = fresh('segmented');+ const undated = fresh('segmented-undated');+ try {+ await importSegmented(engine, dated, big(["valid_from: '2026-01-01'"]));+ await importSegmented(engine, undated, big([]));+ } finally { await engine.setConfig('pages.segmented_storage', 'off'); }++ const r = await read(dated, '2026-03-01');+ expect(r.valid_time).toMatchObject({ status: 'in_force', chosen_is_current: true, valid_from: '2026-01-01' });+ expect(r.body).toBe('window');+ expect(r.compiled_truth).toBeUndefined();+ expect(r.window.text).toContain('Clause 0: refunds');+ expect(r.next.arguments).toMatchObject({ slug: dated, as_of: '2026-03-01' });++ const e = await refusal(read(undated, '2026-03-01'));+ expect(e?.code).toBe('valid_time_undeclared');+ expect(JSON.stringify(e?.fix ?? (e as R)?.detail?.fix)).toContain("valid_from: '<DATE>'");+ }, 300_000);});}