Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

Wave B lane 1d: adapt to the 1b-ii segmenter and chunker (region entry states, per-region fence trust in the occurrence key, facts overlay per batch), ratchet rows

garrytan08b1f18329fe
diff --git a/scripts/check-orphan-modules.mjs b/scripts/check-orphan-modules.mjs
index 7b6be53074..4fd946fb5b 100644
--- a/scripts/check-orphan-modules.mjs
+++ b/scripts/check-orphan-modules.mjs
@@ -53,10 +53,6 @@ const ALLOWLIST = new Map([
// string in a reviewer-visible edit. Modules reached from `scripts/**` carry
// reason 'script-reachable', which the guard verifies.
const PERMITTED_TEST_ONLY = [
- { path: 'src/core/page-body/entry-state.ts', reason: 'held: Wave B PR 1 segmenter state; the segmented ingest path (spec 13 PR 1 integration) imports it' },
- { path: 'src/core/page-body/region-scan.ts', reason: 'held: Wave B PR 1 streaming region scan; the segmented ingest path (spec 13 PR 1 integration) imports it' },
- { path: 'src/core/page-body/segmenter.ts', reason: 'held: Wave B PR 1 segmenter; the segmented ingest path (spec 13 PR 1 integration) imports it' },
- { path: 'src/core/page-body/segment-chunks.ts', reason: 'held: Wave B PR 1 per-segment chunker; the segmented projection (spec 13 PR 1 integration) imports it' },
{ path: 'src/core/bootstrap/template-repo.ts', reason: 'script-reachable' },
{ path: 'src/eval/longmemeval/diagnostics.ts', reason: 'script-reachable' },
{ path: 'src/eval/longmemeval/evidence-brief.ts', reason: 'held: eval-only wave 1 brief builder (10x memory advantage plan A3), loaded by path from gbrain-evals eval/runner/pilot; product wiring is plan item A8, conditional on the A5 pilot' },
diff --git a/scripts/page-body-readers-baseline.tsv b/scripts/page-body-readers-baseline.tsv
index 52a95a933b..bf8fadf83c 100644
--- a/scripts/page-body-readers-baseline.tsv
+++ b/scripts/page-body-readers-baseline.tsv
@@ -144,9 +144,9 @@ src/core/cycle/phantom-redirect.ts phantomHasResidue field SEGW phantom stubs ar
src/core/cycle/phantom-redirect.ts tryRedirectPhantom call:contentHash META hash of the reparsed inline file
src/core/cycle/phantom-redirect.ts tryRedirectPhantom call:refreshPageBody SEGW assertInlineBody on the canonical first
src/core/cycle/phantom-redirect.ts tryRedirectPhantom field SEGW canonical target asserted inline before the disk fence append; per-phantom throw is logged and the walk continues
-src/core/cycle/propose-takes.ts listCandidatePages sql STREAM
src/core/cycle/propose-takes.ts ProposeTakesPhase.process call:contentHash META
src/core/cycle/propose-takes.ts ProposeTakesPhase.process field STREAM
+src/core/cycle/propose-takes.ts listCandidatePages sql STREAM
src/core/cycle/synthesize-concepts.ts runPhaseSynthesizeConcepts field INLINE
src/core/cycle/synthesize-concepts.ts runPhaseSynthesizeConcepts sql INLINE
src/core/cycle/synthesize-postprocess.ts postprocessManagedSynthesis call:serializePageToMarkdown INLINE
@@ -165,8 +165,8 @@ src/core/cycle/synthesize.ts writeSummaryPage field INLINE
src/core/cycle/transcript-discovery.ts discoverConversationPages field STREAM
src/core/cycle/transcript-discovery.ts discoverConversationPages sql STREAM
src/core/eligibility/fence-overlay.ts loadFenceChunkOverlay field STREAM
-src/core/eligibility/scan.ts assess field STREAM
src/core/eligibility/scan.ts SELECT sql STREAM
+src/core/eligibility/scan.ts assess field STREAM
src/core/embed-consent.ts estimateEmbedBackfillUsd sql META
src/core/embed-stale-images.ts embedStaleImages sql INLINE
src/core/embedding-migration-worst-case.ts REPROJECTED_PAGE sql META
@@ -178,10 +178,10 @@ src/core/engine-sql/chunks.ts listChunklessPagesWithContent sql STREAM lane 1e f
src/core/engine-sql/chunks.ts listEmbeddingStateRows sql META lane 1e file: octet_length metadata
src/core/engine-sql/page-body.ts createSegmentedPageShell sql NONE not a reader: the segmented storage writer sets the body columns NULL on the shell row
src/core/engine-sql/page-body.ts flipBodyGeneration sql NONE not a reader: the generation flip sets the body columns NULL and the segmented body columns
+src/core/engine-sql/pages.ts PAGE_VERSION_COLUMNS sql SEGW lane 1e: versions of segmented pages carry no body
src/core/engine-sql/pages.ts listCorpusSample sql LEAD segmented pages excluded from the sample in SQL (skip)
src/core/engine-sql/pages.ts listPrefixSampledPages sql LEAD segmented pages excluded from the sample in SQL (skip)
src/core/engine-sql/pages.ts listStalePagesForExtraction sql STREAM segmented pages skipped in SQL, still counted by countStalePagesForExtraction (visible as stale)
-src/core/engine-sql/pages.ts PAGE_VERSION_COLUMNS sql SEGW lane 1e: versions of segmented pages carry no body
src/core/engine-sql/pages.ts putPage call:contentHash META hash of the incoming inline body
src/core/engine-sql/pages.ts putPage field SEGW incoming PageInput body (a string); see putPage sql
src/core/engine-sql/pages.ts putPage sql SEGW blank-guard reads body_bytes for a segmented page (an empty put over it refuses); a non-empty put over a segmented row is refused by the body-storage CHECK
@@ -299,21 +299,27 @@ src/core/ops/pages.ts stripPrivacyFencesForRemoteReader field STREAM segmented p
src/core/output/post-write.ts runPostWriteLint field INLINE
src/core/output/validators/link.ts linkValidator field INLINE
src/core/output/validators/triple-hr.ts tripleHrValidator field INLINE
-src/core/output/writer.ts runValidators field INLINE
src/core/output/writer.ts WriteTxImpl.createEntity call:putPage INLINE
src/core/output/writer.ts WriteTxImpl.createEntity field INLINE
src/core/output/writer.ts WriteTxImpl.setCompiledTruth call:putPage INLINE
src/core/output/writer.ts WriteTxImpl.setCompiledTruth field INLINE
src/core/output/writer.ts WriteTxImpl.setFrontmatterField call:putPage INLINE
src/core/output/writer.ts WriteTxImpl.setFrontmatterField field INLINE
+src/core/output/writer.ts runValidators field INLINE
src/core/oversized-backfill.ts PAGE_BYTES_SQL sql SEGW
src/core/oversized-backfill.ts reindexPage call:serializeMarkdown SEGW
src/core/oversized-backfill.ts reindexPage field SEGW
src/core/page-body/body-scan.ts scanMarkdownString field NONE not a stored body: scans an incoming markdown string for the segmenter
src/core/page-body/content-hash-stream.ts ContentHashStream.fromState field NONE not a stored body: resumes the streaming content hash over incoming text
src/core/page-body/content-hash-stream.ts streamingContentHash field NONE not a stored body: hashes an incoming page streamed region by region
+src/core/page-body/ingest.ts materializeSegmentedBody field STREAM the segment reader's string form, for single-string write paths; callers materialize only bodies within PAGE_MAX_BYTES
+src/core/page-body/ingest.ts stageBody field NONE not a stored body: the write's region byte streams and the per-region leads it computes
src/core/page-body/page-shape.ts pageBodyBytes field INLINE inline branch of pageBodyBytes; a segmented page answers body_bytes
src/core/page-body/schema.ts PAGE_GENERATION_BUMP_FN_SQL sql STREAM trigger DDL: compares the body columns of inline rows; segmented rows compare body_generation (lane 1a)
+src/core/page-body/segmenter.ts Segmenter.blocked field NONE not the page body: st.timeline is the segmenter's timeline-run parser state
+src/core/page-body/segmenter.ts Segmenter.line field NONE not the page body: st.timeline is the segmenter's timeline-run parser state
+src/core/page-body/segmenter.ts Segmenter.piece field NONE not the page body: st.timeline is the segmenter's timeline-run parser state
+src/core/page-body/streamed-import.ts importScanned field LEAD bounded heads of the streamed file's regions for the sanity and type checks; the body itself streams to the segmenter
src/core/page-embedding-budget.ts pageBytes field META lane 1e file: body_bytes for segmented pages
src/core/page-embedding-budget.ts planPageEmbedding field META lane 1e file: body_bytes for segmented pages
src/core/page-embedding-budget.ts readPageSizeStates sql META lane 1e file: body_bytes for segmented pages
@@ -403,6 +409,8 @@ src/core/persistence/reconcile-prepare.ts prepareReconcileResult call:serializeP
src/core/persistence/reconcile-prepare.ts prepareReconcileResult field INLINE
src/core/persistence/reconcile-state.ts readReconcileState sql INLINE
src/core/persistence/reconcile.ts runReconcilePreview call:serializePageToMarkdown SEGW
+src/core/persistence/segmented-apply.ts demoteSegmentedPage sql INLINE demotion: the row turns inline with an empty body that the inline write in the same transaction fills
+src/core/persistence/segmented-apply.ts stageSegmentedImport field INLINE input.page is the parsed incoming write (strings within PAGE_MAX_BYTES), never a stored segmented row
src/core/persistence/semantic-pages.ts prepareSemanticPageMutation call:serializePageToMarkdown SEGW assertInlineBody first
src/core/persistence/semantic-pages.ts prepareSemanticPageMutation field SEGW assertInlineBody after the identity check (tag and timeline writes refuse)
src/core/persistence/sync-prepare.ts prepareManagedSyncCode field INLINE code pages are never segmented
@@ -526,6 +534,3 @@ src/eval/brainbench/metrics/trust-reads.ts canaryPersisted sql STREAM
src/eval/chronicle/harness.ts seedChronicleEvalCorpus call:putPage SEGW
src/eval/longmemeval/call-plan.ts planPages call:prepareMarkdownChunks INLINE
src/eval/longmemeval/call-plan.ts planPages field INLINE
-src/core/page-body/segmenter.ts Segmenter.blocked field NONE not the page body: st.timeline is the segmenter's timeline-run parser state
-src/core/page-body/segmenter.ts Segmenter.line field NONE not the page body: st.timeline is the segmenter's timeline-run parser state
-src/core/page-body/segmenter.ts Segmenter.piece field NONE not the page body: st.timeline is the segmenter's timeline-run parser state
diff --git a/src/core/page-body/ingest.ts b/src/core/page-body/ingest.ts
index 72b551d4ca..499758e1c9 100644
--- a/src/core/page-body/ingest.ts
+++ b/src/core/page-body/ingest.ts
@@ -21,16 +21,18 @@ import { stepFenceWalk, type FenceWalk } from '../fence-scan.ts';
import { BODY_LEAD_BYTES, BODY_STAGING_HARD_MS, BODY_STAGING_IDLE_MS, STAGE_BATCH_BYTES } from './limits.ts';
import type { BodyRegion, BodyStagingKind, BodyStorage, JsonObject, ManifestRow, ManifestRowInput, SegmentChunkInput,
SegmentedBodyColumns, SegmentTextInput } from './types.ts';
-import { segmentStream, SEGMENTER_VERSION, type SegmentOut } from './segmenter.ts';
-import { initialEntryState } from './entry-state.ts';
+import { segmentProjectionParts, segmentStream, SEGMENTER_VERSION, type StoredRegion } from './segmenter.ts';
+import { initialEntryState, readEntryState, timelineEntryState, type EntryState } from './entry-state.ts';
import { ContentHashStream } from './content-hash-stream.ts';
import { prepareSegmentChunks } from './segment-chunks.ts';
import { reuseSegmentChunkVectors } from '../import-chunk-reuse.ts';
+import { newFenceChunkBudget } from '../markdown-chunks.ts';
+import { loadFenceChunkOverlay } from '../eligibility/fence-overlay.ts';
const utf8 = new TextDecoder('utf-8', { fatal: true });
/** The live page a segmented write replaces (null: create). */
-export interface SegmentedLivePage { id: number; generation: number; storage: BodyStorage; title: string; type: string }
+export interface SegmentedLivePage { id: number; generation: number; storage: BodyStorage; title: string; type: string; flags: JsonObject | null }
/** Who stages, for the `page_body_stagings` row (a GC root while open). */
export interface SegmentedStagingOwner { kind: BodyStagingKind; principalKind: string; principalId: string; baseRevision: string | null }
@@ -46,6 +48,8 @@ export interface SegmentedBodyInput {
/** The stored stream of each region (sanitized, valid UTF-8). */
truth: AsyncIterable<Uint8Array>;
timeline: AsyncIterable<Uint8Array>;
+ /** The timeline region is not empty (the truth then ends at `region_end`, not `eof`). */
+ hasTimeline: boolean;
/** Page-global facts known at EOF (pass 1): `fence_trust`, `timeline_split`, ... */
flags: JsonObject;
/** Body bytes as declared by the source (exact for strings, the file size for streams). */
@@ -119,7 +123,13 @@ export function stringBodyFlags(truth: string, timeline: string): JsonObject {
const hex = (bytes: Uint8Array) => Buffer.from(bytes).toString('hex');
const sameBytes = (a: Uint8Array, b: Uint8Array) => Buffer.from(a).equals(Buffer.from(b));
-const occurrenceKey = (sha256: Uint8Array, entryState: unknown) => `${hex(sha256)}|${stableJson(entryState)}`;
+/** The whole-region fence trust a region's stored regions are computed under (body_flags). */
+export function regionTrust(flags: JsonObject | null | undefined, region: BodyRegion): 'trusted' | 'void' {
+ return (region === 'truth' ? flags?.fence_trust : flags?.timeline_fence_trust) === 'void' ? 'void' : 'trusted';
+}
+
+/** An occurrence is its bytes, entry state and the trust its stored regions were computed under: a trust flip rechunks the region. */
+const occurrenceKey = (sha256: Uint8Array, entryState: unknown, trust: 'trusted' | 'void') => `${hex(sha256)}|${stableJson(entryState)}|${trust}`;
/** Every coordinate of a live row equals the row the new segment would get, so the row stays. */
function rowUnchanged(live: ManifestRow, next: ManifestRowInput): boolean {
@@ -171,8 +181,9 @@ async function stageBody(engine: BrainEngine, input: SegmentedBodyInput, staging
const liveRows = live ? await engine.readManifest(live.id) : [];
const byKey = new Map<string, ManifestRow[]>();
for (const row of liveRows) {
- const key = occurrenceKey(row.sha256, row.entryState);
- byKey.set(key, [...(byKey.get(key) ?? []), row]);
+ const key = occurrenceKey(row.sha256, row.entryState, regionTrust(live!.flags, row.region));
+ const same = byKey.get(key);
+ if (same) same.push(row); else byKey.set(key, [row]);
}
const batchBytes = STAGE_BATCH_BYTES[engine.kind];
const expectedGeneration = input.live?.generation ?? 0;
@@ -196,17 +207,21 @@ async function stageBody(engine: BrainEngine, input: SegmentedBodyInput, staging
let texts = 0, byteStart = 0, lineStart = 0, truthBytes = 0, lines = 0;
const leads: Record<BodyRegion, string> = { truth: '', timeline: '' };
let hasProtected = false;
+ let truthExit: EntryState = initialEntryState({ region: 'truth' });
for (const region of ['truth', 'timeline'] as const) {
const stream = region === 'truth' ? input.truth : input.timeline;
+ const entry = region === 'truth' ? truthExit : timelineEntryState(truthExit);
+ const end = region === 'truth' && input.hasTimeline ? 'region_end' : 'eof';
let first = true;
- for await (const segment of segmentStream(stream, initialEntryState({ region }), { region }) as AsyncIterable<SegmentOut>) {
+ for await (const segment of segmentStream(stream, entry, { byteStart, lineStart, fenceTrust: regionTrust(input.flags, region), end })) {
const seq = rows.length;
if (first) { leads[region] = utf8Prefix(segment.bytes, BODY_LEAD_BYTES); first = false; }
+ if (region === 'truth') truthExit = segment.exitState;
const text = utf8.decode(segment.bytes);
- const key = occurrenceKey(segment.sha256, segment.entryState);
+ const key = occurrenceKey(segment.sha256, segment.entryState, segment.fenceTrust);
const prior = liveRows[seq];
const prefixRow = prefixIntact && prior && prior.region === region && Number(prior.byteStart) === byteStart
- && occurrenceKey(prior.sha256, prior.entryState) === key ? prior : null;
+ && occurrenceKey(prior.sha256, prior.entryState, regionTrust(live!.flags, prior.region)) === key ? prior : null;
let hashState: Uint8Array;
if (prefixRow) hashState = prefixRow.hashState;
else {
@@ -218,7 +233,7 @@ async function stageBody(engine: BrainEngine, input: SegmentedBodyInput, staging
const row: ManifestRowInput = {
pageId, occurrenceId: 0, genFrom: newGeneration, seq, region, sourceId: input.sourceId, sha256: segment.sha256,
byteStart, byteLen: segment.bytes.length, lineStart, lineCount: segment.lineCount, cutKind: segment.cutKind,
- entryState: segment.entryState as JsonObject, protectedRegions: segment.regions, factsSlots: segment.factsSlots,
+ entryState: segment.entryState as unknown as JsonObject, protectedRegions: segment.protectedRegions, factsSlots: segment.factsSlots,
staticProjBytes: segment.staticProjBytes, staticProjLines: segment.staticProjLines, outline: segment.outline,
dateMin: segment.dateMin, dateMax: segment.dateMax, hashState, stagingId,
};
@@ -232,7 +247,7 @@ async function stageBody(engine: BrainEngine, input: SegmentedBodyInput, staging
texts++;
if (pendingBytes >= batchBytes) await flushTexts();
}
- if (segment.regions.length) hasProtected = true;
+ if (segment.protectedRegions.length) hasProtected = true;
rows.push(row);
byteStart += segment.bytes.length;
lineStart += segment.lineCount;
@@ -271,7 +286,7 @@ async function stageBody(engine: BrainEngine, input: SegmentedBodyInput, staging
if (changed.length) await engine.stageManifestRows(changed);
await faultPoint('segmented:manifest_staged', { sourceId: input.sourceId });
const chunkable = await occurrencesWithoutChunks(engine, input.live.id, expectedGeneration, rows);
- const chunks = await stageOccurrenceChunks(engine, { pageId: input.live.id, sourceId: input.sourceId, generation: newGeneration,
+ const chunks = await stageOccurrenceChunks(engine, { pageId: input.live.id, sourceId: input.sourceId, slug: input.slug, generation: newGeneration,
occurrences: chunkable, title: input.title, frontmatter: input.frontmatter, flags: body.body_flags, chunking: input.chunking,
retiredOccurrences: retireChunkOccurrences });
await faultPoint('segmented:chunks_staged', { sourceId: input.sourceId });
@@ -302,13 +317,14 @@ export async function occurrencesWithoutChunks(engine: Pick<BrainEngine, 'execut
* stage the chunk rows under `generation`. Shared by a replace's preparation
* and the post-publication projection.
*/
-export async function stageOccurrenceChunks(engine: BrainEngine, input: { pageId: number; sourceId: string; generation: number;
+export async function stageOccurrenceChunks(engine: BrainEngine, input: { pageId: number; sourceId: string; slug: string; generation: number;
occurrences: readonly ManifestRowInput[]; title: string; frontmatter: JsonObject; flags: JsonObject; chunking: SegmentChunkingContext;
retiredOccurrences: readonly number[];
/** Projection: each batch inserts under the page guard, after re-reading which occurrences still lack rows, so two projections never both chunk one. */
- guard?: { slug: string } }): Promise<{ rows: number; occurrences: number; indexes: number[] }> {
+ guarded?: boolean }): Promise<{ rows: number; occurrences: number; indexes: number[] }> {
if (input.chunking.quarantined || !input.occurrences.length) return { rows: 0, occurrences: 0, indexes: [] };
const batchBytes = STAGE_BATCH_BYTES[engine.kind];
+ const fenceBudget = newFenceChunkBudget();
let rows = 0, done = 0;
const indexes: number[] = [];
for (let start = 0; start < input.occurrences.length;) {
@@ -317,20 +333,29 @@ export async function stageOccurrenceChunks(engine: BrainEngine, input: { pageId
const batch = input.occurrences.slice(start, end);
start = end;
const texts = await engine.readSegmentTexts(input.sourceId, batch.map(row => row.sha256));
+ const segments = batch.map(row => {
+ const bytes = texts.get(hex(row.sha256));
+ if (bytes === undefined) throw new Error(`Segment text ${hex(row.sha256)} of page ${input.pageId} is missing.`);
+ const entryState = readEntryState(row.entryState);
+ if (!entryState) throw new Error(`Manifest row ${row.occurrenceId} of page ${input.pageId} has an entry state of another version; resegment the page.`);
+ const fenceTrust = regionTrust(input.flags, row.region);
+ return { row, fenceTrust, segment: { region: row.region, bytes, byteStart: row.byteStart, entryState, fenceTrust, protectedRegions: row.protectedRegions as StoredRegion[] } };
+ });
+ const factsTexts = segments.flatMap(({ segment }) => segment.protectedRegions.some(region => region.kind === 'facts')
+ ? segmentProjectionParts(utf8.decode(segment.bytes), segment.protectedRegions, segment.byteStart)
+ .filter(part => part.kind === 'facts' && part.region?.open_start === undefined).map(part => part.text) : []);
+ const overlay = factsTexts.length ? await loadFenceChunkOverlay(engine, { sourceId: input.sourceId, slug: input.slug, compiled_truth: factsTexts.join('\n') }) : undefined;
const chunks: SegmentChunkInput[] = [];
- for (const row of batch) {
- const text = texts.get(hex(row.sha256));
- if (text === undefined) throw new Error(`Segment text ${hex(row.sha256)} of page ${input.pageId} is missing.`);
- for (const chunk of prepareSegmentChunks({ ...row, text: utf8.decode(text) }, { flags: input.flags, frontmatter: input.frontmatter })) {
+ for (const { row, fenceTrust, segment } of segments) {
+ for (const chunk of await prepareSegmentChunks(segment, { fenceTrust, frontmatter: input.frontmatter, overlay, fenceBudget })) {
chunks.push({ ...chunk, occurrence_id: row.occurrenceId });
}
}
if (chunks.length && input.retiredOccurrences.length) await reuseSegmentChunkVectors(engine, { pageId: input.pageId,
retiredOccurrences: input.retiredOccurrences, chunks, title: input.title, corpusGeneration: input.chunking.corpusGeneration, tier: input.chunking.tier });
- const guard = input.guard;
- if (chunks.length && !guard) indexes.push(...await engine.stageSegmentChunks(input.pageId, input.generation, chunks));
- if (chunks.length && guard) rows -= chunks.length - await engine.transaction(async tx => {
- await tx.lockPageKeys([{ sourceId: input.sourceId, slug: guard.slug }]);
+ if (chunks.length && !input.guarded) indexes.push(...await engine.stageSegmentChunks(input.pageId, input.generation, chunks));
+ if (chunks.length && input.guarded) rows -= chunks.length - await engine.transaction(async tx => {
+ await tx.lockPageKeys([{ sourceId: input.sourceId, slug: input.slug }]);
const open = new Set((await occurrencesWithoutChunks(tx, input.pageId, input.generation, batch)).map(row => row.occurrenceId));
const still = chunks.filter(chunk => open.has(chunk.occurrence_id));
if (still.length) await tx.stageSegmentChunks(input.pageId, input.generation, still);
diff --git a/src/core/page-body/projection.ts b/src/core/page-body/projection.ts
index 355a6040ee..7b6941f5c5 100644
--- a/src/core/page-body/projection.ts
+++ b/src/core/page-body/projection.ts
@@ -69,8 +69,8 @@ export async function buildSegmentedProjection(engine: BrainEngine, ref: { sourc
const frontmatter = page.frontmatter ?? {};
const quarantined = isQuarantined(frontmatter);
const unchunked = await occurrencesWithoutChunks(engine, pageId, generation, liveRows);
- const staged = await stageOccurrenceChunks(engine, { pageId, sourceId: ref.sourceId, generation, occurrences: unchunked, title: page.title,
- frontmatter, flags: page.body_flags ?? {}, chunking: { quarantined, corpusGeneration: null, tier: 'none' }, retiredOccurrences: [], guard: { slug: ref.slug } });
+ const staged = await stageOccurrenceChunks(engine, { pageId, sourceId: ref.sourceId, slug: ref.slug, generation, occurrences: unchunked, title: page.title,
+ frontmatter, flags: page.body_flags ?? {}, chunking: { quarantined, corpusGeneration: null, tier: 'none' }, retiredOccurrences: [], guarded: true });
await faultPoint('segmented:projection_staged', { sourceId: ref.sourceId });
const sealed = await engine.transaction(async tx => {
await tx.lockPageKeys([{ sourceId: ref.sourceId, slug: ref.slug }]);
diff --git a/src/core/page-body/streamed-import.ts b/src/core/page-body/streamed-import.ts
index 1d273ef3bc..89aa8f0461 100644
--- a/src/core/page-body/streamed-import.ts
+++ b/src/core/page-body/streamed-import.ts
@@ -271,7 +271,7 @@ async function importScanned(engine: BrainEngine, input: { file: FileHandle; bom
const prepared = await prepareSegmentedBody(engine, { sourceId, slug, live, title: parsed.title, type: parsed.type, frontmatter: parsed.frontmatter as JsonObject,
tags: parsed.tags, truth: regionStream(scan.truth, read, inspect),
timeline: (async function* () { codeRefs.end(); carry = ''; yield* regionStream(scan.timeline, read, inspect); })(),
- flags: { fence_trust: scan.bodyFlags.fence_trust, timeline_fence_trust: scan.bodyFlags.timeline_fence_trust, timeline_split: scan.bodyFlags.timeline_split },
+ hasTimeline: scan.timelineBytes > 0, flags: { fence_trust: scan.bodyFlags.fence_trust, timeline_fence_trust: scan.bodyFlags.timeline_fence_trust, timeline_split: scan.bodyFlags.timeline_split },
declaredBytes: scan.truthBytes + scan.timelineBytes,
owner: { kind: 'import', principalKind: principal.kind, principalId: principal.id, baseRevision: existing?.knowledge_revision ?? null },
chunking: { quarantined: disposition.quarantined, corpusGeneration, tier: mode === 'title' ? 'title' : 'none' } });
diff --git a/src/core/persistence/segmented-apply.ts b/src/core/persistence/segmented-apply.ts
index 70da081f0e..6612400bd8 100644
--- a/src/core/persistence/segmented-apply.ts
+++ b/src/core/persistence/segmented-apply.ts
@@ -20,7 +20,7 @@
import type { BrainEngine } from '../engine.ts';
import type { Page } from '../types.ts';
import type { PageSnapshot } from '../page-state/types.ts';
-import type { SegmentedPageMeta } from '../page-body/types.ts';
+import type { JsonObject, SegmentedPageMeta } from '../page-body/types.ts';
import type { PreparedSegmentedBody, SegmentChunkingContext, SegmentedLivePage, SegmentedStagingOwner } from '../page-body/ingest.ts';
import { materializeSegmentedBody, prepareSegmentedBody, stringBodyFlags, stringRegion } from '../page-body/ingest.ts';
import { buildSegmentedProjection } from '../page-body/projection.ts';
@@ -48,10 +48,11 @@ export function bodyStorageOf(page: object | null | undefined): 'inline' | 'segm
/** The live page a segmented write diffs against, read by id (metadata only). */
export async function segmentedLivePage(engine: Pick<BrainEngine, 'executeRaw'>, pageId: number): Promise<SegmentedLivePage> {
- const [row] = await engine.executeRaw<{ id: number; body_generation: number | string; body_storage: string; title: string; type: string }>(
- 'SELECT id, body_generation, body_storage, title, type FROM pages WHERE id=$1', [pageId]);
+ const [row] = await engine.executeRaw<{ id: number; body_generation: number | string; body_storage: string; title: string; type: string; body_flags: JsonObject | null }>(
+ 'SELECT id, body_generation, body_storage, title, type, body_flags FROM pages WHERE id=$1', [pageId]);
if (!row) throw new Error(`Page ${pageId} not found.`);
- return { id: Number(row.id), generation: Number(row.body_generation), storage: row.body_storage === 'segmented' ? 'segmented' : 'inline', title: row.title, type: row.type };
+ return { id: Number(row.id), generation: Number(row.body_generation), storage: row.body_storage === 'segmented' ? 'segmented' : 'inline', title: row.title, type: row.type,
+ flags: row.body_flags };
}
/**
@@ -183,7 +184,7 @@ export async function stageSegmentedImport(engine: BrainEngine, input: { slug: s
}
const prepared = await prepareSegmentedBody(engine, { sourceId: input.sourceId, slug: input.slug, live, title: input.page.title, type: input.page.type,
frontmatter: input.page.frontmatter, tags: input.page.tags, truth: stringRegion(input.page.compiled_truth), timeline: stringRegion(input.page.timeline),
- flags: stringBodyFlags(input.page.compiled_truth, input.page.timeline),
+ hasTimeline: input.page.timeline.length > 0, flags: stringBodyFlags(input.page.compiled_truth, input.page.timeline),
declaredBytes: Buffer.byteLength(input.page.compiled_truth, 'utf-8') + Buffer.byteLength(input.page.timeline, 'utf-8'), owner, chunking: input.chunking });
const staged: SegmentedImport = { prepared, applied: null,
apply: async (tx, meta, contextual) => {