Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

Wave B PR 1: classify the new schema and writers for the repo-wide guards

garrytancc055f03cbf2
diff --git a/docs/architecture/canonical-writers.tsv b/docs/architecture/canonical-writers.tsv
index 837ab950b4..fa4acd2d8c 100644
--- a/docs/architecture/canonical-writers.tsv
+++ b/docs/architecture/canonical-writers.tsv
@@ -61,6 +61,7 @@ src/core/engine-constants.ts 1 contract Engine contract or explanatory SQL refer
src/core/engine-sql/bootstrap.ts 1 schema Schema installation and forward-reference DDL; coordinated activation quiesces canonical writers.
src/core/engine-sql/chunks.ts 2 projection Derived indexing: setPageEmbeddingSignature stamps pages.embedding_signature, and a complete chunk replacement (upsertChunks sealChunkerVersion, #5984) stamps pages.chunker_version in the caller's transaction; chunk rows are derived index state and canonical fields remain guarded by SQL triggers.
src/core/engine-sql/facts.ts 11 engine_guard Canonical table SQL trigger requires coordinator capability; legacy calls fail before canonical DB publication.
+src/core/engine-sql/page-body.ts 2 engine_guard Wave B segmented storage: createSegmentedPageShell inserts the page row and flipBodyGeneration moves its body identity (body_generation, size and lead columns); both run in the caller's publication transaction, and the pages SQL trigger requires coordinator capability on managed brains (body_generation is guarded content).
src/core/engine-sql/pages.ts 18 engine_guard Canonical table SQL trigger requires coordinator capability; legacy calls fail before canonical DB publication. #5761: markPagesAttendanceBlocked writes only derived attendance-marker columns. The additional UPDATE pages in updatePageContextualRetrievalState changes only contextual projection state and clears active vectors in the same statement, under the caller's page lock; canonical body fields remain guarded. #6454: stripStaleFrontmatterKeys removes only the four parser-reserved keys from pages.frontmatter (keys no canonical file can carry, so the file is unchanged) inside the repair sweep's coordinated write; it touches no body, title, type or tag column.
src/core/engine-sql/salience.ts 1 projection Derived indexing, retrieval telemetry, or source settings; canonical fields remain guarded by SQL triggers.
src/core/engine-sql/sources.ts 1 projection Source settings (the sources.config merge in updateSourceConfig); canonical fields remain guarded by SQL triggers.
@@ -85,6 +86,7 @@ src/core/google/google-source.ts 3 coordinator Managed connector imports, deleti
src/core/google/sweep-shared.ts 1 coordinator Peeled from google-source.ts (wave 14 PR4, P4.3): the per-path delete used by the contact and calendar sweeps routes a managed source through the managed journal's delete and confines the legacy deletePages call to unmanaged sources.
src/core/google/loops-extract.ts 1 coordinator Managed loop extraction checks the managed fact authority and owner before model calls and publishes its commitment fact through writeSingleFact's coordinator path; the provenance-tagged loop edge is not a guarded canonical table.
src/core/import-file.ts 19 coordinator Prepared import applies under journal publication and revision CAS; direct managed imports refuse early, legacy source-path repair follows revision validation inside a savepoint, and a moved file's page is renamed only on the direct (unmanaged) path. Frontmatter tag reconciliation deletes only import-owned tag rows inside the same guarded import transaction. Direct importFromContent calls without prepare refuse on managed brains before any write (assertUnmanagedCanonicalWriter).
+src/core/page-body/streamed-import.ts 3 coordinator Wave B streamed import of a file over the single-string ceiling: refuses on managed brains before any write (assertUnmanagedCanonicalWriter), then versions, reconciles import-owned tags and adds code-reference links inside one maintenanceTransaction under the import base check, as importFromContent does on an unmanaged brain.
src/core/last-retrieved.ts 1 projection Derived indexing, retrieval telemetry, or source settings; canonical fields remain guarded by SQL triggers.
src/core/minions/handlers/ingest-capture.ts 3 engine_guard Canonical table SQL trigger requires coordinator capability; legacy calls fail before canonical DB publication. Direct importFromContent calls without prepare refuse on managed brains before any write (assertUnmanagedCanonicalWriter).
src/core/onboard/checks.ts 2 projection Derived indexing, retrieval telemetry, or source settings; canonical fields remain guarded by SQL triggers.
@@ -101,6 +103,7 @@ src/core/page-state/tags.ts 5 engine_guard Canonical table SQL trigger requires
src/core/persistence/memory-mutations.ts 1 coordinator Publication is transaction-scoped under admitted authority, source/page guards and revision checks.
src/core/persistence/memory-prepare.ts 3 coordinator Publication is transaction-scoped under admitted authority, source/page guards and revision checks.
src/core/persistence/page-prepare.ts 10 coordinator Publication, including versioned tombstone restoration, is transaction-scoped under admitted authority, source/page guards and revision checks; the sixth SQL site reconciles trusted first-write provenance with prepared canonical frontmatter and the seventh records canonical source_path in that same guarded transaction. Identical canonical no-ops do not heal physical metadata. The added local-CLI purge deletePage call runs in the prepared publication callback after recorded-artifact removal, under the same source/page identity, revision and durable authority guards as receipt completion; permanent journal IDs and outcomes survive the hard delete. The ninth site pins an inferred slug_root_mode on sources in the same publication transaction as the first bound origin. Its importFromContent calls carry prepare and run inside the coordinator publication.
+src/core/persistence/segmented-apply.ts 2 coordinator Wave B segmented apply inside the page write's publication transaction: sealSegmentedPage stamps only projection state (text_projection_revision, chunker_version, search_vector); demoteSegmentedPage turns a segmented row inline with an empty body that the same transaction's inline write fills, under the request's revision and page guards.
src/core/persistence/semantic-pages.ts 1 coordinator Publication is transaction-scoped under admitted authority, source/page guards and revision checks.
src/core/pglite-engine.ts 31 engine_guard Canonical table SQL trigger requires coordinator capability; legacy calls fail before canonical DB publication.
src/core/pglite-schema.ts 1 schema Schema installation and forward-reference DDL; coordinated activation quiesces canonical writers.
diff --git a/scripts/check-chunk-visibility.ts b/scripts/check-chunk-visibility.ts
index 748becfbe0..9eed356c88 100644
--- a/scripts/check-chunk-visibility.ts
+++ b/scripts/check-chunk-visibility.ts
@@ -44,7 +44,7 @@ const BASELINE_REL = 'scripts/chunk-visibility-baseline.tsv';
const ANCHOR = 'scripts/check-chunk-visibility.ts (header)';
const MARKER = 'chunk-visibility-ok';
const READ = /(?<!\bdelete\s{1,40})\b(?:from|join)\s+content_chunks\b/i;
-const COVERED = /\bchunk(?:VisibleFilter|GenerationFilter|GenerationProbe)\(|\bbuildVisibilityClause\(\s*'\w+'\s*,\s*'\w+'\s*,(?:[^()]|\([^()]*\))*?,\s*'\w+'\s*\)/;
+const COVERED = /\bchunk(?:VisibleFilter|GenerationFilter|GenerationProbe)\(|\bbuildVisibilityClause\(\s*'\w+'\s*,\s*'\w+'\s*,(?:[^()]|\([^()]*\))*?\bchunkAlias:\s*'\w+'/;
const SQL_MARKER = new RegExp(String.raw`--\s*${MARKER}:([^\n]*)`);
export interface Statement {
diff --git a/scripts/e2e-backend-matrix.txt b/scripts/e2e-backend-matrix.txt
index e408a69ea0..e3c0797811 100644
--- a/scripts/e2e-backend-matrix.txt
+++ b/scripts/e2e-backend-matrix.txt
@@ -67,3 +67,4 @@ test/e2e/fts-cjk-boundary-postgres.test.ts
test/e2e/oauth-client-registered-via-postgres.test.ts
test/e2e/oauth-owner-consent-source-postgres.test.ts
test/e2e/entity-names-parity-postgres.test.ts
+test/e2e/segment-gc-parity.test.ts
diff --git a/src/commands/doctor/checks/managed-guard.ts b/src/commands/doctor/checks/managed-guard.ts
index 816213cffc..a5c50656d3 100644
--- a/src/commands/doctor/checks/managed-guard.ts
+++ b/src/commands/doctor/checks/managed-guard.ts
@@ -11,12 +11,12 @@ const RUNBOOK = 'docs/guides/write-refusals.md#managed-guard-page-children';
* tables regenerates the goldens and then updates this list.
*/
export const GUARDED_TABLE_COLUMNS: Readonly<Record<string, readonly string[]>> = {
- pages: ['chunker_version', 'compiled_truth', 'content_hash', 'contextual_retrieval_mode', 'corpus_generation', 'created_at', 'database_only_reason',
+ pages: ['body_bytes', 'body_flags', 'body_generation', 'body_lines', 'body_storage', 'chunker_version', 'compiled_truth', 'content_hash', 'contextual_retrieval_mode', 'corpus_generation', 'created_at', 'database_only_reason',
'deleted_at', 'effective_date', 'effective_date_source', 'embedding_signature', 'emotional_weight', 'emotional_weight_recomputed_at', 'frontmatter',
'generation', 'id', 'import_filename', 'ingested_at', 'ingested_via', 'knowledge_revision', 'last_retrieved_at', 'links_attendance_blocked_at',
'links_attendance_blocked_revision', 'links_extracted_at', 'page_kind', 'revision_principal_id', 'revision_principal_kind', 'revision_write_request_id',
- 'salience_touched_at', 'search_vector', 'slug', 'source_id', 'source_kind', 'source_path', 'source_uri', 'text_projection_revision', 'timeline',
- 'title', 'trust_tier', 'type', 'updated_at', 'write_origin'],
+ 'salience_touched_at', 'search_vector', 'segment_count', 'segmenter_version', 'slug', 'source_id', 'source_kind', 'source_path', 'source_uri',
+ 'text_projection_revision', 'timeline', 'timeline_lead', 'title', 'trust_tier', 'truth_bytes', 'truth_lead', 'type', 'updated_at', 'write_origin'],
tags: ['id', 'page_id', 'tag', 'tag_source'],
slug_aliases: ['alias_slug', 'canonical_slug', 'created_at', 'id', 'notes', 'source_id'],
page_aliases: ['alias_norm', 'alias_text', 'case_sensitive', 'created_at', 'id', 'origin', 'slug', 'source_id'],
@@ -34,6 +34,10 @@ export const GUARDED_TABLE_COLUMNS: Readonly<Record<string, readonly string[]>>
sources: ['archive_expires_at', 'archived', 'archived_at', 'chunker_version', 'config', 'contextual_retrieval_mode', 'created_at', 'id', 'incarnation',
'last_commit', 'last_sync_at', 'local_path', 'name', 'newest_content_at', 'trust_frontmatter_overrides', 'upstream_behind', 'upstream_checked_at',
'upstream_commit'],
+ page_segment_texts: ['body', 'byte_len', 'created_at', 'line_count', 'sha256', 'source_id'],
+ page_body_manifest: ['byte_len', 'byte_start', 'cut_kind', 'date_max', 'date_min', 'entry_state', 'facts_slots', 'gen_from', 'gen_to', 'hash_state',
+ 'line_count', 'line_start', 'occurrence_id', 'outline', 'page_id', 'protected_regions', 'region', 'seq', 'sha256', 'source_id', 'staging_id',
+ 'static_proj_bytes', 'static_proj_lines'],
};
/**
diff --git a/src/core/page-body/schema.ts b/src/core/page-body/schema.ts
index c47a662eda..a0c5816f4a 100644
--- a/src/core/page-body/schema.ts
+++ b/src/core/page-body/schema.ts
@@ -11,9 +11,15 @@
*/
/**
- * Query-cache generation bump (migration v91's trigger function). A segmented
- * page's body identity is `body_generation`: its body columns are NULL on both
- * sides of a flip, so the generation moves when body_generation does.
+ * Query-cache generation bump (v0.40.3.0, migration v91's trigger function).
+ * BEFORE INSERT OR UPDATE so every write path bumps generation (D6 / codex #4).
+ * INSERT: pages get COALESCE(MAX(generation), 0) + 1 so the bookmark gate
+ * fires for any cache row stored before the new page existed. UPDATE: bumps
+ * only when a content column IS DISTINCT FROM (allow-list widened per D6 +
+ * codex #3 to include title/type/page_kind/corpus_generation/content_hash) so
+ * read-time mutations don't invalidate every cache row. A segmented page's
+ * body identity is `body_generation`: its body columns are NULL on both sides
+ * of a flip, so the generation moves when body_generation does.
*/
export const PAGE_GENERATION_BUMP_FN_SQL = `CREATE OR REPLACE FUNCTION bump_page_generation_fn() RETURNS trigger SET search_path = pg_catalog, public AS $func$
BEGIN
diff --git a/src/core/page-state/schema.ts b/src/core/page-state/schema.ts
index 11e9302073..9860070f5b 100644
--- a/src/core/page-state/schema.ts
+++ b/src/core/page-state/schema.ts
@@ -63,11 +63,11 @@ export const PAGE_STATE_SCHEMA_STATEMENTS = [
IF NEW.compiled_truth IS NULL AND OLD.compiled_truth IS NULL THEN
body_moved := NEW.body_generation IS DISTINCT FROM OLD.body_generation;
END IF;
- IF body_moved OR (NEW.source_id, NEW.slug, NEW.type, NEW.page_kind, NEW.title, NEW.compiled_truth,
+ IF (NEW.source_id, NEW.slug, NEW.type, NEW.page_kind, NEW.title, NEW.compiled_truth,
NEW.timeline, NEW.frontmatter, NEW.deleted_at)
IS DISTINCT FROM
(OLD.source_id, OLD.slug, OLD.type, OLD.page_kind, OLD.title, OLD.compiled_truth,
- OLD.timeline, OLD.frontmatter, OLD.deleted_at) THEN
+ OLD.timeline, OLD.frontmatter, OLD.deleted_at) OR body_moved THEN
IF NEW.knowledge_revision = OLD.knowledge_revision AND NOT (
COALESCE(current_setting('gbrain.materializing_revision', true), '') = OLD.knowledge_revision::text
AND (NEW.source_id, NEW.slug, NEW.type, NEW.page_kind, NEW.title, NEW.frontmatter, NEW.deleted_at)
diff --git a/src/core/pglite-engine.ts b/src/core/pglite-engine.ts
index 2e9f96ce92..fad4f16a53 100644
--- a/src/core/pglite-engine.ts
+++ b/src/core/pglite-engine.ts
@@ -1414,7 +1414,7 @@ export class PGLiteEngine implements BrainEngine {
const hardExcludeClause = buildHardExcludeClause('p.slug', hardExcludePrefixes);
// v0.26.5: visibility filter (soft-deleted + archived-source).
- const visibilityClause = buildVisibilityClause('p', 's', opts, 'cc');
+ const visibilityClause = buildVisibilityClause('p', 's', { ...opts, chunkAlias: 'cc' });
// v0.32.7: CJK query branch. PGLite uses websearch_to_tsquery('english')
// which can't tokenize CJK; queries return empty. Switch to ILIKE on
@@ -1625,7 +1625,7 @@ export class PGLiteEngine implements BrainEngine {
const sourceFactorCase = buildSourceFactorCase('p.slug', boostMap, opts?.detail);
const hardExcludePrefixes = resolveHardExcludes(opts?.exclude_slug_prefixes, opts?.include_slug_prefixes);
const hardExcludeClause = buildHardExcludeClause('p.slug', hardExcludePrefixes);
- const visibilityClause = buildVisibilityClause('p', 's', opts, 'cc');
+ const visibilityClause = buildVisibilityClause('p', 's', { ...opts, chunkAlias: 'cc' });
// v0.32.7: CJK branch (same as searchKeyword but without page-dedup).
if (hasCJK(query)) {
diff --git a/src/core/pglite-schema.generated.ts b/src/core/pglite-schema.generated.ts
index 2c1f4aa15c..1386e33668 100644
--- a/src/core/pglite-schema.generated.ts
+++ b/src/core/pglite-schema.generated.ts
@@ -70,14 +70,6 @@ CREATE TABLE IF NOT EXISTS pages (
CONSTRAINT pages_source_slug_key UNIQUE (source_id, slug)
);
--- v0.40.3.0 cache invalidation trigger (migration v91; mirrored in
--- src/core/pglite-schema.ts). BEFORE INSERT OR UPDATE so every write path
--- bumps generation per D6 / codex #4. INSERT: pages get
--- COALESCE(MAX(generation), 0) + 1 so the bookmark gate fires for any
--- cache row stored before the new page existed. UPDATE: bumps only when
--- content columns IS DISTINCT FROM (allow-list widened per D6 + codex #3
--- to include title/type/page_kind/corpus_generation/content_hash) so
--- read-time mutations don't invalidate every cache row.
CREATE OR REPLACE FUNCTION bump_page_generation_fn() RETURNS trigger SET search_path = pg_catalog, public AS \$func\$
BEGIN
IF (TG_OP = 'INSERT') THEN
@@ -1162,11 +1154,11 @@ CREATE OR REPLACE FUNCTION gbrain_advance_page_revision() RETURNS trigger LANGUA
IF NEW.compiled_truth IS NULL AND OLD.compiled_truth IS NULL THEN
body_moved := NEW.body_generation IS DISTINCT FROM OLD.body_generation;
END IF;
- IF body_moved OR (NEW.source_id, NEW.slug, NEW.type, NEW.page_kind, NEW.title, NEW.compiled_truth,
+ IF (NEW.source_id, NEW.slug, NEW.type, NEW.page_kind, NEW.title, NEW.compiled_truth,
NEW.timeline, NEW.frontmatter, NEW.deleted_at)
IS DISTINCT FROM
(OLD.source_id, OLD.slug, OLD.type, OLD.page_kind, OLD.title, OLD.compiled_truth,
- OLD.timeline, OLD.frontmatter, OLD.deleted_at) THEN
+ OLD.timeline, OLD.frontmatter, OLD.deleted_at) OR body_moved THEN
IF NEW.knowledge_revision = OLD.knowledge_revision AND NOT (
COALESCE(current_setting('gbrain.materializing_revision', true), '') = OLD.knowledge_revision::text
AND (NEW.source_id, NEW.slug, NEW.type, NEW.page_kind, NEW.title, NEW.frontmatter, NEW.deleted_at)
diff --git a/src/core/postgres-engine.ts b/src/core/postgres-engine.ts
index a1ea9b39ce..26366f8fe6 100644
--- a/src/core/postgres-engine.ts
+++ b/src/core/postgres-engine.ts
@@ -1008,7 +1008,7 @@ export class PostgresEngine implements BrainEngine {
if (hasCJK(query)) {
return this._searchKeywordCJK(query, {
limit, offset, innerLimit, sourceFactorCase, hardExcludeClause,
- visibilityClause: buildVisibilityClause('p', 's', opts, 'cc'),
+ visibilityClause: buildVisibilityClause('p', 's', { ...opts, chunkAlias: 'cc' }),
detailFilter: detailLow ? `AND cc.chunk_source = 'compiled_truth'` : '',
opts, dedup: true,
});
@@ -1080,7 +1080,7 @@ export class PostgresEngine implements BrainEngine {
// archived sources. Joined `sources s` lets the predicate compile to a
// column lookup. NOT bypassed by detail=high — soft-delete is a contract,
// not a temporal preference.
- const visibilityClause = buildVisibilityClause('p', 's', opts, 'cc');
+ const visibilityClause = buildVisibilityClause('p', 's', { ...opts, chunkAlias: 'cc' });
// FTS config name (e.g. 'english', 'pt_br'). Validated by getFtsLanguage()
// — safe to interpolate into raw SQL.
const ftsLang = getFtsLanguage();
@@ -1231,7 +1231,7 @@ export class PostgresEngine implements BrainEngine {
limit, offset,
innerLimit: 0, // unused on chunk-grain (no inner CTE)
sourceFactorCase, hardExcludeClause,
- visibilityClause: buildVisibilityClause('p', 's', opts, 'cc'),
+ visibilityClause: buildVisibilityClause('p', 's', { ...opts, chunkAlias: 'cc' }),
detailFilter: detailLow ? `AND cc.chunk_source = 'compiled_truth'` : '',
opts, dedup: false,
});
@@ -1293,7 +1293,7 @@ export class PostgresEngine implements BrainEngine {
const offsetParam = `$${params.length}`;
// v0.26.5: visibility filter for searchKeywordChunks (anchor primitive).
- const visibilityClause = buildVisibilityClause('p', 's', opts, 'cc');
+ const visibilityClause = buildVisibilityClause('p', 's', { ...opts, chunkAlias: 'cc' });
// FTS config name (e.g. 'english', 'pt_br'). Validated by getFtsLanguage()
// — safe to interpolate into raw SQL.
const ftsLang = getFtsLanguage();
diff --git a/src/core/schema-embedded.generated.ts b/src/core/schema-embedded.generated.ts
index 57fc23cc73..91789eb23e 100644
--- a/src/core/schema-embedded.generated.ts
+++ b/src/core/schema-embedded.generated.ts
@@ -170,14 +170,6 @@ CREATE TABLE IF NOT EXISTS pages (
CONSTRAINT pages_source_slug_key UNIQUE (source_id, slug)
);
--- v0.40.3.0 cache invalidation trigger (migration v91; mirrored in
--- src/core/pglite-schema.ts). BEFORE INSERT OR UPDATE so every write path
--- bumps generation per D6 / codex #4. INSERT: pages get
--- COALESCE(MAX(generation), 0) + 1 so the bookmark gate fires for any
--- cache row stored before the new page existed. UPDATE: bumps only when
--- content columns IS DISTINCT FROM (allow-list widened per D6 + codex #3
--- to include title/type/page_kind/corpus_generation/content_hash) so
--- read-time mutations don't invalidate every cache row.
-- BEGIN GENERATED from src/core/page-body/schema.ts (PAGE_GENERATION_BUMP_FN_SQL). Edit that file, then run: bun run build:schema
CREATE OR REPLACE FUNCTION bump_page_generation_fn() RETURNS trigger SET search_path = pg_catalog, public AS \$func\$
BEGIN
@@ -1878,11 +1870,11 @@ CREATE OR REPLACE FUNCTION gbrain_advance_page_revision() RETURNS trigger LANGUA
IF NEW.compiled_truth IS NULL AND OLD.compiled_truth IS NULL THEN
body_moved := NEW.body_generation IS DISTINCT FROM OLD.body_generation;
END IF;
- IF body_moved OR (NEW.source_id, NEW.slug, NEW.type, NEW.page_kind, NEW.title, NEW.compiled_truth,
+ IF (NEW.source_id, NEW.slug, NEW.type, NEW.page_kind, NEW.title, NEW.compiled_truth,
NEW.timeline, NEW.frontmatter, NEW.deleted_at)
IS DISTINCT FROM
(OLD.source_id, OLD.slug, OLD.type, OLD.page_kind, OLD.title, OLD.compiled_truth,
- OLD.timeline, OLD.frontmatter, OLD.deleted_at) THEN
+ OLD.timeline, OLD.frontmatter, OLD.deleted_at) OR body_moved THEN
IF NEW.knowledge_revision = OLD.knowledge_revision AND NOT (
COALESCE(current_setting('gbrain.materializing_revision', true), '') = OLD.knowledge_revision::text
AND (NEW.source_id, NEW.slug, NEW.type, NEW.page_kind, NEW.title, NEW.frontmatter, NEW.deleted_at)
diff --git a/src/core/search/cjk-keyword-sql.ts b/src/core/search/cjk-keyword-sql.ts
index 2b05d6cb6b..247c7c98e3 100644
--- a/src/core/search/cjk-keyword-sql.ts
+++ b/src/core/search/cjk-keyword-sql.ts
@@ -110,7 +110,7 @@ export function buildCJKKeywordSql(query: string, ctx: CjkKeywordCtx, variant: C
let fromClause = 'content_chunks cc';
if (variant.candidateIds) {
params.push(variant.candidateIds);
- // chunk-visibility-ok: ctx.visibilityClause is buildVisibilityClause(..., 'cc') (engine searchKeywordCJK)
+ // chunk-visibility-ok: ctx.visibilityClause is buildVisibilityClause(..., { chunkAlias: 'cc' }) (engine searchKeywordCJK)
fromClause = `unnest($${params.length}::bigint[]) AS cand(id) JOIN content_chunks cc ON cc.id = cand.id`;
}
const { whereLikeClause, matchedExpr } = likeClauses(terms, likeParamIndices, any);
@@ -166,7 +166,7 @@ export function buildCJKCandidateSql(
const capIndex = params.length;
const { whereLikeClause } = likeClauses(terms, likeParamIndices, stage.match === 'any' && terms.length > 1);
return {
- // chunk-visibility-ok: ctx.visibilityClause is buildVisibilityClause(..., 'cc') (engine searchKeywordCJK)
+ // chunk-visibility-ok: ctx.visibilityClause is buildVisibilityClause(..., { chunkAlias: 'cc' }) (engine searchKeywordCJK)
sql: `SELECT cc.id AS chunk_id
FROM content_chunks cc
JOIN pages p ON p.id = cc.page_id
diff --git a/src/core/search/keyword-chunk-match.ts b/src/core/search/keyword-chunk-match.ts
index 48ea171a8f..bfbd698180 100644
--- a/src/core/search/keyword-chunk-match.ts
+++ b/src/core/search/keyword-chunk-match.ts
@@ -20,7 +20,7 @@ export function buildKeywordChunkMatch(ftsLang: string, excludePrivate: boolean
const tsq = `websearch_to_tsquery('${ftsLang}', $1)`;
if (!excludePrivate) return { from: 'content_chunks cc', match: `cc.search_vector @@ ${tsq}`, modality: `AND cc.modality = 'text'` };
return {
- // chunk-visibility-ok: the outer search statement applies buildVisibilityClause(..., 'cc') to the generation columns this subquery projects
+ // chunk-visibility-ok: the outer search statement applies buildVisibilityClause(..., { chunkAlias: 'cc' }) to the generation columns this subquery projects
from: `(
SELECT id, page_id, chunk_index, chunk_text, chunk_source, search_vector, language, symbol_type, body_generation, retired_generation
FROM content_chunks
diff --git a/src/core/search/keyword-statement.ts b/src/core/search/keyword-statement.ts
index 0f47ed15f2..a6fa673470 100644
--- a/src/core/search/keyword-statement.ts
+++ b/src/core/search/keyword-statement.ts
@@ -78,7 +78,7 @@ export function buildKeywordMatch(query: string, opts: SearchOpts | undefined):
const hardExclude = buildHardExcludeClause('p.slug', resolveHardExcludes(opts?.exclude_slug_prefixes, opts?.include_slug_prefixes));
const factor = buildSourceFactorCase('p.slug', opts?.source_boosts ?? resolveBoostMap(), opts?.detail);
return {
- where: `${predicate}${filters} ${hardExclude} ${buildVisibilityClause('p', 's', opts, 'cc')} AND cc.modality = 'text'`,
+ where: `${predicate}${filters} ${hardExclude} ${buildVisibilityClause('p', 's', { ...opts, chunkAlias: 'cc' })} AND cc.modality = 'text'`,
score: `((${rank}) * ${factor})::float8`,
params,
};
diff --git a/src/core/search/sql-ranking.ts b/src/core/search/sql-ranking.ts
index 9a93957f97..56e81d1a04 100644
--- a/src/core/search/sql-ranking.ts
+++ b/src/core/search/sql-ranking.ts
@@ -169,9 +169,6 @@ export function buildHardExcludeClause(slugColumn: string, prefixes: string[]):
* @param pageAlias — page table alias (e.g. `'p'`)
* @param sourceAlias — source table alias (e.g. `'s'`); the caller is
* responsible for joining `sources` so this alias resolves.
- * @param chunkAlias — chunk table alias when the statement reads `content_chunks`
- * rows joined to the page: adds the live body generation
- * predicate (`chunkVisibleFilter`, Wave B).
*
* @returns raw SQL fragment, e.g.
* `AND p.deleted_at IS NULL AND NOT s.archived AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'quarantine')`
@@ -194,8 +191,13 @@ export function buildVisibilityClause(
/** #5575: the read floor and proactive activation control (eligibility/sql.ts), applied before LIMIT. */
minTrust?: TrustTier;
suppressFlagged?: boolean;
+ /**
+ * Wave B: the chunk table alias when the statement reads `content_chunks`
+ * rows joined to the page; adds the live body generation predicate
+ * (`chunkVisibleFilter`) in place of the page-only projection filter.
+ */
+ chunkAlias?: string;
},
- chunkAlias?: string,
): string {
// Single source of truth for the quarantine SQL lives in quarantine.ts so
// the marker key + filter can't drift from the search filter (#1699).
@@ -211,7 +213,7 @@ export function buildVisibilityClause(
const pinnedQuestion = ` AND NOT (COALESCE(${pageAlias}.frontmatter, '{}'::jsonb) ? 'pinned_question')`;
const trustClause = opts?.minTrust || opts?.suppressFlagged
? ` AND ${pageEligibleSql(pageAlias, { floor: opts.minTrust, suppressFlagged: opts.suppressFlagged })}` : '';
- const projection = chunkAlias ? chunkVisibleFilter(pageAlias, chunkAlias) : currentTextProjectionFilter(pageAlias);
+ const projection = opts?.chunkAlias ? chunkVisibleFilter(pageAlias, opts.chunkAlias) : currentTextProjectionFilter(pageAlias);
return `AND ${pageAlias}.deleted_at IS NULL AND ${projection} AND NOT ${sourceAlias}.archived AND ${quarantine}${pinnedQuestion}${privateClause}${chunksClause}${trustClause}`;
}
diff --git a/src/core/search/vector-statement.ts b/src/core/search/vector-statement.ts
index 8b8ffe08ba..2d63dca342 100644
--- a/src/core/search/vector-statement.ts
+++ b/src/core/search/vector-statement.ts
@@ -324,7 +324,7 @@ export function buildVectorSearchStatement(input: VectorSearchStatementInput): V
const modalityFilter = resolvedCol.name === 'embedding_image' ? `AND cc.modality = 'image'`
: resolvedCol.name === 'embedding_multimodal' ? '' : `AND cc.modality = 'text'`;
// v0.26.5: visibility in the inner CTE so hidden rows never take candidate slots.
- const visibilityClause = buildVisibilityClause('p', 's', opts, 'cc');
+ const visibilityClause = buildVisibilityClause('p', 's', { ...opts, chunkAlias: 'cc' });
const pageVisibilityClause = buildVisibilityClause('p', 's', opts);
const candidateFrom = (generation: string) => `FROM content_chunks cc
JOIN pages p ON p.id = cc.page_id
diff --git a/src/schema.sql b/src/schema.sql
index 3d5a7a6346..6cade7fc08 100644
--- a/src/schema.sql
+++ b/src/schema.sql
@@ -166,14 +166,6 @@ CREATE TABLE IF NOT EXISTS pages (
CONSTRAINT pages_source_slug_key UNIQUE (source_id, slug)
);
--- v0.40.3.0 cache invalidation trigger (migration v91; mirrored in
--- src/core/pglite-schema.ts). BEFORE INSERT OR UPDATE so every write path
--- bumps generation per D6 / codex #4. INSERT: pages get
--- COALESCE(MAX(generation), 0) + 1 so the bookmark gate fires for any
--- cache row stored before the new page existed. UPDATE: bumps only when
--- content columns IS DISTINCT FROM (allow-list widened per D6 + codex #3
--- to include title/type/page_kind/corpus_generation/content_hash) so
--- read-time mutations don't invalidate every cache row.
-- BEGIN GENERATED from src/core/page-body/schema.ts (PAGE_GENERATION_BUMP_FN_SQL). Edit that file, then run: bun run build:schema
CREATE OR REPLACE FUNCTION bump_page_generation_fn() RETURNS trigger SET search_path = pg_catalog, public AS $func$
BEGIN
@@ -1874,11 +1866,11 @@ CREATE OR REPLACE FUNCTION gbrain_advance_page_revision() RETURNS trigger LANGUA
IF NEW.compiled_truth IS NULL AND OLD.compiled_truth IS NULL THEN
body_moved := NEW.body_generation IS DISTINCT FROM OLD.body_generation;
END IF;
- IF body_moved OR (NEW.source_id, NEW.slug, NEW.type, NEW.page_kind, NEW.title, NEW.compiled_truth,
+ IF (NEW.source_id, NEW.slug, NEW.type, NEW.page_kind, NEW.title, NEW.compiled_truth,
NEW.timeline, NEW.frontmatter, NEW.deleted_at)
IS DISTINCT FROM
(OLD.source_id, OLD.slug, OLD.type, OLD.page_kind, OLD.title, OLD.compiled_truth,
- OLD.timeline, OLD.frontmatter, OLD.deleted_at) THEN
+ OLD.timeline, OLD.frontmatter, OLD.deleted_at) OR body_moved THEN
IF NEW.knowledge_revision = OLD.knowledge_revision AND NOT (
COALESCE(current_setting('gbrain.materializing_revision', true), '') = OLD.knowledge_revision::text
AND (NEW.source_id, NEW.slug, NEW.type, NEW.page_kind, NEW.title, NEW.frontmatter, NEW.deleted_at)
diff --git a/test/engine-surface-coverage.test.ts b/test/engine-surface-coverage.test.ts
index 51271613bd..9f8cd85555 100644
--- a/test/engine-surface-coverage.test.ts
+++ b/test/engine-surface-coverage.test.ts
@@ -114,6 +114,9 @@ const INTERFACE_METHODS: readonly string[] = [
// Salience + anomaly + enrich
'batchLoadEmotionalInputs', 'setEmotionalWeightBatch', 'getRecentSalience', 'listEnrichCandidates',
'findAnomalies',
+ // Wave B segmented page bodies (src/core/engine-sql/page-body.ts; covered by test/large-pages/ and test/engine-sql-page-body.test.ts)
+ 'allocateBodyOccurrenceIds', 'stageSegmentTexts', 'readSegmentTexts', 'stageManifestRows', 'readManifest', 'stageSegmentChunks',
+ 'createSegmentedPageShell', 'flipBodyGeneration', 'openBodyStaging', 'setBodyStagingState', 'sweepSegments',
];
/**
diff --git a/test/fixtures/goldens/exports/runtime.json b/test/fixtures/goldens/exports/runtime.json
index ba52f5c57b..a509aa632b 100644
--- a/test/fixtures/goldens/exports/runtime.json
+++ b/test/fixtures/goldens/exports/runtime.json
@@ -673,6 +673,7 @@
"importFromFile",
"importImageFile",
"isImageFilePath",
+ "loadBrainTimeZone",
"pLimit",
"slugConflictHoldMessage",
"verifyPageReadable",
diff --git a/test/fixtures/goldens/exports/types.json b/test/fixtures/goldens/exports/types.json
index a5085eb3f2..675d04f1a5 100644
--- a/test/fixtures/goldens/exports/types.json
+++ b/test/fixtures/goldens/exports/types.json
@@ -4672,21 +4672,21 @@
"kind": "variable",
"name": "importFile",
"signature": [
- "(engine: BrainEngine, filePath: string, relativePath: string, opts?: { noEmbed?: boolean; inferFrontmatter?: boolean; sourceId?: string; forceRechunk?: boolean; activePack?: { page_types: ReadonlyArray<{ name: string; path_prefixes: ReadonlyArray<string>; aliases?: ReadonlyArray<string>; }>; }; firstCommitAt?: Date; }) => Promise<ImportResult>"
+ "(engine: BrainEngine, filePath: string, relativePath: string, opts?: { noEmbed?: boolean; inferFrontmatter?: boolean; sourceId?: string; forceRechunk?: boolean; activePack?: { page_types: ReadonlyArray<{ name: string; path_prefixes: ReadonlyArray<string>; aliases?: ReadonlyArray<string>; }>; }; firstCommitAt?: Date; bodyPolicy?: PageBodyPolicy; }) => Promise<ImportResult>"
]
},
{
"kind": "function",
"name": "importFromContent",
"signature": [
- "(engine: BrainEngine, slug: string, content: string, opts?: { prepare?: (prepared: PreparedContentImport) => Promise<ImportResult>; coordinated?: boolean; existingSnapshot?: PageSnapshot | null; prepareFrontmatter?: (page: ParsedPage) => void; noEmbed?: boolean; sourceId?: string; filename?: string; sourcePath?: string; sourceRoot?: string; fileTimes?: { birthtime?: Date; mtime?: Date; firstCommit?: Date; }; forceRechunk?: boolean; activePack?: ParseOpts[\"activePack\"]; source_kind?: string | null; source_uri?: string | null; ingested_via?: string | null; remote?: boolean; preserveGateMarkers?: boolean; allowEmptyOverwrite?: boolean; overrideTier?: unknown; writeGate?: WriteGateInput; beforeCommit?: (tx: BrainEngine, slug: string) => Promise<void>; onPostCommitEmbedding?: (complete: () => Promise<ImportEmbeddingResult>) => void; } & ImportFenceOptions) => Promise<ImportResult>"
+ "(engine: BrainEngine, slug: string, content: string, opts?: { prepare?: (prepared: PreparedContentImport) => Promise<ImportResult>; coordinated?: boolean; existingSnapshot?: PageSnapshot | null; prepareFrontmatter?: (page: ParsedPage) => void; noEmbed?: boolean; sourceId?: string; filename?: string; sourcePath?: string; sourceRoot?: string; fileTimes?: { birthtime?: Date; mtime?: Date; firstCommit?: Date; }; forceRechunk?: boolean; activePack?: ParseOpts[\"activePack\"]; source_kind?: string | null; source_uri?: string | null; ingested_via?: string | null; segmentedOwner?: SegmentedStagingOwner; remote?: boolean; preserveGateMarkers?: boolean; allowEmptyOverwrite?: boolean; overrideTier?: unknown; writeGate?: WriteGateInput; beforeCommit?: (tx: BrainEngine, slug: string) => Promise<void>; onPostCommitEmbedding?: (complete: () => Promise<ImportEmbeddingResult>) => void; } & ImportFenceOptions) => Promise<ImportResult>"
]
},
{
"kind": "function",
"name": "importFromFile",
"signature": [
- "(engine: BrainEngine, filePath: string, relativePath: string, opts?: { noEmbed?: boolean; inferFrontmatter?: boolean; sourceId?: string; forceRechunk?: boolean; activePack?: { page_types: ReadonlyArray<{ name: string; path_prefixes: ReadonlyArray<string>; aliases?: ReadonlyArray<string>; }>; }; firstCommitAt?: Date; }) => Promise<ImportResult>"
+ "(engine: BrainEngine, filePath: string, relativePath: string, opts?: { noEmbed?: boolean; inferFrontmatter?: boolean; sourceId?: string; forceRechunk?: boolean; activePack?: { page_types: ReadonlyArray<{ name: string; path_prefixes: ReadonlyArray<string>; aliases?: ReadonlyArray<string>; }>; }; firstCommitAt?: Date; bodyPolicy?: PageBodyPolicy; }) => Promise<ImportResult>"
]
},
{
@@ -4703,6 +4703,13 @@
"(relativePath: string) => boolean"
]
},
+ {
+ "kind": "function",
+ "name": "loadBrainTimeZone",
+ "signature": [
+ "(engine: BrainEngine) => Promise<string | undefined>"
+ ]
+ },
{
"kind": "function",
"name": "pLimit",
diff --git a/test/large-pages/body-scan.test.ts b/test/large-pages/body-scan.test.ts
index caff87a66c..588641e103 100644
--- a/test/large-pages/body-scan.test.ts
+++ b/test/large-pages/body-scan.test.ts
@@ -155,7 +155,7 @@ describe('body scan on files larger than the head bound', () => {
const got = capture(() => scanMarkdownString(content, 'notes/x.md', { validate }));
if (!('thrown' in got) && got.kind === 'frontmatter_head_unbounded') {
refused++;
- const head = content.slice(0, FRONTMATTER_HEAD_MAX_BYTES);
+ const head = new TextDecoder().decode(Buffer.from(content, 'utf8').subarray(0, FRONTMATTER_HEAD_MAX_BYTES), { stream: true });
expect(!/\S/.test(head) || /^\s*-/.test(head)).toBe(true);
return;
}
diff --git a/test/scripts/chunk-visibility-ratchet.test.ts b/test/scripts/chunk-visibility-ratchet.test.ts
index 5f601bb933..5f676ee2ef 100644
--- a/test/scripts/chunk-visibility-ratchet.test.ts
+++ b/test/scripts/chunk-visibility-ratchet.test.ts
@@ -62,7 +62,7 @@ describe('check-chunk-visibility.ts', () => {
"const live = chunkGenerationFilter('p', 'cc');",
'const where = `AND ${live}`;',
'export const viaHelper = `SELECT 1 FROM content_chunks cc JOIN pages p ON p.id = cc.page_id WHERE true ${where}`;',
- "export const clause = `SELECT 1 FROM content_chunks cc JOIN pages p ON p.id = cc.page_id WHERE ${buildVisibilityClause('p', 's', {}, 'cc')}`;",
+ "export const clause = `SELECT 1 FROM content_chunks cc JOIN pages p ON p.id = cc.page_id WHERE ${buildVisibilityClause('p', 's', { chunkAlias: 'cc' })}`;",
"export const sqlMarker = 'SELECT count(*) FROM content_chunks -- chunk-visibility-ok: storage statistics';",
'// chunk-visibility-ok: code pages are never segmented',
"export const lineMarker = 'SELECT id FROM content_chunks WHERE symbol_name_qualified = $1';",