Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

Wave B fix lane L: semantic writes on segmented pages (decision #1 d)

garrytandc21d9b1ed6f
diff --git a/docs/architecture/key-files/core-services-2-continued.md b/docs/architecture/key-files/core-services-2-continued.md
index aaae34de04..3097af1b1a 100644
--- a/docs/architecture/key-files/core-services-2-continued.md
+++ b/docs/architecture/key-files/core-services-2-continued.md
@@ -16,7 +16,7 @@ The page-state concurrency foundation under `src/core/page-state/` and the share
- `src/core/progressive-batch/` — shared ramp-up + cost-cap + verification primitive (trial 10 → ramp 100 → ramp 500 → full, with verification at each stage), with verifier+policy injection (callers describe HOW TO MEASURE SUCCESS, not WHEN TO WAIT FOR CTRL-C). Modules: `types.ts` (Stage, StageVerdict, AbortReason, discriminated `Verifier` union `OutputCountVerifier | IdempotentMutationVerifier | NoopVerifier`, Policy, StageReport), `orchestrator.ts` (`runProgressiveBatch(items, verifier, policy, runner)` — reads `getCurrentBudgetTracker()` ahead of `Policy.maxCostUsd` fail-closed; null both ways triggers `abort_cost_cap reason='no_budget_safety_net'`), `audit.ts` (ISO-week JSONL at `~/.gbrain/audit/progressive-batch-YYYY-Www.jsonl` via the shared `audit-writer` primitive), `stage-report.ts` (ASCII formatter for the default `Policy.onStageReport`). Env knobs: `GBRAIN_PROGRESSIVE_BATCH_DISABLED=1`, `GBRAIN_PROGRESSIVE_BATCH_AUTO=1` (skip Ctrl-C grace), `GBRAIN_PROGRESSIVE_BATCH_STAGES=10,100,500`. Sites that "jump straight to full" stay that way by default; ramp is opt-in per-site via `Policy.interactiveAbortMs > 0`. Pinned by `test/progressive-batch/orchestrator.test.ts` (35 cases, every verdict path).
-- `src/core/page-body/page-shape.ts` — Wave B PR 1 (spec 1.5): segmented page bodies are unreachable as strings. `guardSegmentedBody` (called by `rowToPage` for a row with `body_storage = 'segmented'`, so by every snapshot and `getPage` read) replaces `compiled_truth` / `timeline` with enumerable getters and setters that throw `page_body_segmented`, so property reads, spread, `JSON.stringify`, `structuredClone` and assignment all fail loud instead of seeing an empty body. `isSegmentedPage`, `assertInlineBody(page, site)` (explicit refusal where a writer would otherwise act before a getter fires, e.g. SQL-only writers; every `page_body_segmented` refusal's fix reads the page with `get_page body: 'auto'`), `pageBodyBytes(page)` (`body_bytes` for segmented pages) and `pageBodySegmentedError`. `bodyUnread(page)` says a segmented page's body was not read back as strings (over the single-string ceiling, see `materializedPage`); such a body was written by the streamed import, which holds fenced files, so `fenceBody(page)` reads it as empty for the fence merges and `withoutBody(page)` copies the page's other fields for a render whose body comes from the incoming write (a shrunk file rewrites such a page: `test/large-pages/segmented-shrink-below-ceiling.test.ts`). `Page` stays one shape (`body_storage?`, `body_bytes?`); the static half is `scripts/check-page-body-readers.ts` with `scripts/page-body-readers-baseline.tsv` (docs/TESTING.md#page-body-readers). Pinned by `test/large-pages/segmented-body-unreachable.test.ts`.
+- `src/core/page-body/page-shape.ts` — Wave B PR 1 (spec 1.5): segmented page bodies are unreachable as strings. `guardSegmentedBody` (called by `rowToPage` for a row with `body_storage = 'segmented'`, so by every snapshot and `getPage` read) replaces `compiled_truth` / `timeline` with enumerable getters and setters that throw `page_body_segmented`, so property reads, spread, `JSON.stringify`, `structuredClone` and assignment all fail loud instead of seeing an empty body. `isSegmentedPage`, `assertInlineBody(page, site)` (explicit refusal where a writer would otherwise act before a getter fires, e.g. SQL-only writers; every `page_body_segmented` refusal's fix reads the page with `get_page body: 'auto'`), `pageBodyBytes(page)` (`body_bytes` for segmented pages), `pageBodySegmentedError` and `pageBodyOverCeilingError` (the refusal of a fence or timeline write through the put path on a page over 24 MiB; `wholeBodySnapshot` in `persistence/segmented-apply.ts` reads a page within it back as strings and refuses above it: semantic timeline writes, `takes-prepare.ts`, `facts-prepare.ts`, `reconcile-state.ts`, `gbrain core`). Tag writes on a segmented page never read the body: `prepareSegmentedTagMutation` (`persistence/page-prepare.ts`) flips them in metadata over the live manifest (`test/large-pages/segmented-semantic-writes.test.ts`). `bodyUnread(page)` says a segmented page's body was not read back as strings (over the single-string ceiling, see `materializedPage`); such a body was written by the streamed import, which holds fenced files, so `fenceBody(page)` reads it as empty for the fence merges and `withoutBody(page)` copies the page's other fields for a render whose body comes from the incoming write (a shrunk file rewrites such a page: `test/large-pages/segmented-shrink-below-ceiling.test.ts`). `Page` stays one shape (`body_storage?`, `body_bytes?`); the static half is `scripts/check-page-body-readers.ts` with `scripts/page-body-readers-baseline.tsv` (docs/TESTING.md#page-body-readers). Pinned by `test/large-pages/segmented-body-unreachable.test.ts`.
- `src/core/page-body/limits.ts` — Wave B size classes, ceilings, retention numbers and config keys in one place. `readPageBodyPolicy` is the single question every write asks: `segmented` is the effective `pages.segmented_storage` (unset means `SEGMENTED_STORAGE_DEFAULT`, `off` in this release; `off` or an unrecognized value is off; held off while `segmentedWriterBlockers` finds a recent writer that blocks, and an unreadable gate counts as blocked), `maxBytes` the engine ceiling (256 MiB Postgres, 128 MiB PGLite, lowered by `pages.max_bytes`) while on and `PAGE_MAX_BYTES` while off. Config is read per call; only the writer gate is cached (`SEGMENTED_WRITER_GATE_TTL_MS`, `_resetSegmentedWriterGateForTests`). `chooseBodyStorage` applies the 1 MiB / 512 KiB hysteresis. The writer gate (`segmentedGateWriters` in `persistence/writer-versions.ts`) reads seven days of admitted requests in any state, committed publications, `ingest_log` rows and, on Postgres, `persistence_consumers` heartbeats; a row blocks when its version is below `SEGMENTED_WRITER_FLOOR` or unparsable, or when it lacks the segment-reader mark (migration v251: `admitter_segment_reader`, `consumer_segment_reader`, `persistence_consumers.segment_reader`, `ingest_log.writer_segment_reader`), because releases 0.60.252.0-0.60.262.0 have no segment readers and a version string cannot tell them apart. Not seen: an older binary's unmanaged single-page write, a run that dies before it logs, and read-only or export use. Tests: `test/large-pages/segmented-switch.test.ts`.
- `src/core/page-body/read-range.ts` + `segment-projection.ts` + `segment-ledger.ts` — Wave B PR 2 (spec 7.1, 7.3): the segment reader. `openSegmentedBody` reads a page's live manifest rows and its withdrawal ledger (`readBodyLedger`); `readBodyRange(engine, { pageId, space, start, end, audience, region?, body? })` streams pieces one segment text at a time, never the whole body. Remote reads and every projected-space read serve the read projection: `projectSegment` projects whole segments from their stored protected regions (takes, truncated tail and markers out, keys as the projection token, facts regions rendered world-only and credential-projected), after the withdrawal overlay (`overlaySegmentText`; a fence split by a forced cut is omitted for reads and refuses a trusted read) and the fence overlay (held and purged rows out, rows below the page tier in the low-tier block after the truth). A transform or stale metadata recomputes the regions from the segment's entry state; with none usable the read refuses `page_projection_stale`, never raw text. Trusted stored-space reads give the overlaid stored stream. `projectedLayout` (cached on the handle), `projectedUnits` (rows and fixed text in projected order, for `page-window/segmented.ts`), `projectedTotals`, `projectedLineStart` and `projectedOutline` (outline from stored metadata, no segment text) locate projected bytes; the concatenation equals `projectPageText` of the joined body byte for byte except where a facts fence is longer than a segment (shows less). The chunker (`segment-chunks.ts`) chunks the same projection, so sealed segmented pages carry `MARKDOWN_CHUNKER_VERSION`; `sealSegmentedPage` indexes the overlaid, sanitized timeline lead. Pinned by `test/large-pages/projection-parity.test.ts`, `remote-window-privacy.test.ts` and `sealed-segmented-search.test.ts` (fixture `test/helpers/segmented-privacy-fixture.ts`).
- `src/core/page-body/segment-rewrite.ts` — fence rewrites of a segmented body without holding it as one string (forget strikes, purge drops). Only stored `facts`/`takes` protected regions are decoded and passed, in body order with their region, to a `FenceTransform` (a region crossing forced cuts is joined with its neighbours, refused above `PAGE_MAX_BYTES`). `rewriteLiveSegmentedFences` re-stages the live body through `prepareSegmentedBody` from the segment stream with the changed units replaced and flips it in the caller's transaction (trust tier and soft delete kept; null when nothing changed); `rewriteSegmentedGeneration` rebuilds one retained generation under its own number and updates its versions' hash and size; `rewrittenContentHash` streams the hash of a rewritten generation; `segmentedBodyContains` searches a body segment by segment with the previous segment's tail carried over. Tests: `test/large-pages/purge-segments.test.ts`, `forget-scope.test.ts`, `page-purge-segments.test.ts`.
diff --git a/docs/guides/windowed-reads.md b/docs/guides/windowed-reads.md
index a9460d75d3..eeba78bd98 100644
--- a/docs/guides/windowed-reads.md
+++ b/docs/guides/windowed-reads.md
@@ -144,6 +144,16 @@ it refuses with this code (wire `error: invalid_params`, not retryable) and a
fix that saves the claim without an entity (`infer_entity: false`), whether
the entity was named or inferred from the fact.
+Semantic writes work on such a page. `add_tag` and `remove_tag` change the
+tag at any size without rewriting the body: the tag rows, `content_hash` and
+a version change, and a page backed by a file gets the new frontmatter in that
+file with its body bytes unchanged. `add_timeline_entry`, the `takes_*`
+writes, the facts fence write of `extract_facts`, `gbrain core add` /
+`remove` / `diff` and `gbrain sources reconcile` read a page up to 24 MiB
+back whole and write it as a normal put, with the result an inline page with
+the same body gets; over 24 MiB they refuse with this code, and the message
+names the 24 MiB limit.
+
## page_body_rows_unreadable
A read of a segmented page found manifest rows that do not cover the page's
diff --git a/src/commands/core.ts b/src/commands/core.ts
index da1c225034..f9abb331ae 100644
--- a/src/commands/core.ts
+++ b/src/commands/core.ts
@@ -21,6 +21,7 @@ import {
pendingCoreNotices, readCoreSettings, renderCorePage,
} from '../core/core-memory.ts';
import { serializePageToMarkdown } from '../core/markdown.ts';
+import { wholeBodySnapshot } from '../core/persistence/segmented-apply.ts';
import { setCliExitVerdict } from '../core/cli-force-exit.ts';
import { CORE_SUBCOMMANDS, ROUTERS, subcommandHelpRequested } from '../cli/subcommands.ts';
@@ -67,7 +68,8 @@ function fail(message: string, next?: string): void {
/** Rewrites a page's core marking through put_page as the local owner. */
async function setMarking(engine: BrainEngine, sourceId: string, slug: string, marking: { core: boolean; priority?: number }): Promise<'changed' | 'unchanged' | 'missing'> {
- const snap = await engine.readPageSnapshot(slug, { sourceId });
+ // Wave B: a page stored in segments is read back whole up to 24 MiB and written as a normal put; a larger one refuses.
+ const snap = await wholeBodySnapshot(engine, await engine.readPageSnapshot(slug, { sourceId }), marking.core ? 'core add' : 'core remove');
if (!snap || snap.page.deleted_at) return 'missing';
const fm = { ...((snap.page.frontmatter ?? {}) as Record<string, unknown>) };
const was = isCoreFrontmatter(fm);
@@ -202,9 +204,9 @@ export async function runCore(engine: BrainEngine, args: string[]): Promise<void
if (!slug) { fail('diff needs a page slug.', 'gbrain core diff <slug> [--source <id>]'); return; }
const [oldest] = await engine.executeRaw<{ base_text: string | null; actor: string; created_at: string }>(
`SELECT base_text, actor, created_at::text AS created_at FROM core_edit_notices WHERE source_id = $1 AND slug = $2 AND acked_at IS NULL ORDER BY id LIMIT 1`, [sourceId, slug]);
- const snap = await engine.readPageSnapshot(slug, { sourceId });
- const current = snap ? renderCorePage({ source_id: sourceId, slug, title: snap.page.title, compiled_truth: snap.page.compiled_truth }) : '';
if (!oldest) { print({ pending: false }, () => `No unacknowledged remote edits to ${sourceId}:${slug}.`); return; }
+ const snap = await wholeBodySnapshot(engine, await engine.readPageSnapshot(slug, { sourceId }), 'core diff');
+ const current = snap ? renderCorePage({ source_id: sourceId, slug, title: snap.page.title, compiled_truth: snap.page.compiled_truth }) : '';
print({ pending: true, since: oldest.created_at, actor: oldest.actor, before: oldest.base_text, after: current, revision: snap?.revision ?? null },
() => `Remote edits to ${sourceId}:${slug} since ${oldest.created_at} (first by ${oldest.actor}):\n${lineDiff(oldest.base_text ?? '', current)}\n\nIf this is fine: gbrain core ack --source ${sourceId} ${slug} --revision ${snap?.revision ?? 'latest'}`);
return;
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index f2c76e28d4..f330cb6dd3 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -732,6 +732,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText }
{ since: 'TBD', text: 'Reads of a page stored in segments that follow an authorization (MCP `get_page` windows, outlines, sizes and its whole-body refusal, `fetch`, evidence windows and the `entity` card excerpt) now read the revision they authorized: a page edited, made private or dropped below the caller\'s `min_trust` mid-read refuses with `revision_changed` (or `page_not_found`) instead of returning the newer body, and evidence falls back to the hit chunk. A segmented page whose segment rows the reader cannot see, or that has a gap or a missing tail, refuses with the new `page_body_rows_unreadable` in every reader that produces its body (MCP reads, export, backup and restore file writes, body digests, fence rewrites) instead of reading as empty or short; an export with such a page fails. `purge_fact` now aborts a write in flight that staged a text holding the purged claim (its publish refuses `body_staging_expired`), segment maintenance keeps every text a live write staged, a page purge of an inline page no longer reports other pages\' segments as incomplete, and MCP `get_versions` reports a segmented version\'s readable size as `total_bytes` instead of its stored `body_bytes`.' },
{ since: 'TBD', text: '`gbrain extract --stale`, the cycle\'s stale-extraction drain and the managed stale-links pass now extract a page stored in segments whose links or timeline are stale, reading its body block by block, and stamp it. Before, doctor `links_extraction_lag` and the sync report counted such a page as needing extraction while no extractor picked it up, so the count never reached 0.' },
{ since: 'TBD', text: 'A large page held for embedding approval or stopped by `embed.max_usd_per_page` that is edited down to 1 MiB or under (inline, or still stored in segments) now embeds through the stale sweep and `gbrain embed --stale` like any page of its size, and no longer appears as held or capped in `gbrain embed --held`, doctor `partial_embedding` or write and sync receipts. Its budget row is kept: if the page grows past 1 MiB again, the hold or cap it had applies again.' },
+ { since: 'TBD', text: 'Semantic writes on a page stored in segments (`pages.segmented_storage` on): `add_tag` and `remove_tag` now work at any page size as a metadata change (the tag rows, `content_hash` and a version; no segment, chunk or embedding is rewritten), and a page backed by a file gets the new frontmatter in that file with its body unchanged; an `external_untrusted` writer, whose write gate scans the whole body, takes the put path below. `add_timeline_entry`, `takes_add` / `takes_update` / `takes_supersede` / `takes_resolve` / `takes_remove`, the facts fence write of `extract_facts`, `gbrain core add` / `remove` / `diff` and `gbrain sources reconcile` now read a segmented page up to 24 MiB back whole and write it as a normal put, with the result an inline page with the same body gets. Above 24 MiB they still refuse with `page_body_segmented` (wire error `invalid_params` for the memory verbs, not retryable), and the refusal now names the 24 MiB limit.' },
];
/** The newest disclosed change's release: the notice id moves only when a release adds rows. */
diff --git a/src/core/page-body/page-shape.ts b/src/core/page-body/page-shape.ts
index ffacf0dca2..d892a457d6 100644
--- a/src/core/page-body/page-shape.ts
+++ b/src/core/page-body/page-shape.ts
@@ -13,6 +13,7 @@
* enforcement, not the type checker.
*/
import { opError } from '../ops/contract.ts';
+import { PAGE_MAX_BYTES } from '../page-size-policy.ts';
import type { Page } from '../types.ts';
import type { BodyStorage } from './types.ts';
@@ -63,6 +64,21 @@ export function pageBodySegmentedError(page: { slug?: string; source_id?: string
consent: [], actor: 'agent', requires_exclusive: false, why: "Returns the page's outline and its first window, with next_cursor to read on." } });
}
+/**
+ * The refusal of a write that reads the body whole (a fence or timeline edit through the put path) on a segmented page
+ * over PAGE_MAX_BYTES (24 MiB): up to it the page is read back as strings and written as a normal put.
+ */
+export function pageBodyOverCeilingError(page: { slug?: string; source_id?: string; body_bytes?: number | null }, site: string) {
+ const slug = page.slug ?? '<unknown>';
+ const sourceId = page.source_id ?? 'default';
+ return opError('page_body_segmented',
+ `${site}: page ${slug} (source ${sourceId}) stores its ${Number(page.body_bytes ?? 0)}-byte body in segments, over the 24 MiB (${PAGE_MAX_BYTES}-byte) limit up to which this write reads the body whole. Nothing was read or changed.`,
+ "This write edits a page stored in segments by reading its body whole, which works up to 24 MiB; this page is larger, so retrying refuses the same way. Read the page in pieces: get_page body: 'auto' returns its outline and first window, and body: 'window' reads any lines or bytes.",
+ { fix: { argv: ['gbrain', 'get', '--source', sourceId, '--body', 'auto', '--', slug],
+ mcp: { tool: 'get_page', arguments: { slug, source_id: sourceId, body: 'auto' } },
+ consent: [], actor: 'agent', requires_exclusive: false, why: "Returns the page's outline and its first window, with next_cursor to read on." } });
+}
+
/** Throws `page_body_segmented` for a segmented page; `site` names the caller. Inline pages pass. */
export function assertInlineBody(page: BodyShape & { slug?: string; source_id?: string }, site: string): void {
if (isSegmentedPage(page)) throw pageBodySegmentedError(page, site);
diff --git a/src/core/persistence/facts-prepare.ts b/src/core/persistence/facts-prepare.ts
index dd42eca61d..ca5aff1a05 100644
--- a/src/core/persistence/facts-prepare.ts
+++ b/src/core/persistence/facts-prepare.ts
@@ -7,7 +7,7 @@ import type { Action } from '../agent-output.ts';
import type { RegistryCode } from '../error-registry.ts';
import { factsFenceSection, parseFactsFence, strikeFactRowInPage, upsertFactRow, formatFenceDate } from '../facts-fence.ts';
import { serializePageToMarkdown } from '../markdown.ts';
-import { assertInlineBody } from '../page-body/page-shape.ts';
+import { wholeBodySnapshot } from './segmented-apply.ts';
import { assertFactNotWithdrawn, decideSingleFact, factWithdrawnRefusal, type FactCandidate } from '../facts/single-prepare.ts';
import { assertFactNotPurged, isFactWithdrawn } from '../facts/withdrawal.ts';
import { samePageRewording, warnSamePageShadow } from '../facts/same-page-shadow.ts';
@@ -134,8 +134,8 @@ export async function prepareManagedFactsMutation(engine: BrainEngine, row: Writ
...(wouldDedupSamePage ? { would_dedup_same_page: wouldDedupSamePage } : {}),
fact_ids: done.flatMap(item => item.outcome.fact_ids ?? []) };
} };
- const snapshot = await engine.readPageSnapshot(row.slug, { sourceId: row.source_id, includeDeleted: true });
- if (snapshot?.page.deleted_at || (snapshot?.page.id ?? null) !== row.page_id || (snapshot?.revision ?? null) !== (p.expected_revision ?? null)) {
+ const stored = await engine.readPageSnapshot(row.slug, { sourceId: row.source_id, includeDeleted: true });
+ if (stored?.page.deleted_at || (stored?.page.id ?? null) !== row.page_id || (stored?.revision ?? null) !== (p.expected_revision ?? null)) {
throw factsRefusal('revision_conflict', 'The fact entity changed after extraction admission.', row,
`Entity page ${row.slug} changed or was deleted after these facts were admitted, so none were published.`);
}
@@ -143,12 +143,13 @@ export async function prepareManagedFactsMutation(engine: BrainEngine, row: Writ
// writeSingleFact's opt-in: an unattributed row keeps its fallback entity slug, database-only.
const fallback = (fact: { entity_slug: string | null }) => p.attribute_fallback === true && row.slug === 'memory/unattributed'
&& fact.entity_slug !== null && fact.entity_slug !== row.slug;
- if (!facts.length || facts.some(fact => !fallback(fact) && (fact.entity_slug !== null && fact.entity_slug !== row.slug || fact.entity_slug !== null && !snapshot))) {
+ if (!facts.length || facts.some(fact => !fallback(fact) && (fact.entity_slug !== null && fact.entity_slug !== row.slug || fact.entity_slug !== null && !stored))) {
throw factsRefusal('invalid_params', 'The prepared facts do not match their entity.', row,
`The request holds no facts, or facts attributed to a page other than ${row.slug}, so none were published.`);
}
+ // Wave B: a segmented entity page within 24 MiB is read back whole and its fence written as a normal put; a larger one refuses.
+ const snapshot = await wholeBodySnapshot(engine, stored, 'facts fence write');
// #6188 (D20): the entity's stored fence is normalized in this same write; a residual refuses typed `target_fence_malformed`.
- if (snapshot) assertInlineBody(snapshot.page, 'facts fence write');
const target = snapshot ? await normalizeTargetFences(engine, { sourceId: row.source_id, slug: row.slug, kind: 'facts', page: snapshot.page }) : null;
// #6686: the fence is edited in the section it lives in (a lone timeline fence stays below the sentinel); the other section is kept byte for byte.
const fenced = { compiled_truth: target?.page.compiled_truth ?? '', timeline: target?.page.timeline ?? '' };
diff --git a/src/core/persistence/memory-prepare.ts b/src/core/persistence/memory-prepare.ts
index ed91b566b8..ec24416d8f 100644
--- a/src/core/persistence/memory-prepare.ts
+++ b/src/core/persistence/memory-prepare.ts
@@ -7,7 +7,7 @@ import { pageIdentityError } from './page-identity.ts';
import { assertPageRevision } from '../page-state/types.ts';
import { factsFenceSection, parseFactsFence, strikeFactRowInPage, upsertFactRow, formatFenceDate } from '../facts-fence.ts';
import { serializePageToMarkdown } from '../markdown.ts';
-import { assertInlineBody } from '../page-body/page-shape.ts';
+import { pageBodyOverCeilingError } from '../page-body/page-shape.ts';
import { materializedPage, segmentedOverCeiling } from './segmented-apply.ts';
import { assertFactNotWithdrawn, decideReplacement, decideSingleFact, prepareFactEmbedding, type SingleFactIntent } from '../facts/single-prepare.ts';
import { factEmbeddingDisabled } from '../embedding-disabled.ts';
@@ -147,7 +147,7 @@ export async function prepareMemoryMutation(engine: BrainEngine, row: WriteReque
let fencesNormalized: Record<string, unknown> = {};
if (p.fence === true && snapshot) {
// Wave B: a segmented page is read back whole up to the single-string ceiling and rewritten through the put path.
- if (segmentedOverCeiling(snapshot.page)) assertInlineBody(snapshot.page, 'remember facts fence write');
+ if (segmentedOverCeiling(snapshot.page)) throw pageBodyOverCeilingError(snapshot.page, 'remember facts fence write');
const base = await materializedPage(engine, snapshot.page);
// #6188 (D20): the stored fence is normalized in this same write; a residual refuses typed `target_fence_malformed`.
const target = await normalizeTargetFences(engine, { sourceId: row.source_id, slug: row.slug, kind: 'facts', page: base });
diff --git a/src/core/persistence/page-prepare.ts b/src/core/persistence/page-prepare.ts
index ea155da307..c20fc1b203 100644
--- a/src/core/persistence/page-prepare.ts
+++ b/src/core/persistence/page-prepare.ts
@@ -50,7 +50,8 @@ import { fileBodyDigests, overlaidFileBodyDigests, storedBodyDigests, type ByteS
import { ledgerApplies, type BodyLedger } from '../page-body/segment-ledger.ts';
import { inferredHeadPrefix } from '../page-body/streamed-import.ts';
import { FRONTMATTER_HEAD_MAX_BYTES } from '../page-body/limits.ts';
-import { occurrencesWithoutChunks } from '../page-body/ingest.ts';
+import { occurrencesWithoutChunks, readSegmentedBody } from '../page-body/ingest.ts';
+import { ContentHashStream } from '../page-body/content-hash-stream.ts';
import { buildSegmentedProjection, hasStaleChunks } from '../page-body/projection.ts';
import { segmentedExportMarkdown } from '../export-snapshot.ts';
import { loadImportSanityConfig } from '../import-screen.ts';
@@ -540,6 +541,62 @@ async function unreadPageFile(engine: BrainEngine, snapshot: PageSnapshot): Prom
return StreamedFileContent.measure(engine, exec => segmentedExportMarkdown(exec, snapshot.page, ledger, head));
}
+/** Work counters of segmented tag flips: `flips` applied, `hashStreams` content hashes recomputed over the segments. */
+export const segmentedTagWork = { flips: 0, hashStreams: 0 };
+
+/**
+ * Wave B (spec 6.4): add_tag / remove_tag on a segmented page, at any size, as a metadata flip that reuses the live
+ * manifest: the body generation, segment texts and chunks stay as they are. As the inline tag write does, it versions
+ * the page (a segmented version references the live generation, O(1)), changes the tag rows, stores the new
+ * content_hash and reseals a sealed page at its new revision; the canonical file is serializePageToMarkdown's bytes
+ * with the new tags, streamed from the segments (unreadPageFile). The hash resumes from the last live row's midstate
+ * (content-hash-stream.ts); a midstate that does not reproduce the stored hash is replaced by one pass over the segments.
+ * Null when the write gate would scan the whole body (an external_untrusted writer): that write takes the put path.
+ */
+export async function prepareSegmentedTagMutation(engine: BrainEngine, row: WriteRequest, snapshot: PageSnapshot, tags: string[]): Promise<PreparedMutation | null> {
+ const source = { sourceId: row.source_id };
+ const [, pack, storedTier] = await Promise.all([assertKnowledgePublicationAllowed(engine, row),
+ loadActivePackForEngine(engine, { remote: row.authority.remote, sourceId: row.source_id }).catch(() => null), storedPageTier(engine, row.source_id, row.slug)]);
+ const noop = tags.length === snapshot.tags.length && tags.every(tag => snapshot.tags.includes(tag));
+ const trust = pageWriteTrust(row, snapshot.page.frontmatter);
+ const gateTrust = pageGateTrust(row, trust, storedTier);
+ if (!noop && gateTrust && writeGateApplies(gateTrust.tier, (await loadImportSanityConfig(engine)).writeGate ?? DEFAULT_WRITE_GATE_CONFIG)
+ && gateTrust.tier === 'external_untrusted') return null;
+ const pageId = Number(snapshot.page.id);
+ const hash = noop ? snapshot.page.content_hash : await segmentedContentHash(engine, snapshot, tags);
+ const file = row.worktree_id ? await prepareFileTarget(engine, row, snapshot, await unreadPageFile(engine, { ...snapshot, tags }), undefined,
+ { activePack: pack?.manifest, remote: row.authority.remote }) : undefined;
+ const sealed = snapshot.page.text_projection_revision === snapshot.revision;
+ return { observedRevision: snapshot.revision, noop, file, ...await pageDatabaseOnlyPublication(engine, row, file), ...(trust ? { trust } : {}),
+ apply: async tx => {
+ if (noop) return { ...pageNoopAdvisories(row), status: 'skipped', slug: row.slug, source_id: row.source_id, noop: true, chunks: 0, chunk_skip_reason: 'write_skipped' };
+ await tx.createVersion(row.slug, source);
+ for (const tag of snapshot.tags) if (!tags.includes(tag)) await tx.removeTag(row.slug, tag, source);
+ for (const tag of tags) if (!snapshot.tags.includes(tag)) await tx.addTag(row.slug, tag, source);
+ await tx.executeRaw('UPDATE pages SET content_hash=$2, updated_at=now() WHERE id=$1', [pageId, hash]);
+ if (sealed) await sealSegmentedPage(tx, pageId);
+ segmentedTagWork.flips++;
+ return { ...remoteLinkHint(row), status: 'created_or_updated', slug: row.slug, source_id: row.source_id, chunks: 0, noop: false,
+ searchable: isQuarantined(snapshot.page.frontmatter) ? false : sealed ? true : 'pending', ...await sizeStateField(tx, row.source_id, row.slug, snapshot.page) };
+ } };
+}
+
+/** The content_hash of a segmented page with `tags`: its stored body and frontmatter, resumed from the last live manifest row's midstate. */
+async function segmentedContentHash(engine: BrainEngine, snapshot: PageSnapshot, tags: string[]): Promise<string> {
+ const pageId = Number(snapshot.page.id);
+ const meta = { frontmatter: snapshot.page.frontmatter, tags };
+ const last = (await engine.readManifest(pageId)).at(-1);
+ const resumed = last ? (() => { try { return ContentHashStream.fromState(last.hashState); } catch { return null; } })() : null;
+ if (resumed && resumed.finish({ frontmatter: snapshot.page.frontmatter, tags: snapshot.tags }) === snapshot.page.content_hash) return resumed.finish(meta);
+ segmentedTagWork.hashStreams++;
+ const stream = ContentHashStream.begin(snapshot.page);
+ const decoder = new TextDecoder();
+ for await (const part of readSegmentedBody(engine, pageId, snapshot.page.source_id)) {
+ if (part.region === 'truth') stream.pushTruth(decoder.decode(part.bytes)); else stream.pushTimeline(decoder.decode(part.bytes));
+ }
+ return stream.finish(meta);
+}
+
/**
* Providers and parsing run before the OS lock and before any publication transaction.
* `coordinated`: the caller publishes this mutation itself through the coordinator, whose
diff --git a/src/core/persistence/reconcile-state.ts b/src/core/persistence/reconcile-state.ts
index c31334a063..1929511a7e 100644
--- a/src/core/persistence/reconcile-state.ts
+++ b/src/core/persistence/reconcile-state.ts
@@ -11,6 +11,7 @@ import type { PageSnapshot } from '../page-state/types.ts';
import { isWriteTargetContained } from '../path-confine.ts';
import { recordedPathFromFileUri, scannerSlugRootMode, scannerSourcePath } from '../write-through.ts';
import { findLiveFileClaimants, recordedReconcilePath, type FileClaimTarget } from './file-claims.ts';
+import { wholeBodySnapshot } from './segmented-apply.ts';
import { sharedOriginExit } from './sync-origin.ts';
export { fileClaimCandidatesQuery } from './file-claims.ts';
import { localHostId } from './identity.ts';
@@ -94,7 +95,8 @@ export async function readReconcileState(engine: BrainEngine, sourceId: string,
throw new OperationError('owner_unavailable', 'Reconciliation requires the existing active owner on this host.', 'Run repair on the current owner; repair never claims or activates a source.');
}
const [brain] = await engine.executeRaw<{ brain_id: string }>('SELECT brain_id FROM persistence_brain WHERE singleton=1');
- const snapshot = await engine.readPageSnapshot(slug, { sourceId, includeDeleted: true });
+ // Wave B: a page stored in segments is compared and merged as strings up to 24 MiB; a larger one refuses.
+ const snapshot = await wholeBodySnapshot(engine, await engine.readPageSnapshot(slug, { sourceId, includeDeleted: true }), 'sources reconcile');
if (!snapshot || snapshot.page.deleted_at) throw opError('page_not_found', 'Reconciliation requires an existing live page; use the separate restore workflow for deleted pages.',
`Page ${slug} in '${sourceId}' is deleted or missing; nothing changed. If it was deleted by mistake, restore it (gbrain restore, within the 72-hour window) and then preview it again.`,
{ fix: readFix('Shows whether the page exists or is soft-deleted in this source.', { argv: ['gbrain', 'get', '--source', sourceId, '--include-deleted', '--', slug] }) });
diff --git a/src/core/persistence/segmented-apply.ts b/src/core/persistence/segmented-apply.ts
index bbf5bebccb..044e42efc0 100644
--- a/src/core/persistence/segmented-apply.ts
+++ b/src/core/persistence/segmented-apply.ts
@@ -37,6 +37,7 @@ import { faultPoint } from './fault-points.ts';
import { bodyStagingGoneError, LIVE_STAGING_STATES } from '../engine-sql/page-body.ts';
import { segmentedPageSearchable } from './searchable.ts';
import { stableJson } from './digest.ts';
+import { pageBodyOverCeilingError } from '../page-body/page-shape.ts';
const BODY_KEYS = new Set(['compiled_truth', 'timeline', 'content']);
@@ -101,6 +102,16 @@ export async function materializedSnapshot(engine: BrainEngine, snapshot: PageSn
return { ...snapshot, page };
}
+/**
+ * The snapshot a whole-body write (a fence or timeline edit through the put path) reads and merges into: a segmented
+ * page within PAGE_MAX_BYTES read back as strings, as `materializedSnapshot` gives it; one over it refuses with
+ * `page_body_segmented` (`site` names the write) before anything is read or staged.
+ */
+export async function wholeBodySnapshot(engine: BrainEngine, snapshot: PageSnapshot | null, site: string): Promise<PageSnapshot | null> {
+ if (snapshot && segmentedOverCeiling(snapshot.page)) throw pageBodyOverCeilingError(snapshot.page, site);
+ return materializedSnapshot(engine, snapshot);
+}
+
/**
* The storage class of a string write: reads the policy only when the class
* could be segmented (a body over the demote bound, or a segmented page), so
diff --git a/src/core/persistence/semantic-pages.ts b/src/core/persistence/semantic-pages.ts
index 4ff5c43ec5..04483abe43 100644
--- a/src/core/persistence/semantic-pages.ts
+++ b/src/core/persistence/semantic-pages.ts
@@ -6,11 +6,12 @@ import type { BrainEngine } from '../engine.ts';
import type { GBrainConfig } from '../config.ts';
import { serializePageToMarkdown } from '../markdown.ts';
import { opError, OperationError } from '../ops/contract.ts';
-import { assertInlineBody } from '../page-body/page-shape.ts';
+import { isSegmentedPage } from '../page-body/page-shape.ts';
+import { wholeBodySnapshot } from './segmented-apply.ts';
import { pageIdentityError } from './page-identity.ts';
import { renderTimelineEntry, spliceTimelineBlock } from '../timeline-write-through.ts';
import { extractTimelineFromContent } from '../timeline-extract.ts';
-import { preparePageMutation } from './page-prepare.ts';
+import { preparePageMutation, prepareSegmentedTagMutation } from './page-prepare.ts';
import type { PreparedMutation } from './coordinator.ts';
import type { WriteRequest } from './model.ts';
import { assertPageRevision } from '../page-state/types.ts';
@@ -44,18 +45,21 @@ export function regeneratedByWriter(sourceKind: string | null | undefined, page:
}
export async function prepareSemanticPageMutation(engine: BrainEngine, row: WriteRequest, config: GBrainConfig): Promise<PreparedMutation> {
- const snapshot = await engine.readPageSnapshot(row.slug, { sourceId: row.source_id });
- if (!snapshot || snapshot.page.id !== row.page_id) throw pageIdentityError(snapshot != null, 'The accepted page was replaced by another page.');
- assertInlineBody(snapshot.page, row.operation);
+ const stored = await engine.readPageSnapshot(row.slug, { sourceId: row.source_id });
+ if (!stored || stored.page.id !== row.page_id) throw pageIdentityError(stored != null, 'The accepted page was replaced by another page.');
const p = row.intent!;
- if (p.expected_revision !== undefined) assertPageRevision(snapshot,engineMutationPrecondition(parseMutationPrecondition(p)));
+ if (p.expected_revision !== undefined) assertPageRevision(stored,engineMutationPrecondition(parseMutationPrecondition(p)));
if (row.operation === 'add_tag' || row.operation === 'remove_tag') {
if (typeof p.tag !== 'string' || !p.tag.trim()) {
throw opError('invalid_params', 'A tag must be nonempty.', `Request ${row.request_id} for ${row.slug} in source ${row.source_id} named an empty tag, so nothing changed. Submit the tag change again with a nonempty tag.`);
}
const tag = p.tag.trim();
- const tags = row.operation === 'add_tag' ? [...new Set([...snapshot.tags, tag])].sort() : snapshot.tags.filter(value => value !== tag);
- const prepared = await preparePageMutation(engine, row, config, {
+ const tags = row.operation === 'add_tag' ? [...new Set([...stored.tags, tag])].sort() : stored.tags.filter(value => value !== tag);
+ // Wave B (spec 6.4): a tag change on a segmented page is a metadata flip over the live manifest, at any size;
+ // only a write whose gate scans the whole body (an external_untrusted writer) takes the put path, up to 24 MiB.
+ const flipped = isSegmentedPage(stored.page) ? await prepareSegmentedTagMutation(engine, row, stored, tags) : null;
+ const snapshot = flipped ? stored : (await wholeBodySnapshot(engine, stored, `${row.operation} (the write gate scans the whole body of an external_untrusted write)`))!;
+ const prepared = flipped ?? await preparePageMutation(engine, row, config, {
expectedRevision: snapshot.revision, tags, content: serializePageToMarkdown(snapshot.page, tags),
});
// #5251: a tag change leaves every chunk's text as it was, so the republication queues no
@@ -66,6 +70,8 @@ export async function prepareSemanticPageMutation(engine: BrainEngine, row: Writ
throw opError('writer_coordinator_required', 'This semantic writer has no registered preparation handler.',
`Request ${row.request_id} (${row.operation}) in source ${row.source_id} has no preparation handler in this gbrain version, so nothing changed. This is an internal or version-skew fault: report it to the user.`);
}
+ // Wave B: a segmented page within 24 MiB is read back whole and written as a normal put; a larger one refuses.
+ const snapshot = (await wholeBodySnapshot(engine, stored, row.operation))!;
const entry = { date: String(p.date), summary: String(p.summary), source: String(p.source ?? ''), detail: String(p.detail ?? '') };
const rendered = renderTimelineEntry(entry, row.slug);
if (!rendered) {
diff --git a/src/core/persistence/takes-prepare.ts b/src/core/persistence/takes-prepare.ts
index 3f103bc375..844f9ee92b 100644
--- a/src/core/persistence/takes-prepare.ts
+++ b/src/core/persistence/takes-prepare.ts
@@ -7,6 +7,7 @@ import { isValidHolder, parseTakesFence, upsertTakeRow, supersedeRow, type Parse
import { takesPreparation as edit, TakesWriteError } from '../takes-write.ts';
import { serializePageToMarkdown } from '../markdown.ts';
import { preparePageMutation } from './page-prepare.ts';
+import { wholeBodySnapshot } from './segmented-apply.ts';
import { authorizeTakeHolder } from './authority.ts';
import type { WriteRequest } from './model.ts';
import type { PreparedMutation } from './coordinator.ts';
@@ -91,11 +92,13 @@ export async function prepareTakesMutation(engine: BrainEngine, row: WriteReques
try { return await prepare(engine,row,config); } catch (error) { return fail(error); }
}
async function prepare(engine: BrainEngine, row: WriteRequest, config: GBrainConfig): Promise<PreparedMutation> {
- const snapshot = await engine.readPageSnapshot(row.slug, { sourceId: row.source_id });
- if (!snapshot || snapshot.page.id !== row.page_id) throw takesRefusal('page_identity_changed','The accepted page no longer exists.',row,
+ const stored = await engine.readPageSnapshot(row.slug, { sourceId: row.source_id });
+ if (!stored || stored.page.id !== row.page_id) throw takesRefusal('page_identity_changed','The accepted page no longer exists.',row,
`Page ${row.slug} was deleted or replaced after the takes request was accepted.`);
const p = row.intent!;
- if (p.expected_revision !== undefined) assertPageRevision(snapshot,engineMutationPrecondition(parseMutationPrecondition(p)));
+ if (p.expected_revision !== undefined) assertPageRevision(stored,engineMutationPrecondition(parseMutationPrecondition(p)));
+ // Wave B: a segmented page within 24 MiB is read back whole and written as a normal put; a larger one refuses.
+ const snapshot = (await wholeBodySnapshot(engine, stored, row.operation))!;
// #6188 (D19, D20): takes_add / takes_update normalize the stored takes fence in this write; every other
// takes write refuses typed `target_fence_malformed` (location only) while the fence does not compile.
const appends = row.operation === 'takes_add' || row.operation === 'takes_update';
diff --git a/src/core/persistence/verb-errors.ts b/src/core/persistence/verb-errors.ts
index c91ec3879d..bb6d27ecea 100644
--- a/src/core/persistence/verb-errors.ts
+++ b/src/core/persistence/verb-errors.ts
@@ -139,7 +139,7 @@ export function writeFailureDiagnostic(code: string, message?: string | null): {
}
const SEGMENTED_WRITE_MESSAGE = 'The target page stores its body in segments, and this write needs the whole body as one string; nothing was changed.';
-const SEGMENTED_WRITE_SUGGESTION = 'The target page is over 1 MiB and stores its body in segments, which this write cannot change yet, so retrying refuses the same way. '
+const SEGMENTED_WRITE_SUGGESTION = 'The target page stores its body in segments over the 24 MiB limit up to which this write reads the body whole, so retrying refuses the same way. '
+ 'For remember: save the claim without an entity (omit entity, infer_entity: false); it is filed under memory/unattributed, and remembering it with entity once that page accepts fact rows replaces that copy. '
+ "Read the page with get_page body: 'auto' or a window.";
@@ -149,13 +149,13 @@ export function segmentedRememberFix(): Action {
mcp: { tool: 'remember', arguments: { fact: '<FACT>', provenance: '<PROVENANCE>', infer_entity: false } },
inputs: [{ name: 'FACT', how: 'The claim you tried to remember, unchanged.' }, { name: 'PROVENANCE', how: 'The same provenance you passed.' }],
consent: [], actor: 'agent', requires_exclusive: false,
- why: "Saves the claim without an entity: the entity page's facts fence cannot take a row while its body is stored in segments. Remembering it with entity later replaces this copy." };
+ why: "Saves the claim without an entity: the entity page's facts fence cannot take a row while its body is stored in segments over 24 MiB. Remembering it with entity later replaces this copy." };
}
/** A `remember` whose entity (named or inferred) stores its body in segments: refused before admission with the unattributed-save fix. */
export function segmentedRememberRefusal(slug: string, sourceId: string, inferred: boolean): OperationError {
return opError('page_body_segmented',
- `remember: the entity page ${slug} (source ${sourceId})${inferred ? ', inferred from a mention in the fact,' : ''} stores its body in segments, and remember cannot add a row to its facts fence yet. Nothing was saved.`,
+ `remember: the entity page ${slug} (source ${sourceId})${inferred ? ', inferred from a mention in the fact,' : ''} stores its body in segments over the 24 MiB limit up to which remember reads it whole, so remember cannot add a row to its facts fence. Nothing was saved.`,
SEGMENTED_WRITE_SUGGESTION, { fix: segmentedRememberFix() });
}
diff --git a/test/helpers/segmented-twins.ts b/test/helpers/segmented-twins.ts
new file mode 100644
index 0000000000..c2895f32bb
--- /dev/null
+++ b/test/helpers/segmented-twins.ts
@@ -0,0 +1,141 @@
+/**
+ * Twin pages for semantic-write parity tests (Wave B fix lane L): a managed brain whose one source is file-backed
+ * (write-through on, canonical worktree claimed), seeded while unmanaged, with \`pages.segmented_storage\` off for the
+ * inline twin's writes and on for the segmented twin's. \`call\` runs one verb as an MCP tool call on the local writer
+ * with the switch the target was written under; \`view\` is everything a semantic write can change on a page, with
+ * the slug and seed-time stamps made neutral so twins compare equal.
+ */
+import { expect } from 'bun:test';
+import { randomUUID } from 'node:crypto';
+import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import type { BrainEngine } from '../../src/core/engine.ts';
+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';
+import { dispatchToolCall } from '../../src/mcp/dispatch.ts';
+import { importFromFile } from '../../src/core/import-file.ts';
+import { parseMarkdown, serializePageToMarkdown } from '../../src/core/markdown.ts';
+import { readPageBodyPolicy } from '../../src/core/page-body/limits.ts';
+import { materializeSegmentedBody } from '../../src/core/page-body/ingest.ts';
+import { claimWorktree } from '../../src/core/persistence/ownership.ts';
+import { submitPageMutation } from '../../src/core/persistence/page-mutations.ts';
+import { registerLocalWriter, withVerifiedLocalRegistration, type LocalRegistration } from '../../src/core/persistence/identity.ts';
+import { disposePersistenceConsumer } from '../../src/core/persistence/service.ts';
+import { configureGateway, resetGateway, __setChatTransportForTests, __setEmbedTransportForTests, type ChatResult } from '../../src/core/ai/gateway.ts';
+import { isolatedPersistencePostgres } from './persistence-postgres.ts';
+import { withEnv } from './with-env.ts';
+
+const line = (i: number) => '- ' + String(i).padStart(8, '0') + ' acme-example journal line with enough text to fill a segment quickly\n';
+const body = (bytes: number) => Array.from({ length: Math.ceil(bytes / line(0).length) }, (_, i) => line(i)).join('');
+/** A person page of about \`bytes\` body bytes with one timeline entry; twins share title and body. */
+export const twinPage = (bytes: number) => '---\ntype: person\ntitle: Twin Example\n---\n\n# Twin Example\n\n' + body(bytes) + '\n<!-- timeline -->\n- **2026-10-01** | manual — first entry\n';
+/** The file gbrain itself renders for twinPage(bytes), so a write that re-renders it changes only what the write changes. */
+const canonical = (slug: string, bytes: number) => { const parsed = parseMarkdown(twinPage(bytes), slug + '.md'); return serializePageToMarkdown(parsed as never, parsed.tags); };
+const usage = { input_tokens: 1, output_tokens: 1, cache_read_tokens: 0, cache_creation_tokens: 0 };
+
+export interface TwinSeed {
+ setSwitch(on: boolean): Promise<void>;
+ /** A put_page through the coordinator (it writes the canonical file). */
+ put(slug: string, bytes: number): Promise<void>;
+ /** The canonical file written first, then imported from it (a page over 4 MiB, streamed when segmented). */
+ imported(slug: string, bytes: number): Promise<void>;
+}
+
+export interface TwinBrain {
+ engine: BrainEngine;
+ sourceId: string;
+ root: string;
+ cli: LocalRegistration;
+ env(): Record<string, string>;
+ setSwitch(on: boolean): Promise<void>;
+ /** The extraction model's next reply (extract_facts). */
+ setChatReply(reply: string): void;
+ call(name: string, params: Record<string, unknown>, target?: string): Promise<Record<string, any>>;
+ view(slug: string): Promise<Record<string, unknown>>;
+ hits(term: string): Promise<string[]>;
+ storageOf(slug: string): Promise<string>;
+ close(): Promise<void>;
+}
+
+export async function openTwinBrain(kind: 'pglite' | 'postgres', inlineSlugs: readonly string[], seed: (s: TwinSeed) => Promise<void>): Promise<TwinBrain> {
+ let chatReply = '{"facts":[]}';
+ configureGateway({ chat_model: 'anthropic:claude-sonnet-4-6', embedding_model: 'openai:text-embedding-3-large', embedding_dimensions: 1536,
+ env: { ANTHROPIC_API_KEY: 'sk-ant-test', OPENAI_API_KEY: 'sk-test' } });
+ __setChatTransportForTests(async (): Promise<ChatResult> => ({ text: chatReply, blocks: [], stopReason: 'end', usage, model: 'anthropic:claude-sonnet-4-6', providerId: 'anthropic' }));
+ __setEmbedTransportForTests((async ({ values }: { values: string[] }) => ({ embeddings: values.map(() => Array(1536).fill(0.01)) })) as never);
+ let engine: BrainEngine;
+ let closeEngine: () => Promise<void>;
+ if (kind === 'postgres') {
+ const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL!);
+ engine = pg.engine; closeEngine = pg.close;
+ } else {
+ const lite = new PGLiteEngine(); await lite.connect({}); await lite.initSchema();
+ engine = lite; closeEngine = () => lite.disconnect();
+ }
+ const dir = mkdtempSync(join(tmpdir(), 'gbrain-segmented-twins-'));
+ const root = join(dir, 'brain'); mkdirSync(join(root, 'people'), { recursive: true });
+ const sourceId = 'twins-' + kind;
+ const env = () => ({ GBRAIN_HOME: join(dir, 'home'), GBRAIN_AUDIT_DIR: join(dir, 'audit') });
+ const setSwitch = (on: boolean) => engine.setConfig('pages.segmented_storage', on ? 'on' : 'off');
+ const cli = await withEnv(env(), async () => {
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
+ await engine.executeRaw('INSERT INTO sources(id,name,local_path) VALUES($1,$1,$2)', [sourceId, root]);
+ await engine.setConfig('sync.write_through', 'true');
+ await engine.setConfig('facts.extraction_enabled', 'true');
+ await engine.setConfig('mentions.auto_link', 'off');
+ await claimWorktree(engine, sourceId, root);
+ const ctx = { engine, sourceId, remote: false as const, config: { engine: kind, embedding_disabled: true }, dryRun: false, logger: { info() {}, warn() {}, error() {} } };
+ await seed({ setSwitch,
+ put: async (slug, bytes) => { await submitPageMutation(ctx as never, { operation: 'put_page', params: { slug, content: twinPage(bytes), request_id: randomUUID() } }); },
+ imported: async (slug, bytes) => {
+ writeFileSync(join(root, slug + '.md'), canonical(slug, bytes));
+ expect(await importFromFile(engine, join(root, slug + '.md'), slug + '.md', { sourceId, noEmbed: true, bodyPolicy: await readPageBodyPolicy(engine) })).toMatchObject({ status: 'imported' });
+ } });
+ await disposePersistenceConsumer(engine);
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');
+ return registerLocalWriter(engine, 'cli');
+ });
+ const cleanRows = (rows: Array<Record<string, unknown>>) => rows.map(row => Object.fromEntries(Object.entries(row)
+ .filter(([key]) => !/(^id$|_id$|_at$|^valid_from$|^embedding|slug|^source_session$|^created|^updated|^write_origin$)/.test(key))));
+ return {
+ engine, sourceId, root, cli, env, setSwitch,
+ setChatReply: reply => { chatReply = reply; },
+ call: async (name, params, target = String(params.slug)) => {
+ await setSwitch(!inlineSlugs.includes(target));
+ const request = { request_id: randomUUID(), ...params };
+ return withEnv(env(), async () => {
+ // A write still pending after the reply's wait (a page near 24 MiB on PGLite) is replayed with the same request_id until it settles.
+ for (let replay = 0; ; replay++) {
+ const response = await withVerifiedLocalRegistration(engine, cli, () => dispatchToolCall(engine, name, request, {
+ remote: false, config: { engine: kind }, sourceId, logger: { info() {}, warn() {}, error() {} } }));
+ const out = JSON.parse((response.content[0] as { text: string }).text) as Record<string, any>;
+ if (out.code !== 'write_pending' || replay >= 20) return out;
+ }
+ });
+ },
+ view: async slug => {
+ const [row] = await engine.executeRaw<Record<string, any>>(
+ 'SELECT id, body_storage, content_hash, frontmatter, compiled_truth, timeline FROM pages WHERE source_id=$1 AND slug=$2', [sourceId, slug]);
+ const id = Number(row!.id);
+ const stored = row!.body_storage === 'segmented' ? await materializeSegmentedBody(engine, id, sourceId) : { compiled_truth: row!.compiled_truth, timeline: row!.timeline };
+ const neutral = (text: string) => text.split(slug).join('<slug>').replace(/ingested_at: '[^']*'/, "ingested_at: '<seeded>'");
+ return {
+ body: stored, frontmatter: { ...row!.frontmatter, ...(row!.frontmatter?.ingested_at ? { ingested_at: '<seeded>' } : {}) },
+ tags: (await engine.readPageSnapshot(slug, { sourceId }))!.tags, content_hash: row!.content_hash,
+ timeline: cleanRows(await engine.executeRaw('SELECT * FROM timeline_entries WHERE page_id=$1 ORDER BY date, summary', [id])),
+ takes: cleanRows(await engine.executeRaw('SELECT * FROM takes WHERE page_id=$1 ORDER BY row_num', [id])),
+ facts: cleanRows(await engine.executeRaw('SELECT * FROM facts WHERE source_id=$1 AND source_markdown_slug=$2 ORDER BY row_num', [sourceId, slug])),
+ file: existsSync(join(root, slug + '.md')) ? neutral(readFileSync(join(root, slug + '.md'), 'utf8')) : null,
+ };
+ },
+ hits: async term => [...new Set((await engine.searchKeyword(term, { limit: 50 })).map(r => r.slug))].sort(),
+ storageOf: async slug => (await engine.executeRaw<{ body_storage: string }>('SELECT body_storage FROM pages WHERE source_id=$1 AND slug=$2', [sourceId, slug]))[0]!.body_storage,
+ close: async () => {
+ __setChatTransportForTests(null); __setEmbedTransportForTests(null);
+ await disposePersistenceConsumer(engine);
+ await closeEngine();
+ resetGateway();
+ rmSync(dir, { recursive: true, force: true });
+ },
+ };
+}
diff --git a/test/large-pages/segmented-body-unreachable.test.ts b/test/large-pages/segmented-body-unreachable.test.ts
index 05612f5fcc..16a0eae6f1 100644
--- a/test/large-pages/segmented-body-unreachable.test.ts
+++ b/test/large-pages/segmented-body-unreachable.test.ts
@@ -5,7 +5,7 @@
* fields that throw `page_body_segmented` (property read, spread, JSON.stringify,
* assignment), so no caller sees '' where a multi-megabyte body lives; old-shape
* body writes over a segmented row are refused; every whole-body writer (spec top-25
- * rows 11-19) refuses before it writes, leaving segments, manifest, body_generation
+ * rows 11 and 13-19) refuses before it writes, leaving segments, manifest, body_generation
* and content_hash as they were. Inline pages read exactly as before.
* 2. Fails when: a read path builds a segmented page without the guard, a writer
* reaches the database or the file before refusing, or get_page body:'none' stops
@@ -184,13 +184,8 @@ for (const kind of ['pglite', 'postgres'] as const) {
expect(readFileSync(file, 'utf8')).toBe(fileBefore);
// Row 19: concept and enrich fence preservation.
expectSegmented(() => preserveCanonicalFences(snapshot.page, '# replacement\n'));
- // Row 12: tag and timeline writes through the persistence coordinator.
- const tag = await call('add_tag', { slug: SLUG, tag: 'probe', request_id: randomUUID() });
- expect(tag).toMatchObject({ error: 'page_body_segmented' });
- expect(String(tag.message)).toStartWith('add_tag: ');
- const entry = await call('add_timeline_entry', { slug: SLUG, date: '2026-10-03', summary: 'probe', request_id: randomUUID() });
- expect(entry).toMatchObject({ error: 'page_body_segmented' });
- expect(String(entry.message)).toStartWith('add_timeline_entry: ');
+ // Row 12 (tag and timeline writes through the persistence coordinator) writes segmented pages now: a tag as a
+ // metadata flip, a timeline entry through the put path within 24 MiB (segmented-semantic-writes.test.ts).
expect(await state()).toEqual(before);
});
diff --git a/test/large-pages/segmented-semantic-writes-near-ceiling.slow.test.ts b/test/large-pages/segmented-semantic-writes-near-ceiling.slow.test.ts
new file mode 100644
index 0000000000..7279381729
--- /dev/null
+++ b/test/large-pages/segmented-semantic-writes-near-ceiling.slow.test.ts
@@ -0,0 +1,45 @@
+/**
+ * Wave B PR 2 fix lane L (decision #1, option d): the put path of a semantic write on a page stored in segments near
+ * the 24 MiB single-string ceiling.
+ *
+ * 1. Protects: add_timeline_entry on a segmented page within 640 KiB of 24 MiB reads it back whole and writes it as a
+ * normal segmented put, with the result its inline twin gets (body bytes, frontmatter, tags, content_hash,
+ * timeline rows, takes, facts, canonical file); the page stays segmented.
+ * 2. Fails when: the write refuses page_body_segmented below the ceiling, or its result differs from the inline twin's.
+ * 3. Slow lane: two pages near 24 MiB per engine. PGLite always; PostgreSQL when DATABASE_URL is set
+ * (test/postgres-unit-arms.txt). The pages just over 1 MiB and over 24 MiB are segmented-semantic-writes.test.ts.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { PAGE_MAX_BYTES } from '../../src/core/page-size-policy.ts';
+import { openTwinBrain, type TwinBrain } from '../helpers/segmented-twins.ts';
+import { testBackends } from '../helpers/test-backends.ts';
+
+const INLINE = 'people/nia-example';
+const SEGMENTED = 'people/nes-example';
+const BYTES = PAGE_MAX_BYTES - 640 * 1024;
+
+for (const kind of testBackends()) {
+ describe(kind + ': a semantic write on a segmented page near 24 MiB', () => {
+ let brain: TwinBrain;
+ beforeAll(async () => {
+ brain = await openTwinBrain(kind, [INLINE], async seed => {
+ await seed.setSwitch(false);
+ await seed.imported(INLINE, BYTES);
+ await seed.setSwitch(true);
+ await seed.imported(SEGMENTED, BYTES);
+ });
+ expect([await brain.storageOf(INLINE), await brain.storageOf(SEGMENTED)]).toEqual(['inline', 'segmented']);
+ }, 600_000);
+ afterAll(() => brain.close(), 120_000);
+
+ test('add_timeline_entry writes the segmented page as the inline twin is written', async () => {
+ const params = { date: '2026-10-04', summary: 'near ceiling entry' };
+ const inline = await brain.call('add_timeline_entry', { slug: INLINE, ...params });
+ const segmented = await brain.call('add_timeline_entry', { slug: SEGMENTED, ...params });
+ expect(inline).toMatchObject({ status: 'ok' });
+ expect(segmented).toMatchObject({ status: 'ok' });
+ expect(await brain.view(SEGMENTED)).toEqual(await brain.view(INLINE));
+ expect(await brain.storageOf(SEGMENTED)).toBe('segmented');
+ }, 900_000);
+ });
+}
diff --git a/test/large-pages/segmented-semantic-writes.test.ts b/test/large-pages/segmented-semantic-writes.test.ts
new file mode 100644
index 0000000000..7de70f4e72
--- /dev/null
+++ b/test/large-pages/segmented-semantic-writes.test.ts
@@ -0,0 +1,227 @@
+/**
+ * Wave B PR 2 fix lane L (decision #1, option d): semantic writes on pages stored in segments.
+ *
+ * 1. Protects: add_tag / remove_tag on a segmented page of any size flip the tag in page metadata (spec 6.4): no
+ * segment text, manifest row or chunk is written, the generation stays, content_hash and the version move as the
+ * inline tag write moves them, search and get_page see the tag, and a file-backed page's file gets the new
+ * frontmatter with its body bytes unchanged. add_timeline_entry, the takes_* writes, extract_facts' fence write,
+ * gbrain core add / remove / diff and sources reconcile read a segmented page just over 1 MiB back whole and give
+ * the result its inline twin gets (body bytes, frontmatter, tags, content_hash, timeline rows, takes, facts,
+ * canonical file, search hits); above 24 MiB they refuse with page_body_segmented, naming the 24 MiB limit, and
+ * change nothing. The page near 24 MiB is segmented-semantic-writes-near-ceiling.slow.test.ts.
+ * 2. Fails when: a tag write on a segmented page refuses, rewrites or re-chunks its body, or leaves search or
+ * get_page without the tag; a fence or timeline write on a segmented page within 24 MiB refuses or differs from
+ * its inline twin; one above 24 MiB writes anything.
+ * 3. PGLite always; PostgreSQL when DATABASE_URL is set (test/postgres-unit-arms.txt). Cost assertions are row
+ * counts and work counters, never time.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { createHash, randomUUID } from 'node:crypto';
+import { readFileSync, writeFileSync } from 'node:fs';
+import { join } from 'node:path';
+import { buildSegmentedProjection } from '../../src/core/page-body/projection.ts';
+import { PAGE_MAX_BYTES } from '../../src/core/page-size-policy.ts';
+import { segmentedTagWork } from '../../src/core/persistence/page-prepare.ts';
+import { withVerifiedLocalRegistration } from '../../src/core/persistence/identity.ts';
+import { runReconcilePreview } from '../../src/core/persistence/reconcile.ts';
+import { runCore } from '../../src/commands/core.ts';
+import { _resetCliExitVerdictForTests, currentExitCode } from '../../src/core/cli-force-exit.ts';
+import { openTwinBrain, type TwinBrain } from '../helpers/segmented-twins.ts';
+import { testBackends } from '../helpers/test-backends.ts';
+import { withEnv } from '../helpers/with-env.ts';
+
+const INLINE = 'people/ina-example';
+/** Twin slugs have equal lengths, so outputs that print the slug compare equal once it is replaced. */
+const SEGMENTED = 'people/sei-example';
+const HUGE = 'people/hugo-example';
+
+for (const kind of testBackends()) {
+ describe(kind + ': semantic writes on pages stored in segments', () => {
+ let brain: TwinBrain;
+ const call = (name: string, params: Record<string, unknown>, target?: string) => brain.call(name, params, target);
+ const view = (slug: string) => brain.view(slug);
+ const hits = (term: string) => brain.hits(term);
+ const storageOf = (slug: string) => brain.storageOf(slug);
+ const setSwitch = (on: boolean) => brain.setSwitch(on);
+ const env = () => brain.env();
+
+ beforeAll(async () => {
+ brain = await openTwinBrain(kind, [INLINE], async seed => {
+ await seed.setSwitch(false);
+ await seed.put(INLINE, 1_100_000);
+ await seed.setSwitch(true);
+ await seed.put(SEGMENTED, 1_100_000);
+ await seed.imported(HUGE, PAGE_MAX_BYTES + 512 * 1024);
+ });
+ const { engine, sourceId } = brain;
+ await buildSegmentedProjection(engine, { sourceId: brain.sourceId, slug: HUGE });
+ const storage = await brain.engine.executeRaw<{ slug: string; body_storage: string; body_bytes: string | null; sealed: boolean }>(
+ 'SELECT slug, body_storage, body_bytes::text AS body_bytes, text_projection_revision = knowledge_revision AS sealed FROM pages WHERE source_id=$1 ORDER BY slug', [sourceId]);
+ expect(Object.fromEntries(storage.map(r => [r.slug, r.body_storage]))).toEqual({ [HUGE]: 'segmented', [INLINE]: 'inline', [SEGMENTED]: 'segmented' });
+ expect(Number(storage.find(r => r.slug === HUGE)!.body_bytes)).toBeGreaterThan(PAGE_MAX_BYTES);
+ expect(storage.every(r => r.sealed)).toBe(true);
+ }, 600_000);
+
+ afterAll(() => brain.close(), 120_000);
+
+ test('each verb on a segmented page just over 1 MiB gives the inline twin\'s result', async () => {
+ const steps: Array<[string, Record<string, unknown>]> = [
+ ['add_tag', { tag: 'lane-l-probe' }],
+ ['add_tag', { tag: 'lane-l-probe' }],
+ ['add_timeline_entry', { date: '2026-10-03', summary: 'zebracorn timeline milestone' }],
+ ['takes_add', { claim: 'Acme example ships quokkaware in May', kind: 'bet', holder: 'brain', weight: 0.6 }],
+ ['takes_update', { row_num: 1, weight: 0.7 }],
+ ['takes_add', { claim: 'Acme example hires in June', kind: 'bet', holder: 'brain', weight: 0.4 }],
+ ['takes_supersede', { row_num: 2, claim: 'Acme example hires in July' }],
+ ['takes_resolve', { row_num: 1, quality: 'correct' }],
+ ['takes_remove', { row_num: 3 }],
+ ['remove_tag', { tag: 'lane-l-probe' }],
+ ['add_tag', { tag: 'lane-l-kept' }],
+ ];
+ for (const [verb, params] of steps) {
+ const inline = await call(verb, { slug: INLINE, ...params });
+ const segmented = await call(verb, { slug: SEGMENTED, ...params });
+ expect({ verb, error: segmented.error, status: segmented.status }).toEqual({ verb, error: inline.error, status: inline.status });
+ expect(segmented.state ?? segmented.write_request?.state ?? 'committed').not.toBe('failed');
+ expect(await view(SEGMENTED)).toEqual(await view(INLINE));
+ }
+ brain.setChatReply(JSON.stringify({ facts: [{ fact: 'Twin Example adopted a narwhalbot', kind: 'fact', entity: INLINE, confidence: 1, notability: 'high' }] }));
+ expect(await call('extract_facts', { turn_text: 'Synthetic meeting record. Twin Example adopted a narwhalbot.', visibility: 'world', valid_from: '2026-10-15T00:00:00Z' }, INLINE)).toMatchObject({ inserted: 1 });
+ brain.setChatReply(JSON.stringify({ facts: [{ fact: 'Twin Example adopted a narwhalbot', kind: 'fact', entity: SEGMENTED, confidence: 1, notability: 'high' }] }));
+ expect(await call('extract_facts', { turn_text: 'Synthetic meeting record. Twin Example adopted a narwhalbot.', visibility: 'world', valid_from: '2026-10-15T00:00:00Z' }, SEGMENTED)).toMatchObject({ inserted: 1 });
+ const [a, b] = [await view(INLINE), await view(SEGMENTED)];
+ expect(b.facts).toHaveLength(1);
+ expect(b).toEqual(a);
+ expect(await storageOf(SEGMENTED)).toBe('segmented');
+ expect(await storageOf(INLINE)).toBe('inline');
+ for (const term of ['zebracorn']) expect({ term, hits: await hits(term) }).toEqual({ term, hits: [SEGMENTED, INLINE].sort() });
+ // Fence rows (takes, facts) reach search as their fences render them; either twin is a hit exactly when the other is.
+ for (const term of ['quokkaware', 'narwhalbot']) { const found = await hits(term); expect({ term, segmented: found.includes(SEGMENTED) }).toEqual({ term, segmented: found.includes(INLINE) }); }
+ expect((await brain.engine.listPages({ sourceId: brain.sourceId, tag: 'lane-l-kept' } as never)).map(p => p.slug).sort()).toEqual([SEGMENTED, INLINE].sort());
+ const got = await call('get_page', { slug: SEGMENTED, body: 'none' });
+ expect(got.tags).toEqual(['lane-l-kept']);
+ }, 600_000);
+
+ test('gbrain core add, diff and remove on a segmented page give the inline twin\'s result', async () => {
+ const out: string[] = [];
+ const log = console.log, err = console.error;
+ console.log = (...a: unknown[]) => { out.push(a.join(' ')); };
+ console.error = (...a: unknown[]) => { out.push(a.join(' ')); };
+ const core = async (slug: string, args: string[]) => {
+ out.length = 0;
+ await setSwitch(slug === SEGMENTED);
+ await withEnv(env(), () => withVerifiedLocalRegistration(brain.engine, brain.cli, () => runCore(brain.engine, [...args, '--source', brain.sourceId, slug])));
+ return out.join('\n').split(slug).join('<slug>');
+ };
+ const verdict = () => { const code = currentExitCode(); _resetCliExitVerdictForTests(); return code; };
+ const exitCode = process.exitCode;
+ try {
+ for (const slug of [INLINE, SEGMENTED]) await brain.engine.executeRaw(
+ "INSERT INTO core_edit_notices(source_id, slug, actor, base_text, revision) VALUES($1,$2,'agent','before','r1')", [brain.sourceId, slug]);
+ // A page over 1 MiB never fits the core budget (at most 6000 chars), so core add refuses it on budget, as it refuses
+ // the inline twin; before the segmented page was read back whole it refused page_body_segmented.
+ const added = await core(SEGMENTED, ['add']);
+ expect(verdict()).toBe(1);
+ expect(added).toContain('over the 4000-char budget');
+ expect(added).toBe(await core(INLINE, ['add']));
+ expect(verdict()).toBe(1);
+ expect(await view(SEGMENTED)).toEqual(await view(INLINE));
+ const diff = async (slug: string) => { const { since, revision, ...rest } = JSON.parse(await core(slug, ['diff', '--json'])); return { ...rest, since: typeof since, revision: typeof revision }; };
+ const diffed = await diff(SEGMENTED);
+ expect(verdict()).toBe(0);
+ expect(diffed).toMatchObject({ pending: true, before: 'before', revision: 'string' });
+ expect(String(diffed.after)).toContain('Twin Example');
+ expect(diffed).toEqual(await diff(INLINE));
+ expect(verdict()).toBe(0);
+ const removed = await core(SEGMENTED, ['remove']);
+ expect(verdict()).toBe(0);
+ expect(removed).toContain('Already out of core');
+ expect(removed).toBe(await core(INLINE, ['remove']));
+ expect(verdict()).toBe(0);
+ } finally { console.log = log; console.error = err; _resetCliExitVerdictForTests(); process.exitCode = exitCode; }
+ }, 600_000);
+
+ test('sources reconcile previews a drifted segmented page as it previews the inline twin', async () => {
+ const preview = async (slug: string) => {
+ const path = join(brain.root, slug + '.md');
+ const before = readFileSync(path, 'utf8');
+ writeFileSync(path, before.replace('# Twin Example\n', '# Twin Example\n\nA line added in the file.\n'));
+ try {
+ const result = await withEnv(env(), () => withVerifiedLocalRegistration(brain.engine, brain.cli, () => runReconcilePreview(brain.engine, { source_id: brain.sourceId, slug })));
+ return { status: result.status, conflict_paths: result.conflict_paths, protected_paths: result.protected_paths, formatting_only: result.formatting_only,
+ result: JSON.stringify(result.preview.result).split(slug).join('<slug>').replace(/"ingested_at":"[^"]*"/, '"ingested_at":"<seeded>"') };
+ } finally { writeFileSync(path, before); }
+ };
+ expect(await preview(SEGMENTED)).toEqual(await preview(INLINE));
+ }, 600_000);
+
+ describe('over 24 MiB', () => {
+ const counts = async () => {
+ const [row] = await brain.engine.executeRaw<Record<string, string>>(`SELECT p.body_generation::text AS generation, p.content_hash,
+ (SELECT count(*) FROM page_body_manifest m WHERE m.page_id=p.id)::text AS manifest,
+ (SELECT string_agg(m.occurrence_id::text || ':' || encode(m.sha256, 'hex'), ',' ORDER BY m.seq) FROM page_body_manifest m WHERE m.page_id=p.id AND m.gen_to IS NULL) AS live,
+ (SELECT count(*) FROM page_segment_texts t WHERE t.source_id=p.source_id)::text AS texts,
+ (SELECT count(*) FROM content_chunks c WHERE c.page_id=p.id)::text AS chunks
+ FROM pages p WHERE p.source_id=$1 AND p.slug=$2`, [brain.sourceId, HUGE]);
+ return row!;
+ };
+ const fileBody = () => { const file = readFileSync(join(brain.root, HUGE + '.md')); const end = file.indexOf('\n---\n', 4) + 5; return createHash('sha256').update(file.subarray(end)).digest('hex'); };
+
+ test('add_tag and remove_tag flip the tag in metadata without writing a segment, manifest row or chunk', async () => {
+ const before = await counts();
+ const bodyBefore = fileBody();
+ const work = { texts: 0, textBytes: 0, manifest: 0, chunks: 0 };
+ const e = brain.engine as unknown as Record<string, (...args: any[]) => Promise<unknown>>;
+ const originals = { texts: e.stageSegmentTexts, manifest: e.stageManifestRows, chunks: e.stageSegmentChunks };
+ e.stageSegmentTexts = function (this: unknown, ...args: any[]) { work.texts++; work.textBytes += (args[1] as Array<{ body: Uint8Array }>).reduce((n, t) => n + t.body.length, 0); return originals.texts.apply(this, args); };
+ e.stageManifestRows = function (this: unknown, ...args: any[]) { work.manifest++; return originals.manifest.apply(this, args); };
+ e.stageSegmentChunks = function (this: unknown, ...args: any[]) { work.chunks++; return originals.chunks.apply(this, args); };
+ const flips = segmentedTagWork.flips, streams = segmentedTagWork.hashStreams;
+ try {
+ const requestId = randomUUID();
+ const added = await call('add_tag', { slug: HUGE, tag: 'lane-l-huge', request_id: requestId });
+ expect(added).toMatchObject({ status: 'ok', tag: 'lane-l-huge' });
+ // Idempotency as inline: the same request_id replays the committed receipt and flips nothing again.
+ expect((await call('add_tag', { slug: HUGE, tag: 'lane-l-huge', request_id: requestId })).revision).toBe(added.revision);
+ const after = await counts();
+ expect({ ...after, content_hash: '' }).toEqual({ ...before, content_hash: '' });
+ expect(after.content_hash).not.toBe(before.content_hash);
+ expect((await brain.engine.readPageSnapshot(HUGE, { sourceId: brain.sourceId }))!.tags).toEqual(['lane-l-huge']);
+ expect((await brain.engine.listPages({ sourceId: brain.sourceId, tag: 'lane-l-huge' } as never)).map(p => p.slug)).toEqual([HUGE]);
+ expect((await call('get_page', { slug: HUGE, body: 'none' })).tags).toEqual(['lane-l-huge']);
+ const file = readFileSync(join(brain.root, HUGE + '.md'), 'utf8').slice(0, 4096);
+ expect(file).toContain('lane-l-huge');
+ expect(fileBody()).toBe(bodyBefore);
+ expect(await call('remove_tag', { slug: HUGE, tag: 'lane-l-huge' })).toMatchObject({ status: 'ok' });
+ expect(await counts()).toEqual(before);
+ expect(fileBody()).toBe(bodyBefore);
+ expect(work).toEqual({ texts: 0, textBytes: 0, manifest: 0, chunks: 0 });
+ expect(segmentedTagWork.flips - flips).toBe(2);
+ expect(segmentedTagWork.hashStreams - streams).toBe(0);
+ const versions = await brain.engine.executeRaw<{ body_storage: string; body_generation: string }>(
+ "SELECT v.body_storage, v.body_generation::text AS body_generation FROM page_versions v JOIN pages p ON p.id=v.page_id WHERE p.source_id=$1 AND p.slug=$2", [brain.sourceId, HUGE]);
+ expect(versions.map(v => v).length).toBe(2);
+ expect(versions.every(v => v.body_storage === 'segmented' && v.body_generation === before.generation)).toBe(true);
+ } finally { Object.assign(e, { stageSegmentTexts: originals.texts, stageManifestRows: originals.manifest, stageSegmentChunks: originals.chunks }); }
+ }, 600_000);
+
+ test('timeline, takes and facts writes refuse page_body_segmented naming the 24 MiB limit and change nothing', async () => {
+ const before = await counts();
+ const fileBefore = fileBody();
+ const refusals = [
+ await call('add_timeline_entry', { slug: HUGE, date: '2026-10-05', summary: 'never written' }),
+ await call('takes_add', { slug: HUGE, claim: 'Never written', kind: 'bet', holder: 'brain', weight: 0.5 }),
+ ];
+ brain.setChatReply(JSON.stringify({ facts: [{ fact: 'Hugo Example never gets this row', kind: 'fact', entity: HUGE, confidence: 1, notability: 'high' }] }));
+ refusals.push(await call('extract_facts', { turn_text: 'Synthetic meeting record. Hugo Example never gets this row.', visibility: 'world' }, HUGE));
+ for (const refusal of refusals) {
+ expect(JSON.stringify(refusal)).toContain('page_body_segmented');
+ expect(JSON.stringify(refusal)).toContain('24 MiB');
+ }
+ expect(await counts()).toEqual(before);
+ expect(fileBody()).toBe(fileBefore);
+ expect((await brain.engine.executeRaw<{ n: string }>('SELECT count(*)::text AS n FROM facts WHERE source_id=$1 AND source_markdown_slug=$2', [brain.sourceId, HUGE]))[0]!.n).toBe('0');
+ }, 600_000);
+ });
+ });
+}
diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txt
index 4fbc0e19c1..0d6115215a 100644
--- a/test/postgres-unit-arms.txt
+++ b/test/postgres-unit-arms.txt
@@ -129,6 +129,8 @@ test/large-pages/segmented-remember-refusal.test.ts
test/large-pages/segmented-repair-scans.test.ts
test/large-pages/segmented-retained-blocks.test.ts
test/large-pages/segmented-search-dedup.test.ts
+test/large-pages/segmented-semantic-writes-near-ceiling.slow.test.ts
+test/large-pages/segmented-semantic-writes.test.ts
test/large-pages/segmented-shrink-below-ceiling.test.ts
test/large-pages/segmented-storage-visibility.test.ts
test/large-pages/segmented-sweep-budget.test.ts
diff --git a/test/trust-held-removals.test.ts b/test/trust-held-removals.test.ts
index d46dd222c0..291a39209f 100644
--- a/test/trust-held-removals.test.ts
+++ b/test/trust-held-removals.test.ts
@@ -222,7 +222,7 @@ describe('held removals (W1 #6783 §12 (a))', () => {
try {
const slug = 'people/kai-example';
const filler = Array.from({ length: 20_000 }, (_, i) => `Kai note line ${i} about the acme-example offsite and its agenda.`).join('\n');
- // takes_* verbs refuse a segmented page, so the takes are added while the page is inline and a publish over 1 MiB promotes it.
+ // The takes are added while the page is inline and a publish over 1 MiB promotes it.
await run(b.local, 'put_page', { slug, content: page('Kai', 'Kai.\n\n## Timeline\n\n- **2026-01-05** | note — Kai joined acme-example\n- **2026-02-07** | note — Kai moved to Seoul') });
for (const claim of ['Kai will lead the offsite', 'Kai ships the agenda']) await run(b.local, 'takes_add', { slug, claim, kind: 'bet', holder: 'world', weight: 0.6 });
const storage = async () => (await engine.executeRaw<{ body_storage: string }>('SELECT body_storage FROM pages WHERE id=$1', [await pageId(b, slug)]))[0]!.body_storage;
@@ -244,9 +244,11 @@ describe('held removals (W1 #6783 §12 (a))', () => {
const put = await run(b.local, 'put_page', { slug, content: edited, expected_revision: current.revision });
expect(put.contested?.proposal_refs).toHaveLength(3);
expect(await storage()).toBe('segmented');
- // takes_remove refuses a segmented page for every writer before any guard, so it files nothing.
+ // takes_remove reads a segmented page within 24 MiB back whole, as it reads an inline page: the held rewrite of take 2
+ // leaves its database row and the fence apart, so the remove refuses before any guard and files nothing.
const refused = await run(b.remote, 'takes_remove', { slug, row_num: takes[1]!.row_num }).then(() => null, (error: unknown) => error) as any;
- expect(refused?.code).toBe('page_body_segmented');
+ expect(refused?.code).toBe('invalid_params');
+ expect(String(refused?.message)).toContain("Row #2's database copy disagrees with the page's takes fence");
const pending = (await listTrustProposals(engine, { sourceId: b.sourceId })).filter(p => p.status === 'pending');
expect(pending.map(p => `${p.target_table}:${p.target_id}`).sort()).toEqual([`takes:${takes[0]!.id}`, `takes:${takes[1]!.id}`, `timeline_entries:${timeline[0]!.id}`].sort());
for (const proposal of pending) expect((await decideTrustProposal(engine, proposal.id, 'accept', owner)).status).toBe('accepted');