Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
feat(trust-reads): fence eligibility overlay for chunks (#5575 ENG-1)
garrytan74f6326a71c1
diff --git a/src/commands/embed.ts b/src/commands/embed.tsindex b38dcc7f60..98898210fd 100644--- a/src/commands/embed.ts+++ b/src/commands/embed.ts@@ -1,4 +1,5 @@-import { sanitizeRemoteBody } from '../core/remote-body.ts';+import { prepareProseChunks } from '../core/markdown-chunks.ts';+import type { FenceChunkOverlay } from '../core/eligibility/fence-overlay.ts';import { prepareEmbeddingProjections, countArchivedEmbeddingWork, reportBlockedProjections } from '../core/embedding-readiness.ts';import { embedStaleFacts, type EmbedFactsResult } from '../core/embed-facts.ts';import { embedTakesForStaleDrain, type EmbedTakesResult } from '../core/embed-takes.ts';@@ -11,7 +12,6 @@ import { currentEmbeddingSignature } from '../core/embedding.ts';import type { ChunkInput } from '../core/types.ts';import { carryChunkMetadata, probeEmbedder, resolveProvenanceStamp, stampIfPageProvenanceComplete } from '../core/embed-stale.ts';import type { StaleImageSweepResult } from '../core/embed-stale-images.ts';-import { chunkText } from '../core/chunkers/recursive.ts';import { resolveMaxChunkTokens } from '../core/embedding-input-limit.ts';import { healOversizedPageChunks, healedChunksToStaleRows } from '../core/embed-oversize-heal.ts';import {@@ -1042,19 +1042,8 @@ async function embedPage(// embedded — but we never write chunks or call the embedding model.let chunks = page.text_projection_revision === snapshot.revision ? origin.chunks : [];if (chunks.length === 0) {- const inputs: ChunkInput[] = [];- // #4530: respect the active embedding model's per-input token limit.- const chunkOpts = { maxTokens: origin.maxChunkTokens };- if (page.compiled_truth.trim()) {- for (const c of chunkText(sanitizeRemoteBody(page.compiled_truth), chunkOpts)) {- inputs.push({ chunk_index: inputs.length, chunk_text: c.text, chunk_source: 'compiled_truth' });- }- }- if (page.timeline.trim()) {- for (const c of chunkText(sanitizeRemoteBody(page.timeline), chunkOpts)) {- inputs.push({ chunk_index: inputs.length, chunk_text: c.text, chunk_source: 'timeline' });- }- }+ // #4530: the active embedding model's per-input token limit; #5575 ENG-1: the page's fence overlay.+ const inputs = await prepareProseChunks(page, origin.maxChunkTokens, origin.fenceOverlay);if (dryRun) {// Count what chunking WOULD produce, without writing.@@ -1473,22 +1462,9 @@ async function healChunklessPages(let pagesHealed = 0;let budgetExceeded = false;- const buildInputs = (compiledTruth: string, timeline: string, maxTokens = resolveMaxChunkTokens()): ChunkInput[] => {- const inputs: ChunkInput[] = [];- // #4530: respect the active embedding model's per-input token limit.- const chunkOpts = { maxTokens };- if (compiledTruth.trim()) {- for (const c of chunkText(sanitizeRemoteBody(compiledTruth), chunkOpts)) {- inputs.push({ chunk_index: inputs.length, chunk_text: c.text, chunk_source: 'compiled_truth' });- }- }- if (timeline.trim()) {- for (const c of chunkText(sanitizeRemoteBody(timeline), chunkOpts)) {- inputs.push({ chunk_index: inputs.length, chunk_text: c.text, chunk_source: 'timeline' });- }- }- return inputs;- };+ // #4530: the active embedding model's per-input token limit; #5575 ENG-1: the page's fence overlay.+ const buildInputs = (page: { compiled_truth: string; timeline: string }, maxTokens = resolveMaxChunkTokens(), overlay?: FenceChunkOverlay) =>+ prepareProseChunks(page, maxTokens, overlay);// BUDGET_MS === null means catch-up: no wall-clock cap on this sweep,// mirroring the main stale loop's own --catch-up handling below.const overBudget = (): boolean => BUDGET_MS != null && Date.now() - startedAt > BUDGET_MS;@@ -1514,7 +1490,7 @@ async function healChunklessPages(// dryRun never writes, so there's no live-refetch race to close —// chunk the listed snapshot directly (matches embedPage's own// dry-run, which chunks whatever getPage returned at call time).- const inputs = buildInputs(page.compiled_truth, page.timeline);+ const inputs = await buildInputs(page);// Whitespace-only content (SQL prefilter is `<> ''`, not// trim-aware) chunks to nothing — matches embedPage's contract.if (inputs.length === 0) continue;@@ -1527,7 +1503,7 @@ async function healChunklessPages(const prepared = await observed(activePacer, () => readProjectionSnapshot(engine, page.slug, page.source_id, { allowUnsealed: true, requireLiveSource: true }));if (!prepared || prepared.chunks.length > 0) continue;- const inputs = buildInputs(prepared.snapshot.page.compiled_truth, prepared.snapshot.page.timeline, prepared.maxChunkTokens);+ const inputs = await buildInputs(prepared.snapshot.page, prepared.maxChunkTokens, prepared.fenceOverlay);if (inputs.length === 0) continue;await observed(activePacer, () => engine.transaction(async tx => {diff --git a/src/core/eligibility/fence-overlay.ts b/src/core/eligibility/fence-overlay.tsnew file mode 100644index 0000000000..3776a2796b--- /dev/null+++ b/src/core/eligibility/fence-overlay.ts@@ -0,0 +1,204 @@+/**+ * Fence eligibility overlay for chunks (#5575 ENG-1).+ *+ * Chunk text renders the world rows of a page's `## Facts` fence. A fence row+ * never reaches chunks above its own eligibility:+ * - held rows (a write-gate hold for the row's fingerprint on this page) and+ * purged rows (a fact_purges tombstone; L3's import overlay already drops+ * them from canonical markdown, this is the backstop) are omitted;+ * - rows whose stored tier is below the page tier are taken out of the page's+ * chunks and emitted as separate chunks whose first line is a trust marker+ * naming the row tier (`fenceTrustMarker`, read back by `chunkTrustMarker`).+ *+ * Chunks carry no tier column: a chunk's tier is its page's tier at read time+ * (stamp.ts), lowered to the marker tier when its text carries one. A marker+ * can only lower a label, so text that imitates one cannot raise anything.+ *+ * The split is pure (`splitFenceOverlay`); `loadFenceChunkOverlay` reads what+ * it needs for one page in one batched query. Rows the current write appends+ * have no facts row yet when chunks are prepared; the writer names them and+ * their tier with `withPendingFenceRows`.+ */+import { AsyncLocalStorage } from 'node:async_hooks';+import type { BrainEngine } from '../engine.ts';+import { renderFactsTable, type ParsedFact } from '../facts-fence.ts';+import { dropFactFenceRowsByNumber } from '../facts/purge-overlay.ts';+import { withdrawalFenceBlocks } from '../facts/withdrawal-overlay.ts';+import { compareTrust, isTrustTier, minTrust, TRUST_TIERS, type TrustTier } from '../trust/tier.ts';+import { compactTrustLabel } from './labels.ts';++/** The origin slot of a fence trust marker: the chunk holds facts-fence rows, not page prose. */+export const FENCE_TRUST_ORIGIN = 'facts-fence';++export interface FenceChunkOverlay {+ /** Fence row numbers left out of chunk text entirely (held, purged). */+ omit: ReadonlySet<number>;+ /** Fence row numbers whose tier is below the page tier, with that tier. */+ demote: ReadonlyMap<number, TrustTier>;+}++export function fenceOverlayIsEmpty(overlay: FenceChunkOverlay | null | undefined): boolean {+ return !overlay || (overlay.omit.size === 0 && overlay.demote.size === 0);+}++/** The first line of a low-tier fence chunk, e.g. `[written by an agent · facts-fence]`. */+export function fenceTrustMarker(tier: TrustTier): string {+ return compactTrustLabel({ trust_tier: tier, origin: FENCE_TRUST_ORIGIN });+}++const MARKER_TIERS: ReadonlyMap<string, TrustTier> = new Map(TRUST_TIERS.map(tier => [fenceTrustMarker(tier), tier]));++/** The row tier a chunk's leading fence trust marker names, or null when the chunk carries none. */+export function chunkTrustMarker(chunkText: unknown): TrustTier | null {+ if (typeof chunkText !== 'string' || !chunkText.startsWith('[')) return null;+ const end = chunkText.indexOf('\n');+ return MARKER_TIERS.get(end === -1 ? chunkText : chunkText.slice(0, end)) ?? null;+}++/**+ * The least trusted tier any marker line in a text names, or null. Search+ * evidence can join several chunks into one delivered text, so every line is+ * read, not just the first; a marker only ever lowers a label.+ */+export function lowestFenceTrustMarker(text: unknown): TrustTier | null {+ if (typeof text !== 'string' || !text.includes(FENCE_TRUST_ORIGIN)) return null;+ let lowest: TrustTier | null = null;+ for (const line of text.split('\n')) {+ const tier = MARKER_TIERS.get(line);+ if (tier && (!lowest || compareTrust(tier, lowest) < 0)) lowest = tier;+ }+ return lowest;+}++/** Prefix every piece of a low-tier fence text with its marker line. */+export function markFenceChunk(tier: TrustTier, text: string): string {+ return `${fenceTrustMarker(tier)}\n${text}`;+}++/** Text with a leading marker line removed, and the marker's tier (for re-splitting an oversized chunk). */+export function unmarkFenceChunk(text: string): { tier: TrustTier | null; body: string } {+ const tier = chunkTrustMarker(text);+ return tier ? { tier, body: text.slice(text.indexOf('\n') + 1) } : { tier: null, body: text };+}++export interface FenceOverlaySplit {+ /** The text with omitted and demoted rows removed from every facts fence. */+ main: string;+ /** One rendered facts fence per demoted tier (visible world rows only), least trusted last. */+ lowTier: Array<{ tier: TrustTier; body: string }>;+}++/** Pure: apply an overlay to one body. Unchanged text when the overlay is empty or the body has no facts fence. */+export function splitFenceOverlay(text: string, overlay: FenceChunkOverlay | null | undefined): FenceOverlaySplit {+ if (fenceOverlayIsEmpty(overlay) || !text.includes('gbrain:facts:begin')) return { main: text, lowTier: [] };+ const { omit, demote } = overlay!;+ const byTier = new Map<TrustTier, ParsedFact[]>();+ for (const block of withdrawalFenceBlocks(text)) {+ if (block.parsed.warnings.length) continue;+ for (const row of block.parsed.facts) {+ const tier = demote.get(row.rowNum);+ if (!tier || omit.has(row.rowNum) || row.visibility !== 'world' || row.forgotten) continue;+ byTier.set(tier, [...(byTier.get(tier) ?? []), row]);+ }+ }+ const main = dropFactFenceRowsByNumber(text, row => !omit.has(row.rowNum) && !demote.has(row.rowNum));+ return { main, lowTier: TRUST_TIERS.filter(tier => byTier.has(tier)).map(tier => ({ tier, body: renderFactsTable(byTier.get(tier)!) })) };+}++/** World fence rows of a body, every complete block. */+function worldFenceRows(text: string | null | undefined): ParsedFact[] {+ if (!text || !text.includes('gbrain:facts:begin')) return [];+ return withdrawalFenceBlocks(text).flatMap(block => block.parsed.warnings.length ? [] : block.parsed.facts.filter(row => row.visibility === 'world'));+}++interface PendingFenceRows { sourceId: string; slug: string; rowNums: readonly number[]; tier: TrustTier }+const pendingRows = new AsyncLocalStorage<PendingFenceRows>();++/**+ * Inside `fn`, chunk preparation for (sourceId, slug) treats `rowNums` as+ * rows of tier `tier`: a fence writer appends them in the same publication,+ * so their facts rows do not exist yet when the page's chunks are prepared.+ */+export function withPendingFenceRows<T>(rows: PendingFenceRows, fn: () => Promise<T>): Promise<T> {+ return pendingRows.run(rows, fn);+}++/**+ * The tier a fence append's new rows are labeled with while chunks are+ * prepared. Fence appends (remember, extract_facts entity facts) are+ * agent-classified (trust/backfill.ts); a lower declared tier lowers it.+ */+export function fenceAppendPendingTier(declared?: TrustTier | null): TrustTier {+ return declared ? minTrust('agent_written', declared) : 'agent_written';+}++type HoldTexts = ReadonlyArray<string | null | undefined>;++/**+ * Lane L2a seam (write gate): the fingerprint of a held fact,+ * `holdFingerprint('fact', texts)` from write-gate-store.ts. Null until the+ * gate is on this branch: no held lookup runs (write_gate_holds does not+ * exist yet). The L1b integrator sets the default to the gate's function.+ */+let factHoldFingerprint: ((texts: HoldTexts) => string) | null = null;++/** Installs the held-row fingerprint (the write gate's `holdFingerprint('fact', …)`); null turns the held lookup off. */+export function registerFactHoldFingerprint(fingerprint: ((texts: HoldTexts) => string) | null): void {+ factHoldFingerprint = fingerprint;+}++/** The gated text fields of a fence row, in the gate's `decideFactWrite` order (fact, context, value). */+export function fenceRowHoldTexts(row: Pick<ParsedFact, 'claim' | 'context'>): HoldTexts {+ return [row.claim, row.context ?? null, null];+}++const OVERLAY_SQL = (held: boolean) => `WITH incoming AS MATERIALIZED (+ SELECT i.row_num, i.claim, i.visibility, i.fp FROM jsonb_to_recordset($3::text::jsonb) AS i(row_num integer, claim text, visibility text, fp text))+ SELECT incoming.row_num,+ (SELECT p.trust_tier FROM pages p WHERE p.source_id=$1 AND p.slug=$2 AND p.deleted_at IS NULL LIMIT 1) AS page_tier,+ (SELECT f.trust_tier FROM facts f WHERE f.source_id=$1 AND f.source_markdown_slug=$2 AND f.row_num=incoming.row_num+ ORDER BY f.id DESC LIMIT 1) AS row_tier,+ EXISTS (SELECT 1 FROM fact_purges fp WHERE fp.source_id=$1 AND fp.visibility=incoming.visibility+ AND fp.fact_hash=gbrain_fact_fingerprint(incoming.claim) AND (fp.subject='*' OR fp.subject=$2)) AS purged,+ ${held ? `EXISTS (SELECT 1 FROM write_gate_holds h WHERE h.kind='fact' AND h.source_id=$1 AND h.slug=$2+ AND h.status='held' AND h.fingerprint=incoming.fp)` : 'false'} AS held+ FROM incoming`;+const OVERLAY_SQL_WITH_HOLDS = OVERLAY_SQL(true);+const OVERLAY_SQL_WITHOUT_HOLDS = OVERLAY_SQL(false);++export interface LoadFenceOverlayOpts {+ /** Overrides the registered L2a fingerprint for this call. */+ holdFingerprint?: ((texts: HoldTexts) => string) | null;+}++/**+ * The overlay for one page's body, one query. No query runs (and the overlay+ * is empty) when the body has no world fence rows. A row with no facts row+ * and no pending declaration is treated as the page's own tier (the import+ * that publishes it inserts it at the writer's tier, which is the page's).+ */+export async function loadFenceChunkOverlay(+ engine: Pick<BrainEngine, 'executeRaw'>,+ page: { sourceId: string; slug: string; compiled_truth: string; timeline?: string | null },+ opts: LoadFenceOverlayOpts = {},+): Promise<FenceChunkOverlay | undefined> {+ const rows = [...worldFenceRows(page.compiled_truth), ...worldFenceRows(page.timeline)];+ if (!rows.length) return undefined;+ const fingerprint = opts.holdFingerprint === undefined ? factHoldFingerprint : opts.holdFingerprint;+ const incoming = rows.map(row => ({ row_num: row.rowNum, claim: row.claim, visibility: row.visibility,+ fp: fingerprint ? fingerprint(fenceRowHoldTexts(row)) : null }));+ const found = await engine.executeRaw<{ row_num: number; page_tier: string | null; row_tier: string | null; purged: boolean; held: boolean }>(+ fingerprint ? OVERLAY_SQL_WITH_HOLDS : OVERLAY_SQL_WITHOUT_HOLDS, [page.sourceId, page.slug, JSON.stringify(incoming)]);+ const pending = pendingRows.getStore();+ const pendingHere = pending && pending.sourceId === page.sourceId && pending.slug === page.slug ? new Set(pending.rowNums) : null;+ const omit = new Set<number>();+ const demote = new Map<number, TrustTier>();+ for (const row of found) {+ const rowNum = Number(row.row_num);+ if (row.purged === true || row.held === true) { omit.add(rowNum); continue; }+ if (!isTrustTier(row.page_tier)) continue;+ const rowTier = pendingHere?.has(rowNum) ? pending!.tier : isTrustTier(row.row_tier) ? row.row_tier : null;+ if (rowTier && compareTrust(rowTier, row.page_tier) < 0) demote.set(rowNum, rowTier);+ }+ return omit.size || demote.size ? { omit, demote } : undefined;+}diff --git a/src/core/eligibility/stamp.ts b/src/core/eligibility/stamp.tsindex 1ba4102ef7..fe957df766 100644--- a/src/core/eligibility/stamp.ts+++ b/src/core/eligibility/stamp.ts@@ -1,15 +1,18 @@/*** Stamps `trust_tier` + `origin` (eligibility/labels.ts) onto page-derived* read rows (search/query hits, evidence, fetch results) after ranking, so- * label mode never changes ordering (A7). A chunk's tier is its page's tier.+ * label mode never changes ordering (A7). A chunk's tier is its page's tier,+ * lowered to the row tier when its text carries a facts-fence trust marker+ * (fence-overlay.ts, ENG-1); a marker can only lower.* One batched lookup per call; a failed lookup labels the rows `unknown` /* `unrecorded` rather than dropping them or leaving them unlabeled.*/import type { BrainEngine } from '../engine.ts';-import { admitsTrust, type TrustTier } from '../trust/tier.ts';+import { admitsTrust, compareTrust, type TrustTier } from '../trust/tier.ts';+import { FENCE_TRUST_ORIGIN, lowestFenceTrustMarker } from './fence-overlay.ts';import { trustFields, type TrustFields } from './labels.ts';-interface PageRef { page_id?: number | null; source_id?: string | null; slug: string; trust_tier?: string; origin?: string }+interface PageRef { page_id?: number | null; source_id?: string | null; slug: string; chunk_text?: string | null; trust_tier?: string; origin?: string }type Exec = Pick<BrainEngine, 'executeRaw'>;@@ -42,7 +45,9 @@ export async function loadPageTrust(engine: Exec, refs: readonly PageRef[]): Pro/*** Sets `trust_tier` and `origin` on each row in place and returns the rows a- * floor admits. The floor is already applied inside every arm's SQL; this is+ * floor admits. A row whose text carries a fence trust marker below its+ * page's tier is labeled with the marker tier (origin `facts-fence`) and is+ * held to the floor at that tier. The floor is already applied inside every arm's SQL; this is* the backstop for rows a stage adds by slug (exact lookup, alias hop, graph* walk), so no row below the floor leaves the operation.*/@@ -54,8 +59,10 @@ export async function stampPageTrust<T extends PageRef>(engine: Exec, rows: T[],const fields = (typeof row.page_id === 'number' ? found?.byId.get(row.page_id) : undefined)?? found?.byKey.get(key(row.source_id, row.slug))?? { trust_tier: 'unknown' as const, origin: 'unrecorded' };- row.trust_tier = fields.trust_tier;- row.origin = fields.origin;+ const marked = lowestFenceTrustMarker(row.chunk_text);+ const lowered = marked !== null && compareTrust(marked, fields.trust_tier) < 0;+ row.trust_tier = lowered ? marked : fields.trust_tier;+ row.origin = lowered ? FENCE_TRUST_ORIGIN : fields.origin;}return floor ? rows.filter(row => admitsTrust(row.trust_tier as TrustTier, floor)) : rows;}diff --git a/src/core/embed-oversize-heal.ts b/src/core/embed-oversize-heal.tsindex d69bc2e8f3..a1e3c26852 100644--- a/src/core/embed-oversize-heal.ts+++ b/src/core/embed-oversize-heal.ts@@ -19,6 +19,7 @@ import { readProjectionSnapshot, installPageProjection } from './page-state/proj*/import { chunkText } from './chunkers/recursive.ts';+import { fenceTrustMarker, markFenceChunk, unmarkFenceChunk } from './eligibility/fence-overlay.ts';import { estimateEmbedTokens } from './chunkers/token-estimate.ts';import { resolveMaxChunkTokens } from './embedding-input-limit.ts';import type { BrainEngine } from './engine.ts';@@ -96,16 +97,20 @@ export function healOversizedChunks(}splitCount++;- const parts = chunkText(c.chunk_text, { maxTokens });+ // #5575 ENG-1: a low-tier facts-fence chunk keeps its trust marker on every piece.+ const { tier, body } = unmarkFenceChunk(c.chunk_text);+ const room = tier ? Math.max(1, maxTokens - estimateEmbedTokens(fenceTrustMarker(tier)) - 1) : maxTokens;+ const parts = chunkText(body, { maxTokens: room });// Pathological: estimator / splitter disagreement — hard-split by chars// so we never re-emit the original oversized row unchanged.const pieces =- parts.length > 1 || (parts[0] && estimateEmbedTokens(parts[0].text) <= maxTokens)+ parts.length > 1 || (parts[0] && estimateEmbedTokens(parts[0].text) <= room)? parts.map((p) => p.text)- : hardSplitByChars(c.chunk_text, maxTokens);+ : hardSplitByChars(body, room);- for (const text of pieces) {- if (!text) continue;+ for (const piece of pieces) {+ if (!piece) continue;+ const text = tier ? markFenceChunk(tier, piece) : piece;out.push(carryHealedMetadata(c, {chunk_index: out.length,chunk_text: text,diff --git a/src/core/import-file.ts b/src/core/import-file.tsindex 120670006c..27edbea86d 100644--- a/src/core/import-file.ts+++ b/src/core/import-file.ts@@ -16,7 +16,7 @@ import { applyImportFences } from './fence-repair/import-step.ts';import type { FenceIssueWire } from './fence-repair/tier1.ts';import type { FenceFix } from './fence-repair/types.ts';import { classifyStoredType } from './schema-pack/type-usage.ts';-import { prepareMarkdownChunks } from './markdown-chunks.ts';+import { prepareFenceAwareMarkdownChunks } from './markdown-chunks.ts';import { prepareCodeChunks, installCodeChunkEdges } from './code-chunks.ts';import { detectCodeLanguage, CHUNKER_VERSION } from './chunkers/code.ts';import { sanitizeRemoteBody } from './remote-body.ts';@@ -730,7 +730,7 @@ export async function importFromContent(// Preserve the importer projection (including fenced code and zero-chunk// dispositions) in the provider-free path used by background rebuilds too.- const chunks = await prepareMarkdownChunks(parsed);+ const chunks = await prepareFenceAwareMarkdownChunks(engine, sourceId ?? 'default', slug, parsed);// Embedding failures propagate unless onPostCommitEmbedding lets the caller// report enrichment separately from the already-persisted content.diff --git a/src/core/markdown-chunks.ts b/src/core/markdown-chunks.tsindex 4d967c339d..322b6596f9 100644--- a/src/core/markdown-chunks.ts+++ b/src/core/markdown-chunks.ts@@ -1,4 +1,5 @@import type { ChunkInput } from './types.ts';+import type { BrainEngine } from './engine.ts';import { chunkText } from './chunkers/recursive.ts';import { chunkCodeText, detectCodeLanguage } from './chunkers/code.ts';import { sanitizeRemoteBody } from './remote-body.ts';@@ -7,6 +8,8 @@ import { scanFencedBlocks, MAX_FENCES_PER_PAGE } from './fence-scan.ts';import { isEmbedSkipped } from './embed-skip.ts';import { isQuarantined } from './quarantine.ts';import { resolveMaxChunkTokens } from './embedding-input-limit.ts';+import { estimateEmbedTokens } from './chunkers/token-estimate.ts';+import { fenceTrustMarker, loadFenceChunkOverlay, markFenceChunk, splitFenceOverlay, type FenceChunkOverlay } from './eligibility/fence-overlay.ts';/** Recognized fence tags select the existing code grammar; unknown tags stay prose. */const FENCE_TAG_TO_PSEUDO_PATH: Record<string, string> = {@@ -102,33 +105,58 @@ async function extractFencedChunks(}+/**+ * Truth then timeline prose chunks through a fence overlay, plus the+ * overlay's low-tier facts-fence rows as trailing chunks, each piece led by+ * the fence trust marker naming the row tier (#5575 ENG-1). `fenced` slots+ * the recognized code-fence chunks of the overlaid truth before them.+ */+async function overlaidChunks(page: { compiled_truth: string; timeline?: string | null }, maxTokens: number,+ overlay: FenceChunkOverlay | undefined, fenced?: (truth: string, start: number) => Promise<ChunkInput[]>): Promise<ChunkInput[]> {+ const chunks: ChunkInput[] = [];+ const truth = splitFenceOverlay(page.compiled_truth, overlay);+ const timeline = splitFenceOverlay(page.timeline ?? '', overlay);+ for (const [text, source] of [[truth.main, 'compiled_truth'], [timeline.main, 'timeline']] as const) {+ if (!text.trim()) continue;+ for (const c of chunkText(text, { maxTokens })) chunks.push({ chunk_index: chunks.length, chunk_text: c.text, chunk_source: source });+ }+ if (fenced && truth.main.trim()) chunks.push(...await fenced(truth.main, chunks.length));+ for (const { tier, body } of [...truth.lowTier, ...timeline.lowTier]) {+ const room = Math.max(1, maxTokens - estimateEmbedTokens(fenceTrustMarker(tier)) - 1);+ for (const c of chunkText(body, { maxTokens: room })) {+ chunks.push({ chunk_index: chunks.length, chunk_text: markFenceChunk(tier, c.text), chunk_source: 'compiled_truth' });+ }+ }+ return chunks;+}+/*** Provider-free Markdown projection shared by canonical imports and DB-only* rebuilds. The caller owns content/disposition policy and the token limit;* chunkers enforce the full-body privacy boundary before splitting. Order and* metadata match the importer: truth, timeline, then recognized truth fences.+ * A fence overlay (loadFenceChunkOverlay) leaves held and purged fence rows+ * out and moves rows below the page tier into trailing marked chunks; without+ * one the output is unchanged.*/export async function prepareMarkdownChunks(page: {compiled_truth: string;timeline?: string;frontmatter?: Record<string, unknown> | null;-}, maxChunkTokens?: number): Promise<ChunkInput[]> {+}, maxChunkTokens?: number, overlay?: FenceChunkOverlay): Promise<ChunkInput[]> {// Both dispositions intentionally have no live chunks, including code.if (isEmbedSkipped(page.frontmatter) || isQuarantined(page.frontmatter)) return [];- const chunks: ChunkInput[] = [];- const chunkOpts = { maxTokens: maxChunkTokens ?? resolveMaxChunkTokens() };- if (page.compiled_truth.trim()) {- for (const c of chunkText(page.compiled_truth, chunkOpts)) {- chunks.push({ chunk_index: chunks.length, chunk_text: c.text, chunk_source: 'compiled_truth' });- }- }- if (page.timeline?.trim()) {- for (const c of chunkText(page.timeline, chunkOpts)) {- chunks.push({ chunk_index: chunks.length, chunk_text: c.text, chunk_source: 'timeline' });- }- }- if (page.compiled_truth.trim()) {- chunks.push(...await extractFencedChunks(page.compiled_truth, chunks.length));- }- return chunks;+ return overlaidChunks(page, maxChunkTokens ?? resolveMaxChunkTokens(), overlay, extractFencedChunks);+}++/** Truth and timeline prose only (no code-fence chunks), through the overlay: embed's chunkless-page rebuilds. */+export function prepareProseChunks(page: { compiled_truth: string; timeline?: string | null }, maxChunkTokens: number,+ overlay?: FenceChunkOverlay): Promise<ChunkInput[]> {+ return overlaidChunks(page, maxChunkTokens, overlay);+}++/** The importer's projection of one page: its fence overlay read in one query, then prepareMarkdownChunks. */+export async function prepareFenceAwareMarkdownChunks(engine: Pick<BrainEngine, 'executeRaw'>, sourceId: string, slug: string,+ page: Parameters<typeof prepareMarkdownChunks>[0]): Promise<ChunkInput[]> {+ return prepareMarkdownChunks(page, undefined, await loadFenceChunkOverlay(engine, { sourceId, slug, compiled_truth: page.compiled_truth, timeline: page.timeline }));}diff --git a/src/core/page-state/projections.ts b/src/core/page-state/projections.tsindex 7ef326d520..ed6aa9ce7c 100644--- a/src/core/page-state/projections.ts+++ b/src/core/page-state/projections.ts@@ -3,6 +3,7 @@ import type { Chunk, ChunkInput, ResolvedColumn, PageKind } from '../types.ts';import { MARKDOWN_CHUNKER_VERSION } from '../chunkers/recursive.ts';import { CHUNKER_VERSION } from '../chunkers/code.ts';import { prepareMarkdownChunks } from '../markdown-chunks.ts';+import { loadFenceChunkOverlay, type FenceChunkOverlay } from '../eligibility/fence-overlay.ts';import { prepareCodeChunks, installCodeChunkEdges } from '../code-chunks.ts';import { resolveMaxChunkTokens } from '../embedding-input-limit.ts';import { assertPageRevision, PageRevisionConflictError, type PageSnapshot } from './types.ts';@@ -40,6 +41,8 @@ export interface ProjectionSnapshot {maxChunkTokens: number;maxChunkTokensOverride?: number;pageKind: PageKind;+ /** #5575 ENG-1: held, purged and below-page-tier fence rows, read with the snapshot. */+ fenceOverlay?: FenceChunkOverlay;}export type ProjectionConflictField = 'text_projection_revision' | 'chunk_digest' | 'indexing_context';@@ -134,8 +137,10 @@ async function readGuardedProjectionSnapshot(tx: BrainEngine, slug: string, sourconst snapshot = await tx.readPageSnapshot(slug, { sourceId, ...(opts.requireLiveSource && { requireLiveSource: true }) });if (!snapshot || (!opts.allowUnsealed && snapshot.page.text_projection_revision !== snapshot.revision)) return null;const context = await indexingContext(tx, snapshot, opts.maxChunkTokens);+ const fenceOverlay = context.pageKind === 'markdown' ? await loadFenceChunkOverlay(tx, { sourceId, slug, compiled_truth: snapshot.page.compiled_truth, timeline: snapshot.page.timeline }) : undefined;return { snapshot, chunks: await tx.getChunks(slug, { sourceId, includeUnsealed: true }), indexingContext: context.key,- embeddingModel: context.model, embeddingColumn: context.column, maxChunkTokens: context.maxChunkTokens, maxChunkTokensOverride: opts.maxChunkTokens, pageKind: context.pageKind };+ embeddingModel: context.model, embeddingColumn: context.column, maxChunkTokens: context.maxChunkTokens, maxChunkTokensOverride: opts.maxChunkTokens, pageKind: context.pageKind,+ ...(fenceOverlay ? { fenceOverlay } : {}) };}/** No provider work under the guard. Delayed derived results lose to newer content. */@@ -303,7 +308,7 @@ export async function preparePageProjection(prepared: ProjectionSnapshot) {return { chunks: code.chunks, code };}if (prepared.pageKind !== 'markdown') throw new Error('This page kind requires its source importer.');- return { chunks: await prepareMarkdownChunks(page, prepared.maxChunkTokens), code: undefined };+ return { chunks: await prepareMarkdownChunks(page, prepared.maxChunkTokens, prepared.fenceOverlay), code: undefined };}// The job queue is usually empty or small while pages grows without bound, sodiff --git a/src/core/search/chunk-windows.ts b/src/core/search/chunk-windows.tsindex 3f21302d9f..a582543aee 100644--- a/src/core/search/chunk-windows.ts+++ b/src/core/search/chunk-windows.ts@@ -12,6 +12,7 @@* sealed pages and anchor the hits in that text.*/import type { PageReadScope } from '../types.ts';+import type { FenceChunkOverlay } from '../eligibility/fence-overlay.ts';export interface ChunkWindowRequest {page_id: number;@@ -47,6 +48,8 @@ export interface ChunkWindowPage {chunks: ChunkWindowChunk[];/** True when the row cap stopped before every requested row was read. */row_limited: boolean;+ /** #5575 ENG-1: the page's fence overlay, attached by evidence delivery before it builds the page document. */+ fenceOverlay?: FenceChunkOverlay;}export interface ChunkWindowOpts extends PageReadScope {diff --git a/src/core/search/evidence-delivery.ts b/src/core/search/evidence-delivery.tsindex 7b78edffeb..95df01aa84 100644--- a/src/core/search/evidence-delivery.ts+++ b/src/core/search/evidence-delivery.ts@@ -32,6 +32,7 @@ import { resolveExcludePrivatePages } from './private-visibility.ts';import { safeSplitIndex } from '../text-safe.ts';import { sanitizeRemoteBody } from '../remote-body.ts';import { credentialSafeProjection } from '../credential-projection.ts';+import { loadFenceChunkOverlay, markFenceChunk, splitFenceOverlay, type FenceChunkOverlay } from '../eligibility/fence-overlay.ts';import { stripChunkHeader } from '../chunkers/code.ts';import { OperationError } from '../ops/contract.ts';@@ -522,9 +523,14 @@ function fallbackBlock(hit: SearchResult, hits: SearchResult[], reason: string):* newline-padded tokens), and joined the way serializeMarkdown joins them.* Frontmatter is not part of it.*/-export function pageEvidenceText(page: { compiled_truth: string; timeline: string }, includeTimeline: boolean): { text: string; timelineAt: number } {- const truth = credentialSafeProjection(sanitizeRemoteBody(page.compiled_truth ?? ''));- const timeline = includeTimeline ? credentialSafeProjection(sanitizeRemoteBody(page.timeline ?? '')) : '';+export function pageEvidenceText(page: { compiled_truth: string; timeline: string; fenceOverlay?: FenceChunkOverlay }, includeTimeline: boolean): { text: string; timelineAt: number } {+ // #5575 ENG-1: the page's chunks were cut through its fence overlay; the document is too (held and purged rows+ // out, rows below the page tier after the truth under their trust marker, the way the marked chunks hold them).+ const ownTruth = splitFenceOverlay(page.compiled_truth ?? '', page.fenceOverlay);+ const ownTimeline = splitFenceOverlay(page.timeline ?? '', page.fenceOverlay);+ const truth = [credentialSafeProjection(sanitizeRemoteBody(ownTruth.main)), ...[...ownTruth.lowTier, ...(includeTimeline ? ownTimeline.lowTier : [])]+ .map(({ tier, body }) => markFenceChunk(tier, credentialSafeProjection(sanitizeRemoteBody(body))))].join('\n\n');+ const timeline = includeTimeline ? credentialSafeProjection(sanitizeRemoteBody(ownTimeline.main)) : '';if (!timeline.trim()) return { text: truth, timelineAt: -1 };return { text: truth + TIMELINE_SEPARATOR + timeline, timelineAt: truth.length + TIMELINE_SEPARATOR.length };}@@ -866,6 +872,7 @@ export async function deliverEvidence(chunkSources: scope.detail === 'low' ? ['compiled_truth'] : ['compiled_truth', 'timeline'],maxRows,}), opts.timeoutMs ?? EVIDENCE_FETCH_TIMEOUT_MS);+ for (const p of rows) p.fenceOverlay = await loadFenceChunkOverlay(engine, { sourceId: p.source_id, slug: p.slug, compiled_truth: p.compiled_truth, timeline: p.timeline });pages = new Map(rows.map(p => [p.page_id, p]));} catch (e) {fetchFailure = e instanceof EvidenceTimeout ? 'fetch_timeout' : 'fetch_failed';