Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(large-pages): segmented file comparison sets aside the content gate's safety markers
garrytan7c0c4d53372d
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex 2b70f6e7a1..8572d34609 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -764,7 +764,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText }{ since: '0.60.290.0', text: '`revert_version` of a page stored in segments, or to a version stored in segments, is refused with `page_body_segmented` (reason `segmented_revert`) before anything is written; it arrives with the segment writer in a later release. With `pages.segmented_storage` on, this includes pages between 1 MiB and 24 MiB that `revert_version` restores today. The versions stay readable: `get_versions` lists them, and a versioned `get_page` window reads one. Write the content you want back with `put_page`.' },{ since: '0.60.290.0', text: 'Core memory and `gbrain repair frontmatter` on a page stored in segments (`pages.segmented_storage` on): a core page (`always_load: true`) stored in segments up to 24 MiB is now read back whole and rendered, budgeted and listed as its inline twin is; before, it counted as its title alone, and once a fact was withdrawn from it (or a `*` withdrawal existed in its source) session-start core, `context_pack`, `gbrain core status` and every core page write failed with `page_body_segmented`. A core page over 24 MiB is left out of core and doctor `core_memory` counts it (`skipped_segmented`), which now counts only those. `gbrain repair frontmatter --include-ambiguous` re-imports a page stored in segments up to 24 MiB whose title was derived from its slug, as it re-imports an inline page; over 24 MiB the file is listed `needs_review` with `page_body_segmented`, naming the 24 MiB limit, and nothing is written. Before, either case failed the whole preview.' },// Switch-on flip lane A (withdrawal mirror of segmented pages). `since` is 'TBD' until the merge-slot stamp.- { since: 'TBD', text: 'With `pages.segmented_storage` on, a withdrawal (`forget`, `forget_fact`, `purge_fact`) now rewrites the canonical file of a page stored in segments on a source backed by files, as it rewrites an inline page\'s: the file loses the withdrawn or purged row, its bytes are those `gbrain export` writes for the page, and the withdrawal\'s Git effect commits it. The file is streamed from the segments into its staging file one segment at a time, and its recovery record names that staging file by path and SHA-256 instead of holding the file; the file\'s prior bytes are read in pieces too. A streamed staging file (this mirror\'s, or `restore_page`\'s for a page over 24 MiB) is written under an in-progress name and renamed once complete, so one a crash cut short is discarded and written again instead of blocking the source\'s worktree with `unexpected_staging_bytes`. Before, the withdrawal-mirror and Git effects passed such a page by (`skipped` reason `page_body_segmented`) and its file kept the withdrawn text.' },+ { since: 'TBD', text: 'With `pages.segmented_storage` on, a withdrawal (`forget`, `forget_fact`, `purge_fact`) now rewrites the canonical file of a page stored in segments on a source backed by files, as it rewrites an inline page\'s: the file loses the withdrawn or purged row, its bytes are those `gbrain export` writes for the page, and the withdrawal\'s Git effect commits it. The file is streamed from the segments into its staging file one segment at a time, and its recovery record names that staging file by path and SHA-256 instead of holding the file; the file\'s prior bytes are read in pieces too. A streamed staging file (this mirror\'s, or `restore_page`\'s for a page over 24 MiB) is written under an in-progress name and renamed once complete, so one a crash cut short is discarded and written again instead of blocking the source\'s worktree with `unexpected_staging_bytes`. Before, the withdrawal-mirror and Git effects passed such a page by (`skipped` reason `page_body_segmented`) and its file kept the withdrawn text. The content gate\'s markers (`embed_skip`, `content_flag`, `quarantine`), which the database stores and the file does not, are now set aside when a page stored in segments is compared with its file, as they are for an inline page; before, any rewrite of a marked page\'s file (a withdrawal, delete, restore or tag change) was skipped or refused as `file_database_drift`.' },// FIFO claim foreground guard (fgp-park-before-claim, #6862).{ since: '0.60.271.0', text: 'A foreground write no longer loses to an idle drain\'s sync head. While a managed sync drains, a page write that may go ahead of the queued sync groups (none of them names its page) now holds back the next sync group even when the drain\'s lanes are idle and the write\'s own process is still claiming it; before, the drain could start a group in that moment and the write waited for it. The sync side still gets one group after each such write commits, so a stream of writes cannot stall it.' },// #6858 (GBRA-121; Garry: "take care of fixing" #6858 asks 1-5; ask 5 contained per GBRA-108). `since` is a placeholder equal to the branch's VERSION; the integrator sets it to the merge-slot stamp by hand.diff --git a/src/core/persistence/page-prepare.ts b/src/core/persistence/page-prepare.tsindex 6187d1e57e..cd66ff96ac 100644--- a/src/core/persistence/page-prepare.ts+++ b/src/core/persistence/page-prepare.ts@@ -210,7 +210,7 @@ function snapshotLedger(snapshot: PageSnapshot): BodyLedger {}/*** Wave B: `fileMatchesSnapshot` for a segmented page whose body was not read back (over the single-string ceiling).- * The same comparison with each body region replaced by its SHA-256 on both sides: the file's regions as the streamed+ * The same comparison (the gate's safety markers stripped on both sides) with each body region replaced by its SHA-256 on both sides: the file's regions as the streamed* importer's scan splits them, the stored ones from the trusted stored body (body-digests.ts), one segment at a time.* The withdrawal overlay leaves a body without a facts fence unchanged; a file whose body has one under a ledger* that applies cannot be overlaid streamed, so it refuses (`page_body_segmented`) instead of reading as drift.@@ -232,8 +232,8 @@ async function segmentedFileMatches(engine: BrainEngine, slug: string, bytes: Byconst parsed = { ...file.parsed, compiled_truth: fileDigests.truth, timeline: fileDigests.timeline };const type = importedFileType(parsed, snapshot.page, inferred);stored ??= await storedBodyDigests(engine, Number(snapshot.page.id), ledger);- return digest(canonical({ ...parsed, type }, parsed.tags))- === digest(canonical({ ...withoutBody(snapshot.page), compiled_truth: stored.truth, timeline: stored.timeline }, snapshot.tags));+ return digest(canonical({ ...parsed, frontmatter: withoutSafetyAssessments(parsed.frontmatter), type }, parsed.tags))+ === digest(canonical({ ...withoutBody(snapshot.page), frontmatter: withoutSafetyAssessments(snapshot.page.frontmatter ?? {}), compiled_truth: stored.truth, timeline: stored.timeline }, snapshot.tags));};const raw = await matches({ prefix: new Uint8Array(0), skip: 0 }, false);if (raw === true) return true;diff --git a/test/large-pages/segmented-withdrawal-mirror.test.ts b/test/large-pages/segmented-withdrawal-mirror.test.tsindex 51f1c43f21..32a4a07e6a 100644--- a/test/large-pages/segmented-withdrawal-mirror.test.ts+++ b/test/large-pages/segmented-withdrawal-mirror.test.ts@@ -23,13 +23,16 @@ import * as fs from 'node:fs';import { existsSync, readdirSync, readFileSync, writeFileSync } from 'node:fs';import { basename, join } from 'node:path';import { exportBodyLedger, readExportPage, readExportWithdrawals, segmentedExportMarkdown } from '../../src/core/export-snapshot.ts';+import { buildEmbedSkipMarker, EMBED_SKIP_KEY } from '../../src/core/embed-skip.ts';import { serializeMarkdown, slugStampedFrontmatter } from '../../src/core/markdown.ts';+import { buildContentFlagMarker, CONTENT_FLAG_KEY } from '../../src/core/quarantine.ts';import { SEGMENT_MAX_BYTES } from '../../src/core/page-body/limits.ts';import { runPersistenceEffects } from '../../src/core/persistence/effects.ts';import { installFaultHook } from '../../src/core/persistence/fault-points.ts';import { localHostId } from '../../src/core/persistence/identity.ts';import { largeFileWork } from '../../src/core/persistence/large-file.ts';import { durableGitRepo, gitAsync } from '../helpers/git-publication.ts';+import { withManagedFixtureWrite } from '../helpers/managed-e2e-fixture-write.ts';import { openTwinBrain, type TwinBrain } from '../helpers/segmented-twins.ts';import { testBackends } from '../helpers/test-backends.ts';import { waitFor } from '../helpers/wait-for.ts';@@ -47,6 +50,8 @@ const CRASH_CLAIMS = { 'effect_recovery:before_stage': 'Twin Example vault code/** The claims of the mid-stream death and of the partial stage left at the reserved name. */const STREAM_CLAIM = 'Twin Example vault code is 2718';const PARTIAL_CLAIM = 'Twin Example vault code is 3141';+/** The claim purged from a page the content gate marked in the database only. */+const MARKED_CLAIM = 'Twin Example safe code is 6022';const fileOf = (brain: TwinBrain, slug: string) => join(brain.root, slug + '.md');const sha = (bytes: Buffer) => createHash('sha256').update(bytes).digest('hex');@@ -214,6 +219,42 @@ for (const kind of testBackends()) {}, 600_000);});+ describe(kind + ': a withdrawal mirrors a segmented page the content gate marked in the database only', () => {+ let brain: TwinBrain;++ beforeAll(async () => {+ brain = await openTwinBrain(kind, [], async seed => {+ await seed.setSwitch(true);+ await seed.put(SEGMENTED, 1_100_000);+ });+ await extract(brain, SEGMENTED, [MARKED_CLAIM, KEPT]);+ expect(await brain.storageOf(SEGMENTED)).toBe('segmented');+ await settle(brain, kind);+ // The content gate's assessments are database state an import stamps (import-screen.ts), never written to the file.+ const markers = { [EMBED_SKIP_KEY]: buildEmbedSkipMarker(1_100_000), [CONTENT_FLAG_KEY]: buildContentFlagMarker('markup_heavy', 'synthetic assessment') };+ await withManagedFixtureWrite(brain.engine, [brain.sourceId], tx => tx.executeRaw('UPDATE pages SET frontmatter=frontmatter||$3::text::jsonb WHERE source_id=$1 AND slug=$2', [brain.sourceId, SEGMENTED, JSON.stringify(markers)]));+ }, 600_000);++ afterAll(() => brain.close(), 120_000);++ test('purge_fact rewrites the file without the claim instead of reading the markers as drift', async () => {+ const [row] = await brain.engine.executeRaw<{ frontmatter: Record<string, unknown> }>('SELECT frontmatter FROM pages WHERE source_id=$1 AND slug=$2', [brain.sourceId, SEGMENTED]);+ expect(Object.keys(row!.frontmatter)).toEqual(expect.arrayContaining([EMBED_SKIP_KEY, CONTENT_FLAG_KEY]));+ const before = readFileSync(fileOf(brain, SEGMENTED), 'utf8');+ expect(before).toContain(MARKED_CLAIM);+ expect(before).not.toContain(EMBED_SKIP_KEY);+ expect(before).not.toContain(CONTENT_FLAG_KEY);++ const receipt = await purge(brain, kind, SEGMENTED, MARKED_CLAIM);+ expect(await effectsOf(brain, receipt.requestId)).toEqual(SETTLED);+ const file = readFileSync(fileOf(brain, SEGMENTED));+ expect(file.toString('utf8')).not.toContain(MARKED_CLAIM);+ expect(file.toString('utf8')).toContain(KEPT);+ expect(file.equals(await exported(brain, SEGMENTED))).toBe(true);+ expect(stagingLeft(brain)).toEqual([]);+ }, 600_000);+ });+describe(kind + ': an interrupted streamed mirror recovers forward', () => {let brain: TwinBrain;