Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

large pages PR 2 lane 2e2: linearity coverage, Postgres arms and key-files entry for the new passes

garrytanfaa6af627cb8
diff --git a/docs/architecture/key-files/core-services-2-continued.md b/docs/architecture/key-files/core-services-2-continued.md
index a6a634c557..21b27e176f 100644
--- a/docs/architecture/key-files/core-services-2-continued.md
+++ b/docs/architecture/key-files/core-services-2-continued.md
@@ -19,7 +19,8 @@ The page-state concurrency foundation under `src/core/page-state/` and the share
- `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), `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/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), `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`.
-- `src/core/page-body/segment-blocks.ts` + `segment-links.ts` + `segment-takes.ts` — Wave B PR 2 (spec 8, full-pass mode): the derived passes over a segmented body, O(page) work and O(segment) memory, not yet incremental. `bodyBlocks(engine, page, { regions?, separator? })` yields the trusted, withdrawal-overlaid joined body one block at a time (a segment, or a run joined across forced cuts, refused above `BLOCK_MAX_BYTES` with `page_body_segmented`), so each block starts where the parsers start fresh; `truthLead` reads a bounded lead; `readGarbageCollector` forces a collection every 4 MiB read; `detachedValue` copies a result kept past its block so it pins no segment text; `segmentedPassWork` counts the passes' work for the linearity test. `extractSegmentedPageLinks` runs `extractBodyLinks` over each block in a window (`bodyWindows`: the whole blocks before it, 4096 chars after, the headings still open), with the role phrases a first pass found (`segmentedRoleText`), and merges candidates in `extractPageLinks` order, plus the temporal inputs (`TemporalBody`). `parseTakesFenceBlocks` gives `parseTakesFence` of the joined body. Consumers: link preparation and the links effect, stale-links maintenance, source reconciliation, the sweep, `extract links|timeline|takes --source db`, the mention pass (`pageMentions`), the canonical prior view (`segmentedPriorView`), `segmentedTimelineText`, the chronicle judge and the facts planner (`planSegmentedExtraction`). Tests: `test/large-pages/segmented-derived-parity.test.ts`, `segmented-derived-passes.test.ts`, `segmented-derived-linear.test.ts`, `segmented-derived-memory.slow.test.ts`, `segmented-derived-work.test.ts`.
+- `src/core/page-body/segment-blocks.ts` + `segment-links.ts` + `segment-takes.ts` — Wave B PR 2 (spec 8, full-pass mode): the derived passes over a segmented body, O(page) work and O(segment) memory, not yet incremental. `bodyBlocks(engine, page, { regions?, separator?, want? })` yields the trusted, withdrawal-overlaid joined body one block at a time (a segment, or a run joined across forced cuts, refused above `BLOCK_MAX_BYTES` with `page_body_segmented`; `want` skips a run unread), so each block starts where the parsers start fresh; `truthLead` reads a bounded lead; `readGarbageCollector` forces a collection every 4 MiB read; `detachedValue` copies a result kept past its block so it pins no segment text; `segmentedPassWork` counts the passes' work for the linearity test. `extractSegmentedPageLinks` runs `extractBodyLinks` over each block in a window (`bodyWindows`: the whole blocks before it, 4096 chars after, the headings still open), with the role phrases a first pass found (`segmentedRoleText`), and merges candidates in `extractPageLinks` order, plus the temporal inputs (`TemporalBody`). `parseTakesFenceBlocks` gives `parseTakesFence` of the joined body. Consumers: link preparation and the links effect, stale-links maintenance, source reconciliation, the sweep, `extract links|timeline|takes --source db`, the mention pass (`pageMentions`), the canonical prior view (`segmentedPriorView`), `segmentedTimelineText`, the chronicle judge and the facts planner (`planSegmentedExtraction`). Tests: `test/large-pages/segmented-derived-parity.test.ts`, `segmented-derived-passes.test.ts`, `segmented-derived-linear.test.ts`, `segmented-derived-memory.slow.test.ts`, `segmented-derived-work.test.ts`.
+- `src/core/page-body/segment-facts.ts` + `segment-conversation.ts` — Wave B PR 2 lane 2e2 (spec 8, full-pass mode): the facts fence reconcile and conversation facts over a segmented body. `segmentedFactsFenceView` is `factsFenceView` (facts-fence.ts: each section's parsed fence, which sections hold one, and the #3625 timeline marker) read from the segments: one SQL query selects the live manifest rows that carry facts slots, a forced cut, or a begin/end marker (bytea `position`, nothing transferred), and `bodyBlocks`' `want` option reads only the runs holding them; the segmenter never cuts inside a fence, so a fence lies in one block (a longer one is a forced run, refused above `BLOCK_MAX_BYTES` with `page_body_segmented`), and joining one across blocks is a bounded fallback. `segmentedBodyMatchesFile` is `canonicalCacheState`'s stale-cache check for a segmented page: the canonical file streamed through `BodyScanner` against the stored regions, by length and SHA-256. `readSegmentedConversationInput` gives `readConversationInput` (conversation-parser/body.ts) the summary body through ranged reads: whole within `CONVERSATION_WINDOW_BYTES` (`PAGE_MAX_BYTES`), else the newest whole segments that fit (never starting inside a forced run) with the window's `fallbackDate` from its first segment's entry state; extract-conversation-facts parses that window, passes the date to the parse and the extractor, and writes a `tail_window` receipt. Each loop counts its reads in `segmentedPassWork`. Consumers: `runExtractFacts` (`planFenceReconcile`, the stale-cache guard, the managed fence-facts request), the sweep's fence candidates (segmented pages with facts slots), `extract-conversation-facts`. Tests: `test/large-pages/segmented-facts-reconcile.test.ts`, `segmented-conversation-facts.test.ts`, `segmented-derived-linear.test.ts`.
- `src/core/page-window/bounded-lead.ts` — leads, snippets and synopses read a bounded prefix, never the whole body: fan-out SQL selects `boundedBodyPrefixSql(alias)` (`left(coalesce(alias.compiled_truth, alias.truth_lead), 65536)`: a segmented page's NULL body falls back to its stored lead; the one COALESCE of body and lead the page body reader ratchet allows by name), `boundedRawPrefix` cuts a body at 64 KiB on a code point, and `overlaidBoundedRows` / `overlaidBoundedPrefix` replace a prefix holding a `gbrain:facts:begin` marker with the prefix of the withdrawal-overlaid body (one batched `readPageSnapshotsBatch` read; a page it no longer returns, or a failed read, gets an empty lead). A segmented page's row carries its stored `truth_lead`; when that lead holds a facts fence it is overlaid alone with the withdrawal ledger the snapshot read returns (`overlayCanonicalBodies`, then the same 64 KiB cut), never by reading segments. `pageLeadSource` gives getPage callers (exact-slug and alias snippets) a page's compiled truth, or a segmented page's `truth_lead` without touching its throwing body getters. `projectedLead` is that prefix through `boundedProjectedPrefix` (`document.ts`). Consumers: the exact-slug tier (`exact-lookup.ts`) and alias injection (`alias-hop.ts`) snippets, relational hydrate, the reflex pointer synopsis (`retrieval-reflex.ts` `safeSynopsis`: world-only reads take the projected prefix, the trusted entity-card widening the raw prefix through its own fence strip), the entity card's hit row and `entity names` leads, and think's anchor and window-floor rows (`think/gather.ts`: the raw overlaid prefix for the trusted local CLI, the projected prefix otherwise). Small pages render as before. Pinned by `test/bounded-lead.test.ts` and `test/large-pages/segmented-leads.test.ts`.
- `src/core/page-window/document.ts` — the one read projection every remote window, outline and lead slices: `projectPageText` (fence overlay split, `sanitizeRemoteBody` + `credentialSafeProjection`, timeline after `TIMELINE_SEPARATOR`), `pageDocument` / `readPageDocument` (UTF-8 bytes + timeline byte offset, with the page's fence overlay), `chunkDocumentSpan` + `spanHoldsChunk` (a chunk's stored `projected_byte_*` span mapped into the document and verified), `boundedProjectedPrefix`, `locateChunksByStoredSpans` (byte spans to string offsets in one pass), `DEFAULT_INLINE_BODY_BYTES` (256 KB).
- `src/core/page-window/window.ts` — byte/line window arithmetic on a UTF-8 buffer: windows snap to code points and line starts (`windowFrom`, `windowForLines`, `windowForBytes`, `windowAround`; a lone line longer than the window is cut on a code point as `forced_cut`), `pageOutline` (single pass: ATX headings outside code fences, or 64 KiB blocks for pages with fewer than two headings, with date ranges, paged by `from`/`limit`), and the opaque revision-bound cursor (`gpw1.`).
diff --git a/test/large-pages/segmented-derived-linear.test.ts b/test/large-pages/segmented-derived-linear.test.ts
index 6aa7feac56..a4da7f12b6 100644
--- a/test/large-pages/segmented-derived-linear.test.ts
+++ b/test/large-pages/segmented-derived-linear.test.ts
@@ -3,8 +3,9 @@
* segmented page do O(page) work.
*
* Protects: links (with temporal inputs), takes, timeline (entries and the
- * stored canonical map), mentions and the watermark planner, run over a
- * segmented page, count their work in `segmentedPassWork`: bytes read, units
+ * stored canonical map), mentions, the watermark planner, the facts fence
+ * view, the stale-cache file comparison and the conversation parser input,
+ * run over a segmented page, count their work in `segmentedPassWork`: bytes read, units
* of the blocks yielded and of the link windows built around them, and units
* copied past a block (a takes fence join, the planner's tail window). Counts,
* not CPU time, so a co-tenant cannot move them.
@@ -17,10 +18,12 @@
* Why existing coverage misses it: segmented-derived-parity checks results and
* reads per call; segmented-derived-memory bounds memory, not work.
* Seams: `segmentedPassWork` (@internal counters in segment-blocks.ts).
- * Measured (deterministic; per byte at n, doubling ratio): bytes 6.86 x2.00
+ * Measured (deterministic; per byte at n, doubling ratio): bytes 10.82 x1.99
* (seven page reads: role phrases, link windows, takes, timeline, canonical
- * timeline, mentions, the planner's truth), blocks 5.88 x2.00, windows 2.00
- * x2.00 (a window holds the whole block before its own), carry 0.52 x1.99.
+ * timeline, mentions, the planner's truth; the file read twice and the stored
+ * body once for the stale-cache check; the conversation input; the fence view
+ * reads only its marker segments), blocks 5.95 x1.99, windows 2.00 x2.00 (a
+ * window holds the whole block before its own), carry 0.52 x1.99.
* Prefix-re-reading driver (n = 1 MiB): bytes and blocks x2.68.
*/
import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
@@ -31,6 +34,12 @@ import { extractSegmentedPageLinks } from '../../src/core/page-body/segment-link
import { bodyBlocks, segmentedPassWork } from '../../src/core/page-body/segment-blocks.ts';
import { parseTakesFenceBlocks } from '../../src/core/page-body/segment-takes.ts';
import { TAKES_FENCE_BEGIN, TAKES_FENCE_END } from '../../src/core/takes-fence.ts';
+import { FACTS_FENCE_BEGIN, FACTS_FENCE_END } from '../../src/core/facts-fence.ts';
+import { segmentedBodyMatchesFile, segmentedFactsFenceView } from '../../src/core/page-body/segment-facts.ts';
+import { readSegmentedConversationInput } from '../../src/core/page-body/segment-conversation.ts';
+import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
import { segmentedTimelineText } from '../../src/core/timeline-extract.ts';
import { storedCanonicalTimeline } from '../../src/core/persistence/canonical-projections.ts';
import { pageMentions } from '../../src/core/mentions/pass.ts';
@@ -43,9 +52,10 @@ import { countWorkAsync, describeWork, linearityViolations, MAX_DOUBLING_RATIO,
const MB = 1024 * 1024;
/** Per input byte, about 2x the measured value or more. */
-const PER_BYTE = { 'pass.bytes': 14, 'pass.blocks': 12, 'pass.windows': 4, 'pass.carry': 1.2 };
+const PER_BYTE = { 'pass.bytes': 22, 'pass.blocks': 12, 'pass.windows': 4, 'pass.carry': 1.2 };
let engine: PGLiteEngine;
+let dir: string;
/** `bytes` of linked, dated, mentioning conversation with a takes fence mid-page and dated bullets in the timeline. */
function page(bytes: number): string {
@@ -55,6 +65,8 @@ function page(bytes: number): string {
parts.push(`## Section ${i}\n\n${conversationBody(64 * 1024, { seed: 100 + i })}\n\n`
+ `- **2026-03-${String(10 + (i % 18)).padStart(2, '0')}** Met [[people/alice-example]] and [Acme Example](../companies/acme-example.md) about launch ${i}; `
+ `Alice Example reviewed it.\n\n`);
+ if (i === Math.floor(units / 3)) parts.push(`## Facts\n\n${FACTS_FENCE_BEGIN}\n| # | claim | kind | confidence | visibility | notability | valid_from | valid_until | source | context |\n`
+ + `|---|-------|------|------------|------------|------------|------------|-------------|--------|---------|\n| 1 | Ships quarterly | fact | 1.0 | world | medium | | | notes | |\n${FACTS_FENCE_END}\n\n`);
if (i === Math.floor(units / 2)) parts.push(`${TAKES_FENCE_BEGIN}\n| # | claim | kind | who | weight | since | source |\n|---|-------|------|-----|--------|-------|--------|\n`
+ `| 1 | Acme ships quarterly | fact | world | 1.0 | 2026-01 | notes |\n${TAKES_FENCE_END}\n\n`);
}
@@ -86,6 +98,9 @@ async function passes(slug: string): Promise<void> {
const plan = await planSegmentedExtraction(engine, Number(p.id), { pipelineVersion: EXTRACTION_PIPELINE_VERSION.facts_backstop, bytes: half, sha256: '0'.repeat(64) },
{ cap: 8000, pipeline: 'facts_backstop', emptyTail: 'skip' });
expect(plan.mode).toBe('head');
+ expect((await segmentedFactsFenceView(engine, p)).body.facts).toHaveLength(1);
+ expect(await segmentedBodyMatchesFile(engine, p, join(dir, `${slug.replace('/', '-')}.md`))).toBe('fresh');
+ expect((await readSegmentedConversationInput(engine, p)).window).toBeUndefined();
}
/** The deliberately quadratic driver: re-reads the body's prefix through bodyBlocks before each block. */
@@ -103,16 +118,19 @@ const sample = async (bytes: number, slug: string, run: (slug: string) => Promis
({ bytes, work: await countWorkAsync({ pass: segmentedPassWork }, () => run(slug)) });
beforeAll(async () => {
+ dir = mkdtempSync(join(tmpdir(), 'segmented-linear-'));
engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema();
await engine.setConfig('pages.segmented_storage', 'on');
await engine.putPage('people/alice-example', { type: 'person', title: 'Alice Example', compiled_truth: 'Fixture.', timeline: '', frontmatter: {} }, { sourceId: 'default' });
await engine.putPage('companies/acme-example', { type: 'company', title: 'Acme Example', compiled_truth: 'Fixture.', timeline: '', frontmatter: {} }, { sourceId: 'default' });
for (const [slug, bytes] of [['notes/linear-1', MB], ['notes/linear-2', 2 * MB], ['notes/linear-4', 4 * MB], ['notes/linear-8', 8 * MB]] as const) {
- expect(await importFromContent(engine, slug, page(bytes), { sourceId: 'default', noEmbed: true })).toMatchObject({ status: 'imported' });
+ const content = page(bytes);
+ writeFileSync(join(dir, `${slug.replace('/', '-')}.md`), content);
+ expect(await importFromContent(engine, slug, content, { sourceId: 'default', noEmbed: true })).toMatchObject({ status: 'imported' });
}
}, 600_000);
-afterAll(async () => { await engine.disconnect(); });
+afterAll(async () => { await engine.disconnect(); rmSync(dir, { recursive: true, force: true }); });
describe('derived pass work over a segmented page', () => {
test('work per byte is bounded and doubles with the page', async () => {
diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txt
index 53a6e1f4db..de6a951c65 100644
--- a/test/postgres-unit-arms.txt
+++ b/test/postgres-unit-arms.txt
@@ -78,6 +78,7 @@ test/large-pages/remote-window-privacy.test.ts
test/large-pages/sealed-segmented-search.test.ts
test/large-pages/segment-vector-reuse.test.ts
test/large-pages/segmented-body-unreachable.test.ts
+test/large-pages/segmented-conversation-facts.test.ts
test/large-pages/segmented-derived-parity.test.ts
test/large-pages/segmented-derived-passes.test.ts
test/large-pages/segmented-derived-work.test.ts
@@ -85,6 +86,7 @@ test/large-pages/segmented-embedding-paths.test.ts
test/large-pages/segmented-embedding.test.ts
test/large-pages/segmented-evidence-read-cost.test.ts
test/large-pages/segmented-evidence.test.ts
+test/large-pages/segmented-facts-reconcile.test.ts
test/large-pages/segmented-leads.test.ts
test/large-pages/segmented-search-dedup.test.ts
test/large-pages/segmented-shrink-below-ceiling.test.ts