Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
Wave B PR 1 lane 1c: segmented page bodies unreachable, page body reader ratchet
garrytan939f6cc9a88b
diff --git a/.github/workflows/e2e.yml b/.github/workflows/e2e.ymlindex be09671f44..c531fd3049 100644--- a/.github/workflows/e2e.yml+++ b/.github/workflows/e2e.yml@@ -85,7 +85,7 @@ jobs:path: |test/fixtures/pglite-snapshot.tartest/fixtures/pglite-snapshot.version- key: pglite-snapshot-${{ runner.os }}-${{ hashFiles('src/core/*.ts', 'src/core/audit/redact-connection-info.ts', 'src/core/engine-sql/bootstrap.ts', 'src/core/schema-migrations/**', 'src/core/ai/defaults.ts', 'src/core/company-brain/receipt-schema.ts', 'src/core/entities/resolve.ts', 'src/core/facts/withdrawal-schema.ts', 'src/core/facts/relink-schema.ts', 'src/core/google/*.ts', 'src/core/grants/*.ts', 'src/core/minions/tools/brain-allowlist.ts', 'src/core/ops/contract.ts', 'src/core/page-state/*schema.ts', 'src/core/persistence/*.ts', 'src/core/schema-pack/link-inference.ts', 'src/core/schema-pack/redos-guard.ts', 'src/core/search/alias-normalize.ts', 'src/core/search/private-visibility.ts', 'src/core/search/projection-statistics.ts', 'src/core/search/relational-intent.ts', 'src/core/shared-skills/*schema*.ts', 'src/core/ai/decide/schema.ts', 'test/helpers/legacy-embedding-config.ts', 'scripts/build-pglite-snapshot.ts', 'src/core/facts/purge-schema.ts', 'src/core/facts/fts-index.ts', 'src/core/eligibility/generation-schema.ts', 'src/core/trust/schema.ts', 'src/core/trust/tier.ts', 'src/core/trust/allow-rules.ts', 'src/core/write-gate-schema.ts', 'src/core/questions/schema.ts', 'src/core/questions/identity.ts', 'src/core/questions/auto-think-migration.ts', 'src/core/loops/loops-schema.ts', 'src/core/postgres-engine/schema-lock-timeout.ts') }}+ key: pglite-snapshot-${{ runner.os }}-${{ hashFiles('src/core/*.ts', 'src/core/audit/redact-connection-info.ts', 'src/core/engine-sql/bootstrap.ts', 'src/core/schema-migrations/**', 'src/core/ai/defaults.ts', 'src/core/company-brain/receipt-schema.ts', 'src/core/entities/resolve.ts', 'src/core/facts/withdrawal-schema.ts', 'src/core/facts/relink-schema.ts', 'src/core/google/*.ts', 'src/core/grants/*.ts', 'src/core/minions/tools/brain-allowlist.ts', 'src/core/ops/contract.ts', 'src/core/page-body/page-shape.ts', 'src/core/page-state/*schema.ts', 'src/core/persistence/*.ts', 'src/core/schema-pack/link-inference.ts', 'src/core/schema-pack/redos-guard.ts', 'src/core/search/alias-normalize.ts', 'src/core/search/private-visibility.ts', 'src/core/search/projection-statistics.ts', 'src/core/search/relational-intent.ts', 'src/core/shared-skills/*schema*.ts', 'src/core/ai/decide/schema.ts', 'test/helpers/legacy-embedding-config.ts', 'scripts/build-pglite-snapshot.ts', 'src/core/facts/purge-schema.ts', 'src/core/facts/fts-index.ts', 'src/core/eligibility/generation-schema.ts', 'src/core/trust/schema.ts', 'src/core/trust/tier.ts', 'src/core/trust/allow-rules.ts', 'src/core/write-gate-schema.ts', 'src/core/questions/schema.ts', 'src/core/questions/identity.ts', 'src/core/questions/auto-think-migration.ts', 'src/core/loops/loops-schema.ts', 'src/core/postgres-engine/schema-lock-timeout.ts') }}- name: Install dependencies (bounded, retried once)timeout-minutes: 8run: bun scripts/ci-bun-install.ts --frozen-lockfile@@ -232,7 +232,7 @@ jobs:path: |test/fixtures/pglite-snapshot.tartest/fixtures/pglite-snapshot.version- key: pglite-snapshot-${{ runner.os }}-${{ hashFiles('src/core/*.ts', 'src/core/audit/redact-connection-info.ts', 'src/core/engine-sql/bootstrap.ts', 'src/core/schema-migrations/**', 'src/core/ai/defaults.ts', 'src/core/company-brain/receipt-schema.ts', 'src/core/entities/resolve.ts', 'src/core/facts/withdrawal-schema.ts', 'src/core/facts/relink-schema.ts', 'src/core/google/*.ts', 'src/core/grants/*.ts', 'src/core/minions/tools/brain-allowlist.ts', 'src/core/ops/contract.ts', 'src/core/page-state/*schema.ts', 'src/core/persistence/*.ts', 'src/core/schema-pack/link-inference.ts', 'src/core/schema-pack/redos-guard.ts', 'src/core/search/alias-normalize.ts', 'src/core/search/private-visibility.ts', 'src/core/search/projection-statistics.ts', 'src/core/search/relational-intent.ts', 'src/core/shared-skills/*schema*.ts', 'src/core/ai/decide/schema.ts', 'test/helpers/legacy-embedding-config.ts', 'scripts/build-pglite-snapshot.ts', 'src/core/facts/purge-schema.ts', 'src/core/facts/fts-index.ts', 'src/core/eligibility/generation-schema.ts', 'src/core/trust/schema.ts', 'src/core/trust/tier.ts', 'src/core/trust/allow-rules.ts', 'src/core/write-gate-schema.ts', 'src/core/questions/schema.ts', 'src/core/questions/identity.ts', 'src/core/questions/auto-think-migration.ts', 'src/core/loops/loops-schema.ts', 'src/core/postgres-engine/schema-lock-timeout.ts') }}+ key: pglite-snapshot-${{ runner.os }}-${{ hashFiles('src/core/*.ts', 'src/core/audit/redact-connection-info.ts', 'src/core/engine-sql/bootstrap.ts', 'src/core/schema-migrations/**', 'src/core/ai/defaults.ts', 'src/core/company-brain/receipt-schema.ts', 'src/core/entities/resolve.ts', 'src/core/facts/withdrawal-schema.ts', 'src/core/facts/relink-schema.ts', 'src/core/google/*.ts', 'src/core/grants/*.ts', 'src/core/minions/tools/brain-allowlist.ts', 'src/core/ops/contract.ts', 'src/core/page-body/page-shape.ts', 'src/core/page-state/*schema.ts', 'src/core/persistence/*.ts', 'src/core/schema-pack/link-inference.ts', 'src/core/schema-pack/redos-guard.ts', 'src/core/search/alias-normalize.ts', 'src/core/search/private-visibility.ts', 'src/core/search/projection-statistics.ts', 'src/core/search/relational-intent.ts', 'src/core/shared-skills/*schema*.ts', 'src/core/ai/decide/schema.ts', 'test/helpers/legacy-embedding-config.ts', 'scripts/build-pglite-snapshot.ts', 'src/core/facts/purge-schema.ts', 'src/core/facts/fts-index.ts', 'src/core/eligibility/generation-schema.ts', 'src/core/trust/schema.ts', 'src/core/trust/tier.ts', 'src/core/trust/allow-rules.ts', 'src/core/write-gate-schema.ts', 'src/core/questions/schema.ts', 'src/core/questions/identity.ts', 'src/core/questions/auto-think-migration.ts', 'src/core/loops/loops-schema.ts', 'src/core/postgres-engine/schema-lock-timeout.ts') }}- name: Install dependencies (bounded, retried once)timeout-minutes: 8run: bun scripts/ci-bun-install.ts --frozen-lockfile@@ -326,7 +326,7 @@ jobs:path: |test/fixtures/pglite-snapshot.tartest/fixtures/pglite-snapshot.version- key: pglite-snapshot-${{ runner.os }}-${{ hashFiles('src/core/*.ts', 'src/core/audit/redact-connection-info.ts', 'src/core/engine-sql/bootstrap.ts', 'src/core/schema-migrations/**', 'src/core/ai/defaults.ts', 'src/core/company-brain/receipt-schema.ts', 'src/core/entities/resolve.ts', 'src/core/facts/withdrawal-schema.ts', 'src/core/facts/relink-schema.ts', 'src/core/google/*.ts', 'src/core/grants/*.ts', 'src/core/minions/tools/brain-allowlist.ts', 'src/core/ops/contract.ts', 'src/core/page-state/*schema.ts', 'src/core/persistence/*.ts', 'src/core/schema-pack/link-inference.ts', 'src/core/schema-pack/redos-guard.ts', 'src/core/search/alias-normalize.ts', 'src/core/search/private-visibility.ts', 'src/core/search/projection-statistics.ts', 'src/core/search/relational-intent.ts', 'src/core/shared-skills/*schema*.ts', 'src/core/ai/decide/schema.ts', 'test/helpers/legacy-embedding-config.ts', 'scripts/build-pglite-snapshot.ts', 'src/core/facts/purge-schema.ts', 'src/core/facts/fts-index.ts', 'src/core/eligibility/generation-schema.ts', 'src/core/trust/schema.ts', 'src/core/trust/tier.ts', 'src/core/trust/allow-rules.ts', 'src/core/write-gate-schema.ts', 'src/core/questions/schema.ts', 'src/core/questions/identity.ts', 'src/core/questions/auto-think-migration.ts', 'src/core/loops/loops-schema.ts', 'src/core/postgres-engine/schema-lock-timeout.ts') }}+ key: pglite-snapshot-${{ runner.os }}-${{ hashFiles('src/core/*.ts', 'src/core/audit/redact-connection-info.ts', 'src/core/engine-sql/bootstrap.ts', 'src/core/schema-migrations/**', 'src/core/ai/defaults.ts', 'src/core/company-brain/receipt-schema.ts', 'src/core/entities/resolve.ts', 'src/core/facts/withdrawal-schema.ts', 'src/core/facts/relink-schema.ts', 'src/core/google/*.ts', 'src/core/grants/*.ts', 'src/core/minions/tools/brain-allowlist.ts', 'src/core/ops/contract.ts', 'src/core/page-body/page-shape.ts', 'src/core/page-state/*schema.ts', 'src/core/persistence/*.ts', 'src/core/schema-pack/link-inference.ts', 'src/core/schema-pack/redos-guard.ts', 'src/core/search/alias-normalize.ts', 'src/core/search/private-visibility.ts', 'src/core/search/projection-statistics.ts', 'src/core/search/relational-intent.ts', 'src/core/shared-skills/*schema*.ts', 'src/core/ai/decide/schema.ts', 'test/helpers/legacy-embedding-config.ts', 'scripts/build-pglite-snapshot.ts', 'src/core/facts/purge-schema.ts', 'src/core/facts/fts-index.ts', 'src/core/eligibility/generation-schema.ts', 'src/core/trust/schema.ts', 'src/core/trust/tier.ts', 'src/core/trust/allow-rules.ts', 'src/core/write-gate-schema.ts', 'src/core/questions/schema.ts', 'src/core/questions/identity.ts', 'src/core/questions/auto-think-migration.ts', 'src/core/loops/loops-schema.ts', 'src/core/postgres-engine/schema-lock-timeout.ts') }}- name: Install dependencies (bounded, retried once)timeout-minutes: 8run: bun scripts/ci-bun-install.ts --frozen-lockfile@@ -512,7 +512,7 @@ jobs:path: |test/fixtures/pglite-snapshot.tartest/fixtures/pglite-snapshot.version- key: pglite-snapshot-${{ runner.os }}-${{ hashFiles('src/core/*.ts', 'src/core/audit/redact-connection-info.ts', 'src/core/engine-sql/bootstrap.ts', 'src/core/schema-migrations/**', 'src/core/ai/defaults.ts', 'src/core/company-brain/receipt-schema.ts', 'src/core/entities/resolve.ts', 'src/core/facts/withdrawal-schema.ts', 'src/core/facts/relink-schema.ts', 'src/core/google/*.ts', 'src/core/grants/*.ts', 'src/core/minions/tools/brain-allowlist.ts', 'src/core/ops/contract.ts', 'src/core/page-state/*schema.ts', 'src/core/persistence/*.ts', 'src/core/schema-pack/link-inference.ts', 'src/core/schema-pack/redos-guard.ts', 'src/core/search/alias-normalize.ts', 'src/core/search/private-visibility.ts', 'src/core/search/projection-statistics.ts', 'src/core/search/relational-intent.ts', 'src/core/shared-skills/*schema*.ts', 'src/core/ai/decide/schema.ts', 'test/helpers/legacy-embedding-config.ts', 'scripts/build-pglite-snapshot.ts', 'src/core/facts/purge-schema.ts', 'src/core/facts/fts-index.ts', 'src/core/eligibility/generation-schema.ts', 'src/core/trust/schema.ts', 'src/core/trust/tier.ts', 'src/core/trust/allow-rules.ts', 'src/core/write-gate-schema.ts', 'src/core/questions/schema.ts', 'src/core/questions/identity.ts', 'src/core/questions/auto-think-migration.ts', 'src/core/loops/loops-schema.ts', 'src/core/postgres-engine/schema-lock-timeout.ts') }}+ key: pglite-snapshot-${{ runner.os }}-${{ hashFiles('src/core/*.ts', 'src/core/audit/redact-connection-info.ts', 'src/core/engine-sql/bootstrap.ts', 'src/core/schema-migrations/**', 'src/core/ai/defaults.ts', 'src/core/company-brain/receipt-schema.ts', 'src/core/entities/resolve.ts', 'src/core/facts/withdrawal-schema.ts', 'src/core/facts/relink-schema.ts', 'src/core/google/*.ts', 'src/core/grants/*.ts', 'src/core/minions/tools/brain-allowlist.ts', 'src/core/ops/contract.ts', 'src/core/page-body/page-shape.ts', 'src/core/page-state/*schema.ts', 'src/core/persistence/*.ts', 'src/core/schema-pack/link-inference.ts', 'src/core/schema-pack/redos-guard.ts', 'src/core/search/alias-normalize.ts', 'src/core/search/private-visibility.ts', 'src/core/search/projection-statistics.ts', 'src/core/search/relational-intent.ts', 'src/core/shared-skills/*schema*.ts', 'src/core/ai/decide/schema.ts', 'test/helpers/legacy-embedding-config.ts', 'scripts/build-pglite-snapshot.ts', 'src/core/facts/purge-schema.ts', 'src/core/facts/fts-index.ts', 'src/core/eligibility/generation-schema.ts', 'src/core/trust/schema.ts', 'src/core/trust/tier.ts', 'src/core/trust/allow-rules.ts', 'src/core/write-gate-schema.ts', 'src/core/questions/schema.ts', 'src/core/questions/identity.ts', 'src/core/questions/auto-think-migration.ts', 'src/core/loops/loops-schema.ts', 'src/core/postgres-engine/schema-lock-timeout.ts') }}- name: Install dependencies (bounded, retried once)timeout-minutes: 8run: bun scripts/ci-bun-install.ts --frozen-lockfile@@ -600,7 +600,7 @@ jobs:path: |test/fixtures/pglite-snapshot.tartest/fixtures/pglite-snapshot.version- key: pglite-snapshot-${{ runner.os }}-${{ hashFiles('src/core/*.ts', 'src/core/audit/redact-connection-info.ts', 'src/core/engine-sql/bootstrap.ts', 'src/core/schema-migrations/**', 'src/core/ai/defaults.ts', 'src/core/company-brain/receipt-schema.ts', 'src/core/entities/resolve.ts', 'src/core/facts/withdrawal-schema.ts', 'src/core/facts/relink-schema.ts', 'src/core/google/*.ts', 'src/core/grants/*.ts', 'src/core/minions/tools/brain-allowlist.ts', 'src/core/ops/contract.ts', 'src/core/page-state/*schema.ts', 'src/core/persistence/*.ts', 'src/core/schema-pack/link-inference.ts', 'src/core/schema-pack/redos-guard.ts', 'src/core/search/alias-normalize.ts', 'src/core/search/private-visibility.ts', 'src/core/search/projection-statistics.ts', 'src/core/search/relational-intent.ts', 'src/core/shared-skills/*schema*.ts', 'src/core/ai/decide/schema.ts', 'test/helpers/legacy-embedding-config.ts', 'scripts/build-pglite-snapshot.ts', 'src/core/facts/purge-schema.ts', 'src/core/facts/fts-index.ts', 'src/core/eligibility/generation-schema.ts', 'src/core/trust/schema.ts', 'src/core/trust/tier.ts', 'src/core/trust/allow-rules.ts', 'src/core/write-gate-schema.ts', 'src/core/questions/schema.ts', 'src/core/questions/identity.ts', 'src/core/questions/auto-think-migration.ts', 'src/core/loops/loops-schema.ts', 'src/core/postgres-engine/schema-lock-timeout.ts') }}+ key: pglite-snapshot-${{ runner.os }}-${{ hashFiles('src/core/*.ts', 'src/core/audit/redact-connection-info.ts', 'src/core/engine-sql/bootstrap.ts', 'src/core/schema-migrations/**', 'src/core/ai/defaults.ts', 'src/core/company-brain/receipt-schema.ts', 'src/core/entities/resolve.ts', 'src/core/facts/withdrawal-schema.ts', 'src/core/facts/relink-schema.ts', 'src/core/google/*.ts', 'src/core/grants/*.ts', 'src/core/minions/tools/brain-allowlist.ts', 'src/core/ops/contract.ts', 'src/core/page-body/page-shape.ts', 'src/core/page-state/*schema.ts', 'src/core/persistence/*.ts', 'src/core/schema-pack/link-inference.ts', 'src/core/schema-pack/redos-guard.ts', 'src/core/search/alias-normalize.ts', 'src/core/search/private-visibility.ts', 'src/core/search/projection-statistics.ts', 'src/core/search/relational-intent.ts', 'src/core/shared-skills/*schema*.ts', 'src/core/ai/decide/schema.ts', 'test/helpers/legacy-embedding-config.ts', 'scripts/build-pglite-snapshot.ts', 'src/core/facts/purge-schema.ts', 'src/core/facts/fts-index.ts', 'src/core/eligibility/generation-schema.ts', 'src/core/trust/schema.ts', 'src/core/trust/tier.ts', 'src/core/trust/allow-rules.ts', 'src/core/write-gate-schema.ts', 'src/core/questions/schema.ts', 'src/core/questions/identity.ts', 'src/core/questions/auto-think-migration.ts', 'src/core/loops/loops-schema.ts', 'src/core/postgres-engine/schema-lock-timeout.ts') }}- name: Install dependencies (bounded, retried once)timeout-minutes: 8run: bun scripts/ci-bun-install.ts --frozen-lockfile@@ -897,7 +897,7 @@ jobs:path: |test/fixtures/pglite-snapshot.tartest/fixtures/pglite-snapshot.version- key: pglite-snapshot-${{ runner.os }}-${{ hashFiles('src/core/*.ts', 'src/core/audit/redact-connection-info.ts', 'src/core/engine-sql/bootstrap.ts', 'src/core/schema-migrations/**', 'src/core/ai/defaults.ts', 'src/core/company-brain/receipt-schema.ts', 'src/core/entities/resolve.ts', 'src/core/facts/withdrawal-schema.ts', 'src/core/facts/relink-schema.ts', 'src/core/google/*.ts', 'src/core/grants/*.ts', 'src/core/minions/tools/brain-allowlist.ts', 'src/core/ops/contract.ts', 'src/core/page-state/*schema.ts', 'src/core/persistence/*.ts', 'src/core/schema-pack/link-inference.ts', 'src/core/schema-pack/redos-guard.ts', 'src/core/search/alias-normalize.ts', 'src/core/search/private-visibility.ts', 'src/core/search/projection-statistics.ts', 'src/core/search/relational-intent.ts', 'src/core/shared-skills/*schema*.ts', 'src/core/ai/decide/schema.ts', 'test/helpers/legacy-embedding-config.ts', 'scripts/build-pglite-snapshot.ts', 'src/core/facts/purge-schema.ts', 'src/core/facts/fts-index.ts', 'src/core/eligibility/generation-schema.ts', 'src/core/trust/schema.ts', 'src/core/trust/tier.ts', 'src/core/trust/allow-rules.ts', 'src/core/write-gate-schema.ts', 'src/core/questions/schema.ts', 'src/core/questions/identity.ts', 'src/core/questions/auto-think-migration.ts', 'src/core/loops/loops-schema.ts', 'src/core/postgres-engine/schema-lock-timeout.ts') }}+ key: pglite-snapshot-${{ runner.os }}-${{ hashFiles('src/core/*.ts', 'src/core/audit/redact-connection-info.ts', 'src/core/engine-sql/bootstrap.ts', 'src/core/schema-migrations/**', 'src/core/ai/defaults.ts', 'src/core/company-brain/receipt-schema.ts', 'src/core/entities/resolve.ts', 'src/core/facts/withdrawal-schema.ts', 'src/core/facts/relink-schema.ts', 'src/core/google/*.ts', 'src/core/grants/*.ts', 'src/core/minions/tools/brain-allowlist.ts', 'src/core/ops/contract.ts', 'src/core/page-body/page-shape.ts', 'src/core/page-state/*schema.ts', 'src/core/persistence/*.ts', 'src/core/schema-pack/link-inference.ts', 'src/core/schema-pack/redos-guard.ts', 'src/core/search/alias-normalize.ts', 'src/core/search/private-visibility.ts', 'src/core/search/projection-statistics.ts', 'src/core/search/relational-intent.ts', 'src/core/shared-skills/*schema*.ts', 'src/core/ai/decide/schema.ts', 'test/helpers/legacy-embedding-config.ts', 'scripts/build-pglite-snapshot.ts', 'src/core/facts/purge-schema.ts', 'src/core/facts/fts-index.ts', 'src/core/eligibility/generation-schema.ts', 'src/core/trust/schema.ts', 'src/core/trust/tier.ts', 'src/core/trust/allow-rules.ts', 'src/core/write-gate-schema.ts', 'src/core/questions/schema.ts', 'src/core/questions/identity.ts', 'src/core/questions/auto-think-migration.ts', 'src/core/loops/loops-schema.ts', 'src/core/postgres-engine/schema-lock-timeout.ts') }}- name: Install dependencies (bounded, retried once)timeout-minutes: 8run: bun scripts/ci-bun-install.ts --frozen-lockfilediff --git a/.github/workflows/stress.yml b/.github/workflows/stress.ymlindex 47ecd3e84d..8f1b3e1ebc 100644--- a/.github/workflows/stress.yml+++ b/.github/workflows/stress.yml@@ -119,7 +119,7 @@ jobs:path: |test/fixtures/pglite-snapshot.tartest/fixtures/pglite-snapshot.version- key: pglite-snapshot-${{ runner.os }}-${{ hashFiles('src/core/*.ts', 'src/core/audit/redact-connection-info.ts', 'src/core/engine-sql/bootstrap.ts', 'src/core/schema-migrations/**', 'src/core/ai/defaults.ts', 'src/core/company-brain/receipt-schema.ts', 'src/core/entities/resolve.ts', 'src/core/facts/withdrawal-schema.ts', 'src/core/facts/relink-schema.ts', 'src/core/google/*.ts', 'src/core/grants/*.ts', 'src/core/minions/tools/brain-allowlist.ts', 'src/core/ops/contract.ts', 'src/core/page-state/*schema.ts', 'src/core/persistence/*.ts', 'src/core/schema-pack/link-inference.ts', 'src/core/schema-pack/redos-guard.ts', 'src/core/search/alias-normalize.ts', 'src/core/search/private-visibility.ts', 'src/core/search/projection-statistics.ts', 'src/core/search/relational-intent.ts', 'src/core/shared-skills/*schema*.ts', 'src/core/ai/decide/schema.ts', 'test/helpers/legacy-embedding-config.ts', 'scripts/build-pglite-snapshot.ts', 'src/core/facts/purge-schema.ts', 'src/core/facts/fts-index.ts', 'src/core/eligibility/generation-schema.ts', 'src/core/trust/schema.ts', 'src/core/trust/tier.ts', 'src/core/trust/allow-rules.ts', 'src/core/write-gate-schema.ts', 'src/core/questions/schema.ts', 'src/core/questions/identity.ts', 'src/core/questions/auto-think-migration.ts', 'src/core/loops/loops-schema.ts', 'src/core/postgres-engine/schema-lock-timeout.ts') }}+ key: pglite-snapshot-${{ runner.os }}-${{ hashFiles('src/core/*.ts', 'src/core/audit/redact-connection-info.ts', 'src/core/engine-sql/bootstrap.ts', 'src/core/schema-migrations/**', 'src/core/ai/defaults.ts', 'src/core/company-brain/receipt-schema.ts', 'src/core/entities/resolve.ts', 'src/core/facts/withdrawal-schema.ts', 'src/core/facts/relink-schema.ts', 'src/core/google/*.ts', 'src/core/grants/*.ts', 'src/core/minions/tools/brain-allowlist.ts', 'src/core/ops/contract.ts', 'src/core/page-body/page-shape.ts', 'src/core/page-state/*schema.ts', 'src/core/persistence/*.ts', 'src/core/schema-pack/link-inference.ts', 'src/core/schema-pack/redos-guard.ts', 'src/core/search/alias-normalize.ts', 'src/core/search/private-visibility.ts', 'src/core/search/projection-statistics.ts', 'src/core/search/relational-intent.ts', 'src/core/shared-skills/*schema*.ts', 'src/core/ai/decide/schema.ts', 'test/helpers/legacy-embedding-config.ts', 'scripts/build-pglite-snapshot.ts', 'src/core/facts/purge-schema.ts', 'src/core/facts/fts-index.ts', 'src/core/eligibility/generation-schema.ts', 'src/core/trust/schema.ts', 'src/core/trust/tier.ts', 'src/core/trust/allow-rules.ts', 'src/core/write-gate-schema.ts', 'src/core/questions/schema.ts', 'src/core/questions/identity.ts', 'src/core/questions/auto-think-migration.ts', 'src/core/loops/loops-schema.ts', 'src/core/postgres-engine/schema-lock-timeout.ts') }}- name: Install dependencies (bounded, retried once)timeout-minutes: 8run: bun scripts/ci-bun-install.ts --frozen-lockfilediff --git a/.github/workflows/test.yml b/.github/workflows/test.ymlindex 2c6a966d5e..e52e1b5336 100644--- a/.github/workflows/test.yml+++ b/.github/workflows/test.yml@@ -333,7 +333,7 @@ jobs:path: |test/fixtures/pglite-snapshot.tartest/fixtures/pglite-snapshot.version- key: pglite-snapshot-${{ runner.os }}-${{ hashFiles('src/core/*.ts', 'src/core/audit/redact-connection-info.ts', 'src/core/engine-sql/bootstrap.ts', 'src/core/schema-migrations/**', 'src/core/ai/defaults.ts', 'src/core/company-brain/receipt-schema.ts', 'src/core/entities/resolve.ts', 'src/core/facts/withdrawal-schema.ts', 'src/core/facts/relink-schema.ts', 'src/core/google/*.ts', 'src/core/grants/*.ts', 'src/core/minions/tools/brain-allowlist.ts', 'src/core/ops/contract.ts', 'src/core/page-state/*schema.ts', 'src/core/persistence/*.ts', 'src/core/schema-pack/link-inference.ts', 'src/core/schema-pack/redos-guard.ts', 'src/core/search/alias-normalize.ts', 'src/core/search/private-visibility.ts', 'src/core/search/projection-statistics.ts', 'src/core/search/relational-intent.ts', 'src/core/shared-skills/*schema*.ts', 'src/core/ai/decide/schema.ts', 'test/helpers/legacy-embedding-config.ts', 'scripts/build-pglite-snapshot.ts', 'src/core/facts/purge-schema.ts', 'src/core/facts/fts-index.ts', 'src/core/eligibility/generation-schema.ts', 'src/core/trust/schema.ts', 'src/core/trust/tier.ts', 'src/core/trust/allow-rules.ts', 'src/core/write-gate-schema.ts', 'src/core/questions/schema.ts', 'src/core/questions/identity.ts', 'src/core/questions/auto-think-migration.ts', 'src/core/loops/loops-schema.ts', 'src/core/postgres-engine/schema-lock-timeout.ts') }}+ key: pglite-snapshot-${{ runner.os }}-${{ hashFiles('src/core/*.ts', 'src/core/audit/redact-connection-info.ts', 'src/core/engine-sql/bootstrap.ts', 'src/core/schema-migrations/**', 'src/core/ai/defaults.ts', 'src/core/company-brain/receipt-schema.ts', 'src/core/entities/resolve.ts', 'src/core/facts/withdrawal-schema.ts', 'src/core/facts/relink-schema.ts', 'src/core/google/*.ts', 'src/core/grants/*.ts', 'src/core/minions/tools/brain-allowlist.ts', 'src/core/ops/contract.ts', 'src/core/page-body/page-shape.ts', 'src/core/page-state/*schema.ts', 'src/core/persistence/*.ts', 'src/core/schema-pack/link-inference.ts', 'src/core/schema-pack/redos-guard.ts', 'src/core/search/alias-normalize.ts', 'src/core/search/private-visibility.ts', 'src/core/search/projection-statistics.ts', 'src/core/search/relational-intent.ts', 'src/core/shared-skills/*schema*.ts', 'src/core/ai/decide/schema.ts', 'test/helpers/legacy-embedding-config.ts', 'scripts/build-pglite-snapshot.ts', 'src/core/facts/purge-schema.ts', 'src/core/facts/fts-index.ts', 'src/core/eligibility/generation-schema.ts', 'src/core/trust/schema.ts', 'src/core/trust/tier.ts', 'src/core/trust/allow-rules.ts', 'src/core/write-gate-schema.ts', 'src/core/questions/schema.ts', 'src/core/questions/identity.ts', 'src/core/questions/auto-think-migration.ts', 'src/core/loops/loops-schema.ts', 'src/core/postgres-engine/schema-lock-timeout.ts') }}- name: Install dependencies (bounded, retried once)timeout-minutes: 8run: bun scripts/ci-bun-install.ts --frozen-lockfile@@ -443,7 +443,7 @@ jobs:path: |test/fixtures/pglite-snapshot.tartest/fixtures/pglite-snapshot.version- key: pglite-snapshot-${{ runner.os }}-${{ hashFiles('src/core/*.ts', 'src/core/audit/redact-connection-info.ts', 'src/core/engine-sql/bootstrap.ts', 'src/core/schema-migrations/**', 'src/core/ai/defaults.ts', 'src/core/company-brain/receipt-schema.ts', 'src/core/entities/resolve.ts', 'src/core/facts/withdrawal-schema.ts', 'src/core/facts/relink-schema.ts', 'src/core/google/*.ts', 'src/core/grants/*.ts', 'src/core/minions/tools/brain-allowlist.ts', 'src/core/ops/contract.ts', 'src/core/page-state/*schema.ts', 'src/core/persistence/*.ts', 'src/core/schema-pack/link-inference.ts', 'src/core/schema-pack/redos-guard.ts', 'src/core/search/alias-normalize.ts', 'src/core/search/private-visibility.ts', 'src/core/search/projection-statistics.ts', 'src/core/search/relational-intent.ts', 'src/core/shared-skills/*schema*.ts', 'src/core/ai/decide/schema.ts', 'test/helpers/legacy-embedding-config.ts', 'scripts/build-pglite-snapshot.ts', 'src/core/facts/purge-schema.ts', 'src/core/facts/fts-index.ts', 'src/core/eligibility/generation-schema.ts', 'src/core/trust/schema.ts', 'src/core/trust/tier.ts', 'src/core/trust/allow-rules.ts', 'src/core/write-gate-schema.ts', 'src/core/questions/schema.ts', 'src/core/questions/identity.ts', 'src/core/questions/auto-think-migration.ts', 'src/core/loops/loops-schema.ts', 'src/core/postgres-engine/schema-lock-timeout.ts') }}+ key: pglite-snapshot-${{ runner.os }}-${{ hashFiles('src/core/*.ts', 'src/core/audit/redact-connection-info.ts', 'src/core/engine-sql/bootstrap.ts', 'src/core/schema-migrations/**', 'src/core/ai/defaults.ts', 'src/core/company-brain/receipt-schema.ts', 'src/core/entities/resolve.ts', 'src/core/facts/withdrawal-schema.ts', 'src/core/facts/relink-schema.ts', 'src/core/google/*.ts', 'src/core/grants/*.ts', 'src/core/minions/tools/brain-allowlist.ts', 'src/core/ops/contract.ts', 'src/core/page-body/page-shape.ts', 'src/core/page-state/*schema.ts', 'src/core/persistence/*.ts', 'src/core/schema-pack/link-inference.ts', 'src/core/schema-pack/redos-guard.ts', 'src/core/search/alias-normalize.ts', 'src/core/search/private-visibility.ts', 'src/core/search/projection-statistics.ts', 'src/core/search/relational-intent.ts', 'src/core/shared-skills/*schema*.ts', 'src/core/ai/decide/schema.ts', 'test/helpers/legacy-embedding-config.ts', 'scripts/build-pglite-snapshot.ts', 'src/core/facts/purge-schema.ts', 'src/core/facts/fts-index.ts', 'src/core/eligibility/generation-schema.ts', 'src/core/trust/schema.ts', 'src/core/trust/tier.ts', 'src/core/trust/allow-rules.ts', 'src/core/write-gate-schema.ts', 'src/core/questions/schema.ts', 'src/core/questions/identity.ts', 'src/core/questions/auto-think-migration.ts', 'src/core/loops/loops-schema.ts', 'src/core/postgres-engine/schema-lock-timeout.ts') }}- name: Install dependencies (bounded, retried once)timeout-minutes: 8run: bun scripts/ci-bun-install.ts --frozen-lockfile@@ -514,13 +514,13 @@ jobs:path: |test/fixtures/pglite-snapshot.tartest/fixtures/pglite-snapshot.version- key: pglite-snapshot-${{ runner.os }}-${{ hashFiles('src/core/*.ts', 'src/core/audit/redact-connection-info.ts', 'src/core/engine-sql/bootstrap.ts', 'src/core/schema-migrations/**', 'src/core/ai/defaults.ts', 'src/core/company-brain/receipt-schema.ts', 'src/core/entities/resolve.ts', 'src/core/facts/withdrawal-schema.ts', 'src/core/facts/relink-schema.ts', 'src/core/google/*.ts', 'src/core/grants/*.ts', 'src/core/minions/tools/brain-allowlist.ts', 'src/core/ops/contract.ts', 'src/core/page-state/*schema.ts', 'src/core/persistence/*.ts', 'src/core/schema-pack/link-inference.ts', 'src/core/schema-pack/redos-guard.ts', 'src/core/search/alias-normalize.ts', 'src/core/search/private-visibility.ts', 'src/core/search/projection-statistics.ts', 'src/core/search/relational-intent.ts', 'src/core/shared-skills/*schema*.ts', 'src/core/ai/decide/schema.ts', 'test/helpers/legacy-embedding-config.ts', 'scripts/build-pglite-snapshot.ts', 'src/core/facts/purge-schema.ts', 'src/core/facts/fts-index.ts', 'src/core/eligibility/generation-schema.ts', 'src/core/trust/schema.ts', 'src/core/trust/tier.ts', 'src/core/trust/allow-rules.ts', 'src/core/write-gate-schema.ts', 'src/core/questions/schema.ts', 'src/core/questions/identity.ts', 'src/core/questions/auto-think-migration.ts', 'src/core/loops/loops-schema.ts', 'src/core/postgres-engine/schema-lock-timeout.ts') }}+ key: pglite-snapshot-${{ runner.os }}-${{ hashFiles('src/core/*.ts', 'src/core/audit/redact-connection-info.ts', 'src/core/engine-sql/bootstrap.ts', 'src/core/schema-migrations/**', 'src/core/ai/defaults.ts', 'src/core/company-brain/receipt-schema.ts', 'src/core/entities/resolve.ts', 'src/core/facts/withdrawal-schema.ts', 'src/core/facts/relink-schema.ts', 'src/core/google/*.ts', 'src/core/grants/*.ts', 'src/core/minions/tools/brain-allowlist.ts', 'src/core/ops/contract.ts', 'src/core/page-body/page-shape.ts', 'src/core/page-state/*schema.ts', 'src/core/persistence/*.ts', 'src/core/schema-pack/link-inference.ts', 'src/core/schema-pack/redos-guard.ts', 'src/core/search/alias-normalize.ts', 'src/core/search/private-visibility.ts', 'src/core/search/projection-statistics.ts', 'src/core/search/relational-intent.ts', 'src/core/shared-skills/*schema*.ts', 'src/core/ai/decide/schema.ts', 'test/helpers/legacy-embedding-config.ts', 'scripts/build-pglite-snapshot.ts', 'src/core/facts/purge-schema.ts', 'src/core/facts/fts-index.ts', 'src/core/eligibility/generation-schema.ts', 'src/core/trust/schema.ts', 'src/core/trust/tier.ts', 'src/core/trust/allow-rules.ts', 'src/core/write-gate-schema.ts', 'src/core/questions/schema.ts', 'src/core/questions/identity.ts', 'src/core/questions/auto-think-migration.ts', 'src/core/loops/loops-schema.ts', 'src/core/postgres-engine/schema-lock-timeout.ts') }}- uses: actions/cache/restore@5a3ec84eff668545956fd18022155c47e93e2684 # v4.2.3with:path: |test/fixtures/pglite-snapshot-default.tartest/fixtures/pglite-snapshot-default.version- key: pglite-snapshot-default-${{ runner.os }}-${{ hashFiles('src/core/*.ts', 'src/core/audit/redact-connection-info.ts', 'src/core/engine-sql/bootstrap.ts', 'src/core/schema-migrations/**', 'src/core/ai/defaults.ts', 'src/core/company-brain/receipt-schema.ts', 'src/core/entities/resolve.ts', 'src/core/facts/withdrawal-schema.ts', 'src/core/facts/relink-schema.ts', 'src/core/google/*.ts', 'src/core/grants/*.ts', 'src/core/minions/tools/brain-allowlist.ts', 'src/core/ops/contract.ts', 'src/core/page-state/*schema.ts', 'src/core/persistence/*.ts', 'src/core/schema-pack/link-inference.ts', 'src/core/schema-pack/redos-guard.ts', 'src/core/search/alias-normalize.ts', 'src/core/search/private-visibility.ts', 'src/core/search/projection-statistics.ts', 'src/core/search/relational-intent.ts', 'src/core/shared-skills/*schema*.ts', 'src/core/ai/decide/schema.ts', 'test/helpers/legacy-embedding-config.ts', 'scripts/build-pglite-snapshot.ts', 'src/core/facts/purge-schema.ts', 'src/core/facts/fts-index.ts', 'src/core/eligibility/generation-schema.ts', 'src/core/trust/schema.ts', 'src/core/trust/tier.ts', 'src/core/trust/allow-rules.ts', 'src/core/write-gate-schema.ts', 'src/core/questions/schema.ts', 'src/core/questions/identity.ts', 'src/core/questions/auto-think-migration.ts', 'src/core/loops/loops-schema.ts', 'src/core/postgres-engine/schema-lock-timeout.ts') }}+ key: pglite-snapshot-default-${{ runner.os }}-${{ hashFiles('src/core/*.ts', 'src/core/audit/redact-connection-info.ts', 'src/core/engine-sql/bootstrap.ts', 'src/core/schema-migrations/**', 'src/core/ai/defaults.ts', 'src/core/company-brain/receipt-schema.ts', 'src/core/entities/resolve.ts', 'src/core/facts/withdrawal-schema.ts', 'src/core/facts/relink-schema.ts', 'src/core/google/*.ts', 'src/core/grants/*.ts', 'src/core/minions/tools/brain-allowlist.ts', 'src/core/ops/contract.ts', 'src/core/page-body/page-shape.ts', 'src/core/page-state/*schema.ts', 'src/core/persistence/*.ts', 'src/core/schema-pack/link-inference.ts', 'src/core/schema-pack/redos-guard.ts', 'src/core/search/alias-normalize.ts', 'src/core/search/private-visibility.ts', 'src/core/search/projection-statistics.ts', 'src/core/search/relational-intent.ts', 'src/core/shared-skills/*schema*.ts', 'src/core/ai/decide/schema.ts', 'test/helpers/legacy-embedding-config.ts', 'scripts/build-pglite-snapshot.ts', 'src/core/facts/purge-schema.ts', 'src/core/facts/fts-index.ts', 'src/core/eligibility/generation-schema.ts', 'src/core/trust/schema.ts', 'src/core/trust/tier.ts', 'src/core/trust/allow-rules.ts', 'src/core/write-gate-schema.ts', 'src/core/questions/schema.ts', 'src/core/questions/identity.ts', 'src/core/questions/auto-think-migration.ts', 'src/core/loops/loops-schema.ts', 'src/core/postgres-engine/schema-lock-timeout.ts') }}- name: Install dependencies (bounded, retried once)timeout-minutes: 8run: bun scripts/ci-bun-install.ts --frozen-lockfile@@ -597,7 +597,7 @@ jobs:path: |test/fixtures/pglite-snapshot-default.tartest/fixtures/pglite-snapshot-default.version- key: pglite-snapshot-default-${{ runner.os }}-${{ hashFiles('src/core/*.ts', 'src/core/audit/redact-connection-info.ts', 'src/core/engine-sql/bootstrap.ts', 'src/core/schema-migrations/**', 'src/core/ai/defaults.ts', 'src/core/company-brain/receipt-schema.ts', 'src/core/entities/resolve.ts', 'src/core/facts/withdrawal-schema.ts', 'src/core/facts/relink-schema.ts', 'src/core/google/*.ts', 'src/core/grants/*.ts', 'src/core/minions/tools/brain-allowlist.ts', 'src/core/ops/contract.ts', 'src/core/page-state/*schema.ts', 'src/core/persistence/*.ts', 'src/core/schema-pack/link-inference.ts', 'src/core/schema-pack/redos-guard.ts', 'src/core/search/alias-normalize.ts', 'src/core/search/private-visibility.ts', 'src/core/search/projection-statistics.ts', 'src/core/search/relational-intent.ts', 'src/core/shared-skills/*schema*.ts', 'src/core/ai/decide/schema.ts', 'test/helpers/legacy-embedding-config.ts', 'scripts/build-pglite-snapshot.ts', 'src/core/facts/purge-schema.ts', 'src/core/facts/fts-index.ts', 'src/core/eligibility/generation-schema.ts', 'src/core/trust/schema.ts', 'src/core/trust/tier.ts', 'src/core/trust/allow-rules.ts', 'src/core/write-gate-schema.ts', 'src/core/questions/schema.ts', 'src/core/questions/identity.ts', 'src/core/questions/auto-think-migration.ts', 'src/core/loops/loops-schema.ts', 'src/core/postgres-engine/schema-lock-timeout.ts') }}+ key: pglite-snapshot-default-${{ runner.os }}-${{ hashFiles('src/core/*.ts', 'src/core/audit/redact-connection-info.ts', 'src/core/engine-sql/bootstrap.ts', 'src/core/schema-migrations/**', 'src/core/ai/defaults.ts', 'src/core/company-brain/receipt-schema.ts', 'src/core/entities/resolve.ts', 'src/core/facts/withdrawal-schema.ts', 'src/core/facts/relink-schema.ts', 'src/core/google/*.ts', 'src/core/grants/*.ts', 'src/core/minions/tools/brain-allowlist.ts', 'src/core/ops/contract.ts', 'src/core/page-body/page-shape.ts', 'src/core/page-state/*schema.ts', 'src/core/persistence/*.ts', 'src/core/schema-pack/link-inference.ts', 'src/core/schema-pack/redos-guard.ts', 'src/core/search/alias-normalize.ts', 'src/core/search/private-visibility.ts', 'src/core/search/projection-statistics.ts', 'src/core/search/relational-intent.ts', 'src/core/shared-skills/*schema*.ts', 'src/core/ai/decide/schema.ts', 'test/helpers/legacy-embedding-config.ts', 'scripts/build-pglite-snapshot.ts', 'src/core/facts/purge-schema.ts', 'src/core/facts/fts-index.ts', 'src/core/eligibility/generation-schema.ts', 'src/core/trust/schema.ts', 'src/core/trust/tier.ts', 'src/core/trust/allow-rules.ts', 'src/core/write-gate-schema.ts', 'src/core/questions/schema.ts', 'src/core/questions/identity.ts', 'src/core/questions/auto-think-migration.ts', 'src/core/loops/loops-schema.ts', 'src/core/postgres-engine/schema-lock-timeout.ts') }}- name: Install dependencies (bounded, retried once)timeout-minutes: 8run: bun scripts/ci-bun-install.ts --frozen-lockfile@@ -636,7 +636,7 @@ jobs:path: |test/fixtures/pglite-snapshot.tartest/fixtures/pglite-snapshot.version- key: pglite-snapshot-${{ runner.os }}-${{ hashFiles('src/core/*.ts', 'src/core/audit/redact-connection-info.ts', 'src/core/engine-sql/bootstrap.ts', 'src/core/schema-migrations/**', 'src/core/ai/defaults.ts', 'src/core/company-brain/receipt-schema.ts', 'src/core/entities/resolve.ts', 'src/core/facts/withdrawal-schema.ts', 'src/core/facts/relink-schema.ts', 'src/core/google/*.ts', 'src/core/grants/*.ts', 'src/core/minions/tools/brain-allowlist.ts', 'src/core/ops/contract.ts', 'src/core/page-state/*schema.ts', 'src/core/persistence/*.ts', 'src/core/schema-pack/link-inference.ts', 'src/core/schema-pack/redos-guard.ts', 'src/core/search/alias-normalize.ts', 'src/core/search/private-visibility.ts', 'src/core/search/projection-statistics.ts', 'src/core/search/relational-intent.ts', 'src/core/shared-skills/*schema*.ts', 'src/core/ai/decide/schema.ts', 'test/helpers/legacy-embedding-config.ts', 'scripts/build-pglite-snapshot.ts', 'src/core/facts/purge-schema.ts', 'src/core/facts/fts-index.ts', 'src/core/eligibility/generation-schema.ts', 'src/core/trust/schema.ts', 'src/core/trust/tier.ts', 'src/core/trust/allow-rules.ts', 'src/core/write-gate-schema.ts', 'src/core/questions/schema.ts', 'src/core/questions/identity.ts', 'src/core/questions/auto-think-migration.ts', 'src/core/loops/loops-schema.ts', 'src/core/postgres-engine/schema-lock-timeout.ts') }}+ key: pglite-snapshot-${{ runner.os }}-${{ hashFiles('src/core/*.ts', 'src/core/audit/redact-connection-info.ts', 'src/core/engine-sql/bootstrap.ts', 'src/core/schema-migrations/**', 'src/core/ai/defaults.ts', 'src/core/company-brain/receipt-schema.ts', 'src/core/entities/resolve.ts', 'src/core/facts/withdrawal-schema.ts', 'src/core/facts/relink-schema.ts', 'src/core/google/*.ts', 'src/core/grants/*.ts', 'src/core/minions/tools/brain-allowlist.ts', 'src/core/ops/contract.ts', 'src/core/page-body/page-shape.ts', 'src/core/page-state/*schema.ts', 'src/core/persistence/*.ts', 'src/core/schema-pack/link-inference.ts', 'src/core/schema-pack/redos-guard.ts', 'src/core/search/alias-normalize.ts', 'src/core/search/private-visibility.ts', 'src/core/search/projection-statistics.ts', 'src/core/search/relational-intent.ts', 'src/core/shared-skills/*schema*.ts', 'src/core/ai/decide/schema.ts', 'test/helpers/legacy-embedding-config.ts', 'scripts/build-pglite-snapshot.ts', 'src/core/facts/purge-schema.ts', 'src/core/facts/fts-index.ts', 'src/core/eligibility/generation-schema.ts', 'src/core/trust/schema.ts', 'src/core/trust/tier.ts', 'src/core/trust/allow-rules.ts', 'src/core/write-gate-schema.ts', 'src/core/questions/schema.ts', 'src/core/questions/identity.ts', 'src/core/questions/auto-think-migration.ts', 'src/core/loops/loops-schema.ts', 'src/core/postgres-engine/schema-lock-timeout.ts') }}- name: Install dependencies (bounded, retried once)timeout-minutes: 8run: bun scripts/ci-bun-install.ts --frozen-lockfile@@ -737,7 +737,7 @@ jobs:path: |test/fixtures/pglite-snapshot.tartest/fixtures/pglite-snapshot.version- key: pglite-snapshot-${{ runner.os }}-${{ hashFiles('src/core/*.ts', 'src/core/audit/redact-connection-info.ts', 'src/core/engine-sql/bootstrap.ts', 'src/core/schema-migrations/**', 'src/core/ai/defaults.ts', 'src/core/company-brain/receipt-schema.ts', 'src/core/entities/resolve.ts', 'src/core/facts/withdrawal-schema.ts', 'src/core/facts/relink-schema.ts', 'src/core/google/*.ts', 'src/core/grants/*.ts', 'src/core/minions/tools/brain-allowlist.ts', 'src/core/ops/contract.ts', 'src/core/page-state/*schema.ts', 'src/core/persistence/*.ts', 'src/core/schema-pack/link-inference.ts', 'src/core/schema-pack/redos-guard.ts', 'src/core/search/alias-normalize.ts', 'src/core/search/private-visibility.ts', 'src/core/search/projection-statistics.ts', 'src/core/search/relational-intent.ts', 'src/core/shared-skills/*schema*.ts', 'src/core/ai/decide/schema.ts', 'test/helpers/legacy-embedding-config.ts', 'scripts/build-pglite-snapshot.ts', 'src/core/facts/purge-schema.ts', 'src/core/facts/fts-index.ts', 'src/core/eligibility/generation-schema.ts', 'src/core/trust/schema.ts', 'src/core/trust/tier.ts', 'src/core/trust/allow-rules.ts', 'src/core/write-gate-schema.ts', 'src/core/questions/schema.ts', 'src/core/questions/identity.ts', 'src/core/questions/auto-think-migration.ts', 'src/core/loops/loops-schema.ts', 'src/core/postgres-engine/schema-lock-timeout.ts') }}+ key: pglite-snapshot-${{ runner.os }}-${{ hashFiles('src/core/*.ts', 'src/core/audit/redact-connection-info.ts', 'src/core/engine-sql/bootstrap.ts', 'src/core/schema-migrations/**', 'src/core/ai/defaults.ts', 'src/core/company-brain/receipt-schema.ts', 'src/core/entities/resolve.ts', 'src/core/facts/withdrawal-schema.ts', 'src/core/facts/relink-schema.ts', 'src/core/google/*.ts', 'src/core/grants/*.ts', 'src/core/minions/tools/brain-allowlist.ts', 'src/core/ops/contract.ts', 'src/core/page-body/page-shape.ts', 'src/core/page-state/*schema.ts', 'src/core/persistence/*.ts', 'src/core/schema-pack/link-inference.ts', 'src/core/schema-pack/redos-guard.ts', 'src/core/search/alias-normalize.ts', 'src/core/search/private-visibility.ts', 'src/core/search/projection-statistics.ts', 'src/core/search/relational-intent.ts', 'src/core/shared-skills/*schema*.ts', 'src/core/ai/decide/schema.ts', 'test/helpers/legacy-embedding-config.ts', 'scripts/build-pglite-snapshot.ts', 'src/core/facts/purge-schema.ts', 'src/core/facts/fts-index.ts', 'src/core/eligibility/generation-schema.ts', 'src/core/trust/schema.ts', 'src/core/trust/tier.ts', 'src/core/trust/allow-rules.ts', 'src/core/write-gate-schema.ts', 'src/core/questions/schema.ts', 'src/core/questions/identity.ts', 'src/core/questions/auto-think-migration.ts', 'src/core/loops/loops-schema.ts', 'src/core/postgres-engine/schema-lock-timeout.ts') }}- name: Install dependencies (bounded, retried once)timeout-minutes: 8run: bun scripts/ci-bun-install.ts --frozen-lockfilediff --git a/docs/TESTING.md b/docs/TESTING.mdindex d928201d53..48ed7026cf 100644--- a/docs/TESTING.md+++ b/docs/TESTING.md@@ -872,9 +872,7 @@ by the engines and by `migrate.ts`, so an import back up is an ESM cycle thatcan fail with a temporal-dead-zone error at module load. Take the executor as aparameter and import types from `src/core/engine.ts`; migration helpers live in`schema-migrations/helpers.ts` and the `Migration` type in-`schema-migrations/types.ts`; persistence embeds via `src/core/embedding.ts`. Fixtures:-`test/fixtures/guards/check-layering.ts/`; forms are driven in-`test/scripts/layering.test.ts`.+`schema-migrations/types.ts`; persistence embeds via `src/core/embedding.ts`.#### Write-path model guards@@ -946,8 +944,13 @@ remain. Rows only shrink. The guard fails on:- a duplicate or malformed row, or a `migrated` row with no module.When a domain moves, delete its members' rows and add its `migrated` row in-the same commit. Fixtures: `test/fixtures/guards/check-engine-sql-ratchet.ts/`;-forms are driven in `test/scripts/engine-sql-ratchet.test.ts`.+the same commit.++#### Page body readers++`bun run check:page-body-readers` (in verify): every site that reads or writes+a page body as one string has a row in `scripts/page-body-readers-baseline.tsv`+naming what it must become; rows only shrink. Rules: the script's header.#### Engine-sql dynamic SQL@@ -1015,9 +1018,7 @@ read is scoped. The guard fails on:`src/core/ops/**`, the MCP-facing surface, is always denied. Take thebranded executor from the engine façade instead.-The allowlists live in the script. Fixtures:-`test/fixtures/guards/check-engine-sql-brands.ts/`; forms are driven in-`test/scripts/engine-sql-brands.test.ts`.+The allowlists live in the script.#### Retired-phrase guarddiff --git a/docs/architecture/key-files/core-search-2.md b/docs/architecture/key-files/core-search-2.mdindex 5afe834722..c13aa79fdd 100644--- a/docs/architecture/key-files/core-search-2.md+++ b/docs/architecture/key-files/core-search-2.md@@ -66,7 +66,8 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/search/hub-dampening.ts` — `hubWeight(degree, H)` = 1 / (1 + ((max(n,1) − 1) / H)²), `'off'` → 1; `dampenBoost`, `normalizeHubDampening`. Pure; callers pass the caller-visible degree.-- `src/core/page-window/bounded-lead.ts` — leads, snippets and synopses read a bounded prefix, never the whole body: fan-out SQL selects `boundedPrefixSql(col)` (`left(col, 65536)`), `boundedRawPrefix` cuts a body at 64 KiB on a code point, and `overlaidBoundedRows` / `overlaidBoundedPrefix` replace a prefix holding a `gbrain:facts:begin` marker with the prefix of the withdrawal-overlaid body (one batched `readPageSnapshotsBatch` read; a page it no longer returns, or a failed read, gets an empty lead). `projectedLead` is that prefix through `boundedProjectedPrefix` (`document.ts`). Consumers: the exact-slug tier (`exact-lookup.ts`) and alias injection (`alias-hop.ts`) snippets, relational hydrate, the reflex pointer synopsis (`retrieval-reflex.ts` `safeSynopsis`: world-only reads take the projected prefix, the trusted entity-card widening the raw prefix through its own fence strip), the entity card's hit row and `entity names` leads, and think's anchor and window-floor rows (`think/gather.ts`: the raw overlaid prefix for the trusted local CLI, the projected prefix otherwise). Small pages render as before. Pinned by `test/bounded-lead.test.ts`.+- `src/core/page-body/page-shape.ts` — Wave B PR 1 (spec 1.5): segmented page bodies are unreachable as strings. `guardSegmentedBody` (called by `rowToPage` for a row with `body_storage = 'segmented'`, so by every snapshot and `getPage` read) replaces `compiled_truth` / `timeline` with enumerable getters and setters that throw `page_body_segmented`, so property reads, spread, `JSON.stringify`, `structuredClone` and assignment all fail loud instead of seeing an empty body. `isSegmentedPage`, `assertInlineBody(page, site)` (explicit refusal where a writer would otherwise act before a getter fires, e.g. SQL-only writers), `pageBodyBytes(page)` (`body_bytes` for segmented pages) and `pageBodySegmentedError`. `Page` stays one shape (`body_storage?`, `body_bytes?`); the static half is `scripts/check-page-body-readers.ts` with `scripts/page-body-readers-baseline.tsv` (docs/TESTING.md#page-body-readers). Pinned by `test/large-pages/segmented-body-unreachable.test.ts`.+- `src/core/page-window/bounded-lead.ts` — leads, snippets and synopses read a bounded prefix, never the whole body: fan-out SQL selects `boundedBodyPrefixSql(alias)` (`left(coalesce(alias.compiled_truth, alias.truth_lead), 65536)`: a segmented page's NULL body falls back to its stored lead; the one COALESCE of body and lead the page body reader ratchet allows by name), `boundedRawPrefix` cuts a body at 64 KiB on a code point, and `overlaidBoundedRows` / `overlaidBoundedPrefix` replace a prefix holding a `gbrain:facts:begin` marker with the prefix of the withdrawal-overlaid body (one batched `readPageSnapshotsBatch` read; a page it no longer returns, a segmented page, or a failed read, gets an empty lead). `projectedLead` is that prefix through `boundedProjectedPrefix` (`document.ts`). Consumers: the exact-slug tier (`exact-lookup.ts`) and alias injection (`alias-hop.ts`) snippets, relational hydrate, the reflex pointer synopsis (`retrieval-reflex.ts` `safeSynopsis`: world-only reads take the projected prefix, the trusted entity-card widening the raw prefix through its own fence strip), the entity card's hit row and `entity names` leads, and think's anchor and window-floor rows (`think/gather.ts`: the raw overlaid prefix for the trusted local CLI, the projected prefix otherwise). Small pages render as before. Pinned by `test/bounded-lead.test.ts`.- `src/core/page-window/document.ts` — the one read projection every remote window, outline and lead slices: `projectPageText` (fence overlay split, `sanitizeRemoteBody` + `credentialSafeProjection`, timeline after `TIMELINE_SEPARATOR`), `pageDocument` / `readPageDocument` (UTF-8 bytes + timeline byte offset, with the page's fence overlay), `chunkDocumentSpan` + `spanHoldsChunk` (a chunk's stored `projected_byte_*` span mapped into the document and verified), `boundedProjectedPrefix`, `locateChunksByStoredSpans` (byte spans to string offsets in one pass), `DEFAULT_INLINE_BODY_BYTES` (256 KB).- `src/core/page-window/window.ts` — byte/line window arithmetic on a UTF-8 buffer: windows snap to code points and line starts (`windowFrom`, `windowForLines`, `windowForBytes`, `windowAround`; a lone line longer than the window is cut on a code point as `forced_cut`), `pageOutline` (single pass: ATX headings outside code fences, or 64 KiB blocks for pages with fewer than two headings, with date ranges, paged by `from`/`limit`), and the opaque revision-bound cursor (`gpw1.`).- `src/core/search/relational-recall.ts` — the relational recall arm: `parseRelationalQuery` → seed resolution per in-scope source (federated set, scalar source, or every non-archived source for an unscoped caller; a literal `__all__` resolves no seeds, fail-closed) → `relationalFanout` → hydrate, fail-open. Seeds resolve through `resolveEntitySlugWithSource` and a `fallback_slugify` result is dropped (confidence gate D3). The entity resolver never returns meetings, so for an incoming `attended` relation (`Who attended <meeting>?`) a live `meeting` or `event` page whose title is exactly the seed phrase (case-insensitive, unique in the source) is the seed; other relations never seed from titles. Pinned by `test/relational-recall.test.ts`, `test/relational-recall-scope-sources.test.ts` and `test/pack-relation-direction-engine.test.ts`. With `planner` on (`search.relational_planner`, on in balanced/tokenmax), a 2-3 relationship question (`parseRelationalPlan`) runs `runRelationalChain` first: answers then evidence pages, each with a `relational` field; nothing found → the one-hop path; refused → no arm (`meta.plan`). With `orientOneHop` (`search.relational_orient_onehop`, off in every bundle) typed one-hop walks add neighbors reached through links written on the other page. `answerRows` limits the pin and evidence slot to answers. Hydrate selects a bounded body prefix and shows its synopsis through `page-window/bounded-lead.ts`. Pinned by `test/relational-recall.test.ts`.diff --git a/docs/guides/error-codes.md b/docs/guides/error-codes.mdindex 477ccaf0e6..6eb6084c69 100644--- a/docs/guides/error-codes.md+++ b/docs/guides/error-codes.md@@ -2138,6 +2138,16 @@ Reasons: `host_mismatch`, `transfer_in_progress`, `clone_in_progress`, `binding_More: [docs/guides/troubleshooting.md#owner-unavailable](../../docs/guides/troubleshooting.md#owner-unavailable)+### page_body_segmented++<a id="page_body_segmented"></a>++| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |+|---|---|---|---|---|---|---|+| This page's body is stored in segments, and the path that hit it reads or writes the whole body as one string, so it stopped before reading or changing anything. | With pages.segmented_storage on, a page over 1 MiB keeps its body in segments instead of the page row; a whole-body path would otherwise see an empty body and could overwrite the page or drop the unread rest. Windowed reads and segment-aware writers replace these paths. | Read the page's revision and stored size with get_page body: 'none' (size.body_bytes); windowed reads of a segmented body arrive with the segment reader. Run: gbrain get --source '{source_id}' --body none -- '{slug}' | agent | `repeat the read that failed` | 1 | no |++More: [docs/guides/windowed-reads.md#page_body_segmented](../../docs/guides/windowed-reads.md#page_body_segmented)+### page_identity_changed<a id="page_identity_changed"></a>diff --git a/docs/guides/windowed-reads.md b/docs/guides/windowed-reads.mdindex 2c9c8a29bc..318ffa8272 100644--- a/docs/guides/windowed-reads.md+++ b/docs/guides/windowed-reads.md@@ -90,6 +90,18 @@ cap. Nothing was returned or cut. Read `body: "outline"`, then windows; edit wit`edit_page` using the revision from `body: "none"`. An older gbrain CLI gets thisrefusal instead of a partial page: upgrade it (`gbrain upgrade`).+## page_body_segmented++The page's body is stored in segments (pages over 1 MiB with+`pages.segmented_storage` on), and the command or tool that hit it reads or+writes the whole body as one string. It stopped before reading or changing+anything, so the page is intact. Read the page's revision and stored size with+`get_page` `body: "none"` (`gbrain get --body none <slug>`; the size is+`size.body_bytes`); windowed reads of a segmented body arrive with the segment+reader. Queue work (fact reconcile, link and mention passes, effect scans)+skips a segmented page with this code as its logged reason instead of+stopping.+## page_shrink_refusedA remote `put_page` would replace a page over the inline size with content underdiff --git a/package.json b/package.jsonindex 1baa3b87ef..c000e36285 100644--- a/package.json+++ b/package.json@@ -158,6 +158,7 @@"check:durable-flush": "bun scripts/check-durable-flush.ts","check:windows-hide": "bun scripts/check-windows-hide.ts","check:engine-sql-ratchet": "bun scripts/check-engine-sql-ratchet.ts",+ "check:page-body-readers": "bun scripts/check-page-body-readers.ts","check:engine-sql-dynamic": "bun scripts/check-engine-sql-dynamic.ts","check:engine-sql-brands": "bun scripts/check-engine-sql-brands.ts","check:sync-run-state": "bun scripts/check-sync-run-state.ts",diff --git a/scripts/check-page-body-readers.ts b/scripts/check-page-body-readers.tsnew file mode 100644index 0000000000..630e30a4bc--- /dev/null+++ b/scripts/check-page-body-readers.ts@@ -0,0 +1,234 @@+#!/usr/bin/env bun+/**+ * Page body reader ratchet (Wave B segmented storage, spec 1.5 layer 4;+ * docs/TESTING.md#page-body-readers).+ *+ * A segmented page keeps its body in segments: `pages.compiled_truth` and+ * `pages.timeline` are NULL, and `rowToPage` / the snapshot readers give the+ * page object getters that throw `page_body_segmented`. `Page` stays one+ * TypeScript shape, so the type checker does not stop a new whole-body+ * reader; those getters (runtime) and this ratchet (static) do. Every site+ * that reads or writes a body as one string is listed with what it must+ * become, and the list only shrinks.+ *+ * Parses src/**\/*.ts (generated files excluded) with the TypeScript compiler+ * API and names units like the engine-sql ratchet: top-level functions and+ * variables by name, class members as `Class.member`, any other top-level+ * statement as `<module>`. A unit hits:+ *+ * field `.compiled_truth` / `.timeline` property access, the+ * same names in an element access or a destructuring+ * sql a string literal naming a body column (`x.compiled_truth`,+ * a bare `compiled_truth` / `timeline` column in SQL text,+ * quoted values like `chunk_source = 'timeline'` excluded)+ * or projecting `*` / `p.*` from `pages`+ * call:<name> a call to serializePageToMarkdown, serializeMarkdown,+ * contentHash, prepareMarkdownChunks, pageDocument,+ * refreshPageBody or putPage+ *+ * `boundedBodyPrefixSql` (page-window/bounded-lead.ts), the one sanctioned+ * COALESCE of the body and its lead, is allowed by name.+ *+ * Baseline: scripts/page-body-readers-baseline.tsv, rows+ * `path<TAB>unit<TAB>kind<TAB>action<TAB>note`. Action codes: STREAM (moves to+ * the segment reader), LEAD (a bounded prefix by design), META (size or hash+ * only: body_bytes / content_hash), SEGW (a writer that must go through the+ * segment writer; until then it refuses a segmented page), INLINE (the page+ * is inline by construction; asserts it), NONE (the name is not the page body;+ * the note says why). The note records how the site treats a segmented page+ * today.+ *+ * Rules (every violation is reported, then one exit):+ * 1. a hit with no row -> FAIL (new reader)+ * 2. a row with no hit -> FAIL (stale; rows only shrink)+ * 3. a duplicate row -> FAIL+ * 4. a malformed row, an unknown action, or NONE without a note -> FAIL+ *+ * `--prune` rewrites the file without stale and duplicate rows; nothing ever+ * adds rows.+ *+ * Seam: GBRAIN_GUARD_ROOT (fixture tree root; baseline read from+ * <root>/scripts/page-body-readers-baseline.tsv).+ */+import { existsSync, readdirSync, readFileSync, statSync, writeFileSync } from 'node:fs';+import { join, relative } from 'node:path';+import ts from 'typescript';+import { isSqlText } from './check-engine-sql-ratchet.ts';++const ROOT = process.env.GBRAIN_GUARD_ROOT ?? join(import.meta.dir, '..');+const BASELINE_REL = 'scripts/page-body-readers-baseline.tsv';+const ANCHOR = 'docs/TESTING.md#page-body-readers';+const BODY_FIELDS = new Set(['compiled_truth', 'timeline']);+const BODY_CALLS = new Set(['serializePageToMarkdown', 'serializeMarkdown', 'contentHash', 'prepareMarkdownChunks', 'pageDocument',+ 'refreshPageBody', 'putPage']);+const ALLOWED_UNITS = new Set(['boundedBodyPrefixSql']);+export const ACTIONS = new Set(['STREAM', 'LEAD', 'META', 'SEGW', 'INLINE', 'NONE']);++const QUALIFIED_COLUMN = /\.(?:compiled_truth|timeline)\b/;+const BARE_COLUMN = /(?<![\w'".])(?:compiled_truth|timeline)(?![\w'"])/;+const SELECT_STAR_FROM_PAGES = /\bselect\s+(?:distinct\s+)?\*\s+from\s+pages\b/i;+const RETURNING_STAR_FROM_PAGES = /\b(?:update|into)\s+pages\b[\s\S]*\breturning\s+\*/i;+const ALIAS_STAR = /\b([a-z_]\w*)\.\*/gi;++function aliasesPages(text: string, alias: string): boolean {+ // nosemgrep: javascript.lang.security.audit.detect-non-literal-regexp.detect-non-literal-regexp -- alias is a \w+ identifier captured by ALIAS_STAR+ return alias === 'pages' || new RegExp(`\\bpages\\s+(?:as\\s+)?${alias}\\b`, 'i').test(text);+}++/** True when literal text names a body column or projects every column of `pages` (`*`, `p.*`, `RETURNING *`). */+export function namesBodyColumn(text: string): boolean {+ if (QUALIFIED_COLUMN.test(text)) return true;+ if (!isSqlText(text)) return false;+ if (BARE_COLUMN.test(text) || SELECT_STAR_FROM_PAGES.test(text) || RETURNING_STAR_FROM_PAGES.test(text)) return true;+ return [...text.matchAll(ALIAS_STAR)].some((m) => aliasesPages(text, m[1]));+}++function literalText(node: ts.Node): string | null {+ if (ts.isStringLiteral(node) || ts.isNoSubstitutionTemplateLiteral(node)) return node.text;+ if (ts.isTemplateExpression(node)) return node.head.text + node.templateSpans.map((s) => ` _sub_ ${s.literal.text}`).join('');+ return null;+}++function calleeName(call: ts.CallExpression): string | null {+ const callee = call.expression;+ if (ts.isIdentifier(callee)) return callee.text;+ if (ts.isPropertyAccessExpression(callee)) return callee.name.text;+ return null;+}++export interface Hit { path: string; unit: string; kind: string; line: number }++function hitsIn(body: ts.Node, sf: ts.SourceFile, path: string, unit: string, out: Map<string, Hit>): void {+ const add = (kind: string, node: ts.Node) => {+ const key = `${path}\t${unit}\t${kind}`;+ if (!out.has(key)) out.set(key, { path, unit, kind, line: sf.getLineAndCharacterOfPosition(node.getStart(sf)).line + 1 });+ };+ const allowed = ALLOWED_UNITS.has(unit);+ const visit = (n: ts.Node): void => {+ if (ts.isPropertyAccessExpression(n) && BODY_FIELDS.has(n.name.text)) add('field', n);+ else if (ts.isElementAccessExpression(n) && ts.isStringLiteralLike(n.argumentExpression) && BODY_FIELDS.has(n.argumentExpression.text)) add('field', n);+ else if (ts.isBindingElement(n) && ts.isObjectBindingPattern(n.parent)) {+ const name = n.propertyName ?? n.name;+ if ((ts.isIdentifier(name) || ts.isStringLiteral(name)) && BODY_FIELDS.has(name.text)) add('field', n);+ } else if (ts.isCallExpression(n)) {+ const name = calleeName(n);+ if (name && BODY_CALLS.has(name)) add(`call:${name}`, n);+ }+ const text = literalText(n);+ if (text !== null && !allowed && namesBodyColumn(text)) add('sql', n);+ ts.forEachChild(n, visit);+ };+ visit(body);+}++function memberName(member: ts.ClassElement, sf: ts.SourceFile): string {+ if (ts.isConstructorDeclaration(member)) return 'constructor';+ if (ts.isClassStaticBlockDeclaration(member)) return 'static';+ const name = member.name;+ if (!name) return '<anonymous>';+ if (ts.isIdentifier(name) || ts.isPrivateIdentifier(name) || ts.isStringLiteral(name) || ts.isNumericLiteral(name)) return name.text;+ return name.getText(sf);+}++export function scanFile(abs: string, rel: string): Hit[] {+ const sf = ts.createSourceFile(abs, readFileSync(abs, 'utf8'), ts.ScriptTarget.Latest, true, ts.ScriptKind.TS);+ const out = new Map<string, Hit>();+ for (const stmt of sf.statements) {+ if (ts.isInterfaceDeclaration(stmt) || ts.isTypeAliasDeclaration(stmt) || ts.isImportDeclaration(stmt)) continue;+ if (ts.isFunctionDeclaration(stmt) && stmt.name) hitsIn(stmt, sf, rel, stmt.name.text, out);+ else if (ts.isVariableStatement(stmt)) {+ for (const decl of stmt.declarationList.declarations) hitsIn(decl, sf, rel, ts.isIdentifier(decl.name) ? decl.name.text : '<module>', out);+ } else if (ts.isClassDeclaration(stmt) && stmt.name) {+ for (const member of stmt.members) hitsIn(member, sf, rel, `${stmt.name.text}.${memberName(member, sf)}`, out);+ } else hitsIn(stmt, sf, rel, '<module>', out);+ }+ return [...out.values()];+}++function tsFiles(dir: string): string[] {+ if (!existsSync(dir)) return [];+ const out: string[] = [];+ for (const entry of readdirSync(dir).sort()) {+ const full = join(dir, entry);+ if (statSync(full).isDirectory()) out.push(...tsFiles(full));+ else if (entry.endsWith('.ts') && !entry.endsWith('.d.ts') && !entry.includes('.generated.')) out.push(full);+ }+ return out;+}++export function scanTree(root: string): Hit[] {+ return tsFiles(join(root, 'src')).flatMap((abs) => scanFile(abs, relative(root, abs).replace(/\\/g, '/')));+}++interface Row { lineNo: number; raw: string; key: string | null; problem: string | null }++function parseBaseline(text: string): Row[] {+ const rows: Row[] = [];+ text.split('\n').forEach((raw, i) => {+ if (raw.trim() === '' || raw.startsWith('#')) return;+ const [path, unit, kind, action, note, ...extra] = raw.split('\t');+ const problem = !path || !unit || !kind || !action || extra.length ? "use 'path<TAB>unit<TAB>kind<TAB>action<TAB>note'"+ : !ACTIONS.has(action) ? `unknown action '${action}' (one of ${[...ACTIONS].join(', ')})`+ : action === 'NONE' && !note?.trim() ? 'a NONE row needs a note saying why the name is not the page body'+ : null;+ rows.push({ lineNo: i + 1, raw, key: problem ? null : `${path}\t${unit}\t${kind}`, problem });+ });+ return rows;+}++if (import.meta.main) {+ const prune = process.argv.includes('--prune');+ const baselinePath = join(ROOT, BASELINE_REL);+ if (!existsSync(baselinePath)) {+ console.error(`FAIL: ${BASELINE_REL}:1 baseline file missing`);+ console.error('Why: the ratchet compares page body readers against the committed baseline.');+ console.error(`Fix: git checkout ${BASELINE_REL}`);+ console.error(`See: ${ANCHOR}`);+ process.exit(1);+ }+ const baselineText = readFileSync(baselinePath, 'utf8');+ const rows = parseBaseline(baselineText);+ const hits = new Map(scanTree(ROOT).map((h) => [`${h.path}\t${h.unit}\t${h.kind}`, h]));+ const violations: string[] = [];+ const stale = new Set<number>();+ const listed = new Set<string>();++ for (const row of rows) {+ const where = `${BASELINE_REL}:${row.lineNo}`;+ if (row.problem || !row.key) {+ violations.push(`FAIL: ${where} malformed row '${row.raw.replace(/\t/g, ' ')}'\n Fix: ${row.problem}`);+ continue;+ }+ if (listed.has(row.key)) {+ stale.add(row.lineNo);+ violations.push(`FAIL: ${where} duplicate row '${row.key.replace(/\t/g, ' ')}'\n Fix: delete this line (or: bun scripts/check-page-body-readers.ts --prune)`);+ continue;+ }+ listed.add(row.key);+ if (!hits.has(row.key)) {+ stale.add(row.lineNo);+ violations.push(`FAIL: ${where} stale row: ${row.key.replace(/\t/g, ' ')} no longer reads the body\n Fix: delete this line; rows only shrink (or: bun scripts/check-page-body-readers.ts --prune)`);+ }+ }++ for (const [key, hit] of hits) {+ if (listed.has(key)) continue;+ violations.push(`FAIL: ${hit.path}:${hit.line} new page body reader in ${hit.unit} (${hit.kind})\n Fix: read size and identity from body_bytes / content_hash (pageBodyBytes) or a bounded prefix from boundedBodyPrefixSql; a whole-body reader that has to stay (refusing a segmented page with assertInlineBody, or waiting for the segment reader) needs a reviewed row in ${BASELINE_REL} with its action code`);+ }++ if (prune) {+ const kept = baselineText.split('\n').filter((_line, i) => !stale.has(i + 1));+ writeFileSync(baselinePath, kept.join('\n'));+ console.log(`check-page-body-readers: pruned ${stale.size} row(s) from ${BASELINE_REL}`);+ process.exit(0);+ }++ if (violations.length) {+ for (const v of violations) console.error(v);+ console.error('Why: a segmented page has no body string; a whole-body reader would see nothing or throw page_body_segmented. Readers only shrink.');+ console.error(`See: ${ANCHOR}`);+ console.error(`check-page-body-readers: ${violations.length} violation(s)`);+ process.exit(1);+ }+ console.log(`check-page-body-readers: ok (${listed.size} baseline rows)`);+}diff --git a/scripts/guards-manifest.tsv b/scripts/guards-manifest.tsvindex dddac25f35..08da2f64ac 100644--- a/scripts/guards-manifest.tsv+++ b/scripts/guards-manifest.tsv@@ -65,6 +65,7 @@ check-grok-pin.sh repostate exempt pin-stamp drift check (GROK-CLI-PIN.md stampscheck-module-size.sh scanner yes committed per-file line ceilings (module-size-limits.tsv); growth + stale-ceiling + missing-row + new-file capcheck-function-size.ts scanner yes W5 per-function line ratchet (TS compiler API): new >300-line function, growth, shrink-below-limit, stale slack, missing row, raise without issue/TODO id; baseline scripts/function-size-baseline.tsv keyed by path + name path; --transfer for verified move-only commitscheck-engine-sql-ratchet.ts scanner yes goal (a) engine-sql ratchet (TS AST): SQL-bearing engine members (façade classes + pglite-engine/ and postgres-engine/ modules) need a baseline row or an engine-sql-ok marker; stale/duplicate rows and unbacked migrated domains fail; baseline scripts/engine-sql-baseline.tsv; --prune drops stale rows only+check-page-body-readers.ts scanner yes Wave B segmented storage (spec 1.5 layer 4, TS AST): src units reading .compiled_truth/.timeline, SQL literals naming the body columns or p.* from pages, and whole-body calls (serializePageToMarkdown, putPage, ...) need a baseline row with an action code; stale/duplicate/malformed rows fail; boundedBodyPrefixSql allowed by name; baseline scripts/page-body-readers-baseline.tsv; --prune drops stale rows onlycheck-engine-sql-dynamic.ts scanner yes CQ3/EO17 dynamic SQL in src/core/engine-sql/** (TS AST; fragment.ts exempt as the renderer): trustedSql args and composed .query/.unsafe/.executeRaw/executeRawJsonb SQL splice only literals, as-const/allowlisted constants, VETTED_BUILDERS calls or Number.isFinite-checked numbers; no $<digit> in composed strings; no expanded IN listscheck-engine-sql-brands.ts scanner yes EO4/AR2 RLS read brands (TS AST + text): brand-key mentions outside engine-sql/brands.ts; casts onto ScopedRead/LegacyUnscopedRead or `as unknown as` executor types in src/; unscopedExecutor/LegacyUnscopedRead/scopedRead imports outside their allowlists, src/core/ops/** always deniedcheck-sync-run-state.ts scanner yes A17 (W4 sync): SyncRun mutable fields (non-readonly members of interface SyncRun) are never destructured or aliased into locals under src/commands/sync/; @checkpoint fields are assigned only in sync-run.ts (single owner); fixtures cover destructuring, aliasing, a parameter pattern in a nested dir, and an out-of-owner checkpoint writediff --git a/scripts/page-body-readers-baseline.tsv b/scripts/page-body-readers-baseline.tsvnew file mode 100644index 0000000000..0e711de632--- /dev/null+++ b/scripts/page-body-readers-baseline.tsv@@ -0,0 +1,521 @@+# Page body reader ratchet baseline (Wave B segmented storage, spec 1.5 layer 4).+# Enforced by scripts/check-page-body-readers.ts via `bun run check:page-body-readers` (in verify).+# Rows: path<TAB>unit<TAB>kind<TAB>action<TAB>note+# kind field | sql | call:<name>+# action STREAM | LEAD | META | SEGW | INLINE | NONE (see the script's header)+# note how the site treats a segmented page today (throw, refuse, logged+# skip, SQL exclusion); empty when the site relies on the throwing+# getters alone and was not changed in PR 1. NONE needs a note.+# Rows only shrink: when a site moves to the segment reader or writer, delete+# its row (`bun scripts/check-page-body-readers.ts --prune` drops stale rows).+# A new whole-body reader never gets a row: use the segment reader, a bounded+# lead (boundedBodyPrefixSql), body_bytes or content_hash instead.+# docs/TESTING.md#page-body-readers+src/cli/main.ts formatResult field STREAM renders a get_page result body; segmented bodies stream in PR 2+src/cli/page-render.ts formatGetPage call:serializeMarkdown SEGW+src/cli/page-render.ts formatGetPage field STREAM+src/commands/brainstorm.ts runBrainstormCli call:serializeMarkdown SEGW+src/commands/core.ts runCore field INLINE+src/commands/core.ts setMarking call:serializePageToMarkdown INLINE+src/commands/core.ts suggestCandidates field INLINE+src/commands/core.ts suggestCandidates sql INLINE+src/commands/doctor/checks/calibration.ts checkLinkResolutionOpportunity field LEAD+src/commands/doctor/checks/calibration.ts checkLinkResolutionOpportunity sql LEAD+src/commands/doctor/checks/content-quality.ts runContentSanity sql META+src/commands/doctor/checks/data-integrity.ts runMarkdownBody sql META+src/commands/doctor/checks/derived-visibility.ts derivedVisibilityCheck sql NONE not the page body: p.* in a CTE, only metadata columns read+src/commands/doctor/checks/graph-health.ts runGraphCoverage field NONE not the page body: timeline count alias+src/commands/doctor/checks/graph-health.ts runGraphCoverage sql NONE not the page body: timeline coverage count alias+src/commands/enrich.ts enrichOneLocked call:serializeMarkdown SEGW+src/commands/enrich.ts enrichOneLocked field SEGW+src/commands/export.ts runExport call:serializeMarkdown SEGW+src/commands/export.ts runExport field STREAM+src/commands/export.ts runExport sql STREAM+src/commands/extract-conversation-facts.ts regularPageVersionToken field STREAM+src/commands/extract-mentions-explain.ts explainMention field STREAM+src/commands/extract-mentions-explain.ts explainMention sql STREAM+src/commands/extract-mentions-explain.ts pageNames sql STREAM+src/commands/extract-mentions-explain.ts rejectedDeclaration sql STREAM+src/commands/extract-timeline-db.ts extractTimelineFromDB field STREAM+src/commands/extract-timeline-db.ts plannedTimeline field STREAM+src/commands/extract.ts extractFromDB field STREAM+src/commands/extract.ts extractLinksFromDB field STREAM+src/commands/extract.ts extractMentionsFromDb field STREAM+src/commands/extract.ts extractStaleFromDB field STREAM+src/commands/extract.ts runExtractCore field STREAM+src/commands/integrity.ts cmdAuto field STREAM+src/commands/integrity.ts scanIntegrity field STREAM+src/commands/integrity.ts scanIntegrityBatch field STREAM+src/commands/integrity.ts scanIntegrityBatch sql STREAM+src/commands/jobs.ts JOBS_HELP sql NONE not the page body: help text+src/commands/lint.ts lintContent field STREAM+src/commands/migrate-engine.ts copyPageToTarget call:putPage SEGW+src/commands/migrate-engine.ts copyPageToTarget field STREAM+src/commands/migrations/v0_32_2.ts phaseCVerify call:serializePageToMarkdown SEGW+src/commands/quarantine.ts runClear call:serializeMarkdown SEGW+src/commands/quarantine.ts runClear field SEGW+src/commands/quarantine.ts runScan call:serializePageToMarkdown SEGW+src/commands/quarantine.ts runScan field SEGW+src/commands/reconcile-links.ts runReconcileLinks field STREAM+src/commands/reindex-aliases.ts runReindexAliases field STREAM+src/commands/reindex-code.ts estimateReindexCost field INLINE+src/commands/reindex-code.ts fetchCodePages sql INLINE+src/commands/reindex-code.ts runReindexCode field INLINE+src/commands/reindex.ts readBatch sql STREAM+src/commands/reindex.ts runReindex call:serializeMarkdown SEGW+src/commands/reindex.ts runReindex field STREAM+src/commands/sources.ts runAudit field SEGW+src/commands/sync/finalize.ts backstopAffectedPageFacts field STREAM+src/core/ai/decide/review-lane.ts pagePairAnchor field LEAD bounded prefix row+src/core/ai/decide/review-lane.ts pagePairAnchor sql LEAD boundedBodyPrefixSql (truth_lead for segmented), sliced to PAGE_TEXT_LIMIT+src/core/attendance-repair.ts prepareOrigin field META+src/core/attendance-repair.ts readOrigin sql META+src/core/brainstorm/domain-bank.ts fetchFar field LEAD+src/core/brainstorm/orchestrator.ts _runBrainstormInner field LEAD+src/core/by-mention.ts scanStaleMentions sql STREAM+src/core/chronicle/backfill.ts runChronicleBackfill field STREAM+src/core/chronicle/backfill.ts runChronicleBackfill sql STREAM+src/core/chronicle/execute.ts executeChronicleRow field LEAD+src/core/chronicle/extract-events.ts chronicleJudgeContext field LEAD+src/core/chronicle/ledger.ts decideChronicle field LEAD+src/core/chronicle/publish.ts publishChronicleGeneration call:putPage INLINE+src/core/chronicle/publish.ts publishChronicleGeneration call:serializeMarkdown INLINE+src/core/code-chunks.ts prepareCodeChunks field INLINE+src/core/company-brain/inspection.ts readPage field STREAM+src/core/company-brain/profile.ts importCompanyBrainFile field META+src/core/company-brain/verification.ts verifyCompanyBrain field STREAM+src/core/content-repair/judgment.ts judgmentParticipant field STREAM+src/core/content-sanity.ts assessContentSanity field STREAM+src/core/context/compile-view.ts compileView field LEAD+src/core/context/compile-view.ts renderEntry field LEAD+src/core/context/retrieval-reflex.ts resolveEntitiesToPointers sql LEAD boundedBodyPrefixSql AS compiled_truth+src/core/context/retrieval-reflex.ts safeSynopsis field LEAD bounded prefix rows+src/core/context/retrieval-reflex.ts weakTitleHits sql LEAD boundedBodyPrefixSql AS compiled_truth+src/core/conversation-parser/body.ts readSummaryBody field STREAM+src/core/core-memory.ts applyCoreSensitivity field INLINE+src/core/core-memory.ts listCorePages field INLINE+src/core/core-memory.ts listCorePages sql INLINE+src/core/core-memory.ts renderCorePage field INLINE+src/core/cycle/chronicle.ts discover sql STREAM+src/core/cycle/concept-publication.ts composeConceptRepublication call:serializeMarkdown INLINE+src/core/cycle/concept-publication.ts composeConceptRepublication field INLINE+src/core/cycle/concept-publication.ts conceptPreservationHold field INLINE+src/core/cycle/concept-publication.ts fileHoldsPage field INLINE+src/core/cycle/concept-publication.ts preserveCanonicalFences call:serializeMarkdown INLINE after assertInlineBody+src/core/cycle/concept-publication.ts preserveCanonicalFences field INLINE assertInlineBody: refuses a segmented page (concept pages inline; enrich/connector callers SEGW)+src/core/cycle/concept-publication.ts publishClassicConcept call:serializeMarkdown INLINE+src/core/cycle/concept-publication.ts publishClassicConcept field INLINE+src/core/cycle/concept-publication.ts publishManagedConcept call:serializeMarkdown INLINE+src/core/cycle/dream-taint.ts putDerivedPage call:putPage SEGW+src/core/cycle/drift.ts runPhaseDrift call:putPage INLINE+src/core/cycle/drift.ts runPhaseDrift call:serializeMarkdown INLINE+src/core/cycle/edge-contradictions.ts removeTimelineLine call:serializeMarkdown SEGW+src/core/cycle/edge-contradictions.ts removeTimelineLine field SEGW+src/core/cycle/extract-atoms-page-state.ts transferLegacyAtomPageState field META compares two snapshots; segmented page: getter throws page_body_segmented+src/core/cycle/extract-atoms.ts discoverExtractablePages field STREAM see sql row; CAS is on content_hash + knowledge_revision+src/core/cycle/extract-atoms.ts discoverExtractablePages sql STREAM minCompiledTruthChars is false for NULL: segmented pages are never discovered (skip until per-segment extraction, PR 4)+src/core/cycle/extract-atoms.ts minCompiledTruthChars sql STREAM false for a segmented page (NULL body): skip+src/core/cycle/extract-atoms.ts runPhaseExtractAtoms call:serializeMarkdown SEGW+src/core/cycle/extract-facts.ts canonicalCacheState field STREAM segmented page: getter throws page_body_segmented+src/core/cycle/extract-facts.ts planFenceReconcile field STREAM managed preparer: segmented page: getter throws page_body_segmented before any write+src/core/cycle/extract-facts.ts runExtractFacts field STREAM segmented page skipped with warning FACTS_RECONCILE_SEGMENTED; its facts index is preserved (per-segment reconcile, PR 4)+src/core/cycle/extract-takes.ts extractTakesFromDb field STREAM+src/core/cycle/extract-takes.ts plannedTakes field STREAM+src/core/cycle/extract-takes.ts prepareTakesReextract sql STREAM+src/core/cycle/extract-takes.ts reconcilePageTakes field STREAM+src/core/cycle/extract-takes.ts reextractCoordinated field STREAM+src/core/cycle/extract-takes.ts reextractCoordinated sql STREAM+src/core/cycle/grade-takes.ts GradeTakesPhase.process field STREAM+src/core/cycle/link-manifest.ts buildLinkManifest field STREAM+src/core/cycle/pattern-claim-sources.ts dedupePatternClaimSources call:serializePageToMarkdown SEGW+src/core/cycle/patterns.ts gatherReflections field LEAD bounded prefix row+src/core/cycle/patterns.ts gatherReflections sql LEAD boundedBodyPrefixSql, truncated to a 600-byte excerpt+src/core/cycle/patterns.ts groundPatternPages call:serializePageToMarkdown SEGW+src/core/cycle/patterns.ts groundPatternPages field LEAD+src/core/cycle/patterns.ts groundPatternPages sql LEAD+src/core/cycle/patterns.ts renderPageToMarkdown call:serializeMarkdown SEGW+src/core/cycle/patterns.ts renderPageToMarkdown field LEAD+src/core/cycle/phantom-redirect-managed.ts redirectManagedPhantom call:serializePageToMarkdown SEGW spread of a segmented page throws+src/core/cycle/phantom-redirect-managed.ts redirectManagedPhantom field SEGW segmented page: getter throws page_body_segmented in preparation (nothing written)+src/core/cycle/phantom-redirect.ts fenceDbDrift field SEGW segmented page: getter throws page_body_segmented+src/core/cycle/phantom-redirect.ts materializeCanonicalToDisk call:serializeMarkdown SEGW canonical asserted inline by the caller+src/core/cycle/phantom-redirect.ts materializeCanonicalToDisk field SEGW canonical asserted inline by the caller+src/core/cycle/phantom-redirect.ts phantomHasResidue field SEGW phantom stubs are small; segmented page: getter throws page_body_segmented+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/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+src/core/cycle/synthesize-postprocess.ts postprocessManagedSynthesis field INLINE+src/core/cycle/synthesize-postprocess.ts sameBody field INLINE+src/core/cycle/synthesize-verify-epochs.ts loadPreRunRevision field STREAM+src/core/cycle/synthesize-verify-epochs.ts loadPreRunRevision sql STREAM+src/core/cycle/synthesize-verify.ts quarantineUnits field INLINE+src/core/cycle/synthesize-verify.ts verifyAndRepairDreamPages call:serializePageToMarkdown INLINE+src/core/cycle/synthesize-verify.ts verifyAndRepairDreamPages field INLINE+src/core/cycle/synthesize-verify.ts verifyDreamPage field INLINE+src/core/cycle/synthesize.ts renderPageToMarkdown call:serializePageToMarkdown INLINE+src/core/cycle/synthesize.ts reverseWriteRefs call:serializePageToMarkdown INLINE+src/core/cycle/synthesize.ts writeSummaryPage call:serializeMarkdown INLINE+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/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+src/core/embedding-readiness.ts countArchivedEmbeddingWork sql META+src/core/engine-sql/chunks.ts chunklessPagesWhere sql META lane 1e file: body <> '' predicate+src/core/engine-sql/chunks.ts getChunkWindows sql STREAM lane 1e file: ships whole bodies per hit; NULL for segmented (chunk windows by stored spans in PR 2)+src/core/engine-sql/chunks.ts listChunklessPagesWithContent field STREAM lane 1e file+src/core/engine-sql/chunks.ts listChunklessPagesWithContent sql STREAM lane 1e file+src/core/engine-sql/chunks.ts listEmbeddingStateRows sql META lane 1e file: octet_length metadata+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 and refuses a whole-body put over it with page_body_segmented+src/core/engine-sql/pages.ts refreshPageBody sql SEGW UPDATE of the body columns; the body-storage CHECK refuses it over a segmented row; callers assert first+src/core/engine-sql/pages.ts revertToVersion sql SEGW lane 1e: refuses a segmented page/version (revert deferred to PR 3)+src/core/engine-sql/pages.ts toDomainBankRow field LEAD maps sampled rows; segmented pages are never sampled+src/core/engine-sql/salience.ts listEnrichCandidates sql META+src/core/engine-sql/timeline.ts getTimeline sql NONE not the page body: SELECT * FROM pages inside a LATERAL used for the page id only+src/core/enrichment-service.ts enrichEntity call:putPage INLINE+src/core/enrichment-service.ts enrichEntity call:serializeMarkdown INLINE+src/core/export-snapshot.ts readExportPage field STREAM+src/core/export-snapshot.ts readExportPage sql STREAM+src/core/extract-ner.ts extractNerLinks field STREAM+src/core/extract-takes-from-pages.ts extractTakesFromPages call:serializePageToMarkdown SEGW+src/core/extract-takes-from-pages.ts extractTakesFromPages field STREAM inline rows only (SQL filter)+src/core/extract-takes-from-pages.ts extractTakesFromPages sql STREAM length(COALESCE(compiled_truth, '')) > 200 skips segmented pages; head-only slice(0, 20000) for inline+src/core/extract-timeline-from-meetings.ts extractTimelineFromMeetings field STREAM+src/core/extract-timeline-from-meetings.ts extractTimelineFromMeetings sql STREAM+src/core/extract/receipt-writer.ts writeReceipt call:putPage INLINE+src/core/facts/backstop.ts runFactsBackstop field STREAM+src/core/facts/backstop.ts runPipeline field STREAM+src/core/facts/drain.ts estimateBacklogUsd sql META+src/core/facts/eligibility.ts isFactsBackstopEligible field LEAD+src/core/facts/fence-write.ts writeFactsToFence call:contentHash META+src/core/facts/fence-write.ts writeFactsToFence call:refreshPageBody SEGW+src/core/facts/fence-write.ts writeFactsToFence field SEGW+src/core/facts/forget.ts forgetFactInFence call:contentHash META inline pages only+src/core/facts/forget.ts forgetFactInFence call:refreshPageBody SEGW assertInlineBody first+src/core/facts/forget.ts forgetFactInFence field SEGW assertInlineBody before the DB strike/mirror (best-effort: the withdrawal record stays authoritative)+src/core/facts/proposal-supersede.ts acceptUnmanaged field SEGW mirrorBody refuses a segmented page before the file publish+src/core/facts/proposal-supersede.ts mirrorBody call:contentHash META inline pages only+src/core/facts/proposal-supersede.ts mirrorBody call:refreshPageBody SEGW assertInlineBody first+src/core/facts/proposal-supersede.ts mirrorBody field SEGW assertInlineBody before refreshPageBody (inside the transaction, before the file publish)+src/core/facts/proposal-supersede.ts prepareProposalMutation call:serializePageToMarkdown SEGW spread of a segmented page throws+src/core/facts/proposal-supersede.ts prepareProposalMutation field SEGW segmented page: getter throws page_body_segmented in preparation (nothing written)+src/core/facts/proposal-supersede.ts undoUnmanaged field SEGW segmented page: getter throws page_body_segmented+src/core/facts/purge-verify.ts verifyFactPurge sql STREAM pages store reports unverified (segmented_body) while the source holds segmented pages; segment probe in PR 2+src/core/facts/purge-verify.ts verifyPagePurge sql STREAM source_prose store reports unverified (segmented_body) while the source holds segmented pages; segment probe in PR 2+src/core/facts/purge.ts planFactPurge sql SEGW strpos over NULL never matches a segmented page; the purge refuses segmented targets (rewritePageBodies)+src/core/facts/purge.ts redactPageVersions field SEGW lane 1e: segmented versions carry no body+src/core/facts/purge.ts redactPageVersions sql SEGW lane 1e: segmented versions carry no body+src/core/facts/purge.ts rewritePageBodies call:contentHash META inline pages only (see sql row)+src/core/facts/purge.ts rewritePageBodies field SEGW segmented page: getter throws page_body_segmented+src/core/facts/purge.ts rewritePageBodies sql SEGW refuses a segmented target with page_body_segmented before rewriting (segment purge in PR 2)+src/core/facts/reconcile-watermark.ts readFactsReconcileBacklog sql STREAM+src/core/facts/reconcile-watermark.ts selectFactsReconcileDrain sql STREAM+src/core/facts/relink-publish.ts prepareRelinkMutation call:serializePageToMarkdown SEGW+src/core/facts/relink-publish.ts prepareRelinkMutation field SEGW+src/core/facts/subject-infer-write.ts linkAllowed field STREAM+src/core/facts/unfenced-facts.ts auditUnadoptableFacts call:serializePageToMarkdown SEGW+src/core/facts/unfenced-facts.ts fenceFilePage call:contentHash META+src/core/facts/unfenced-facts.ts fenceFilePage call:refreshPageBody SEGW+src/core/facts/unfenced-facts.ts fenceFilePage field SEGW+src/core/facts/unfenced-facts.ts planManagedPage call:serializePageToMarkdown SEGW+src/core/facts/withdrawal-discovery.ts discoverWithdrawalTargets field STREAM inline rows only+src/core/facts/withdrawal-discovery.ts discoverWithdrawalTargets sql STREAM page scan reads inline bodies (NULL never matches); segmented pages are found by the chunk scan and their mirror writers refuse or skip (per-segment discovery, PR 2)+src/core/fence-repair/census.ts judgePages field STREAM+src/core/fence-repair/content.ts contentPass field STREAM+src/core/fence-repair/hold-fix.ts fenceFileLine field STREAM+src/core/fence-repair/import-step.ts applyImportFences field STREAM+src/core/fence-repair/import-step.ts hiddenFenceRows field STREAM+src/core/fence-repair/import-step.ts resolveImportFences field STREAM+src/core/fence-repair/import-step.ts settleImportFences field STREAM+src/core/fence-repair/import-step.ts storedPageStep field STREAM+src/core/fence-repair/normalize.ts withSections field STREAM+src/core/fence-repair/page-checks.ts sectionsOf field STREAM+src/core/fence-repair/refusal.ts completeFenceLocation field STREAM+src/core/fence-repair/refusal.ts scanCanonicalFences field STREAM+src/core/fence-repair/repair-io.ts pageSha field SEGW+src/core/fence-repair/repair-io.ts readFenceTarget field SEGW+src/core/fence-repair/repair-io.ts spliceFileSections field SEGW+src/core/fence-repair/repair-io.ts writeFenceRepair call:serializePageToMarkdown SEGW+src/core/fence-repair/repair-io.ts writeFenceRepair field SEGW+src/core/fence-repair/repair-tiers.ts holderAt field STREAM+src/core/fence-repair/tier1.ts pageHasFenceText field STREAM+src/core/fts-language.ts pageSearchVectorTriggerFnSql sql LEAD+src/core/google/loops-extract.ts runLoopsExtract field STREAM tail slice(-12000) of a getPage body; per-job: segmented page: getter throws page_body_segmented+src/core/import-file.ts applyImportTransaction call:putPage SEGW lane 1d file (streaming ingest); code/image pages inline+src/core/import-file.ts importCodeFile call:putPage SEGW lane 1d file (streaming ingest); code/image pages inline+src/core/import-file.ts importFromContent call:contentHash META lane 1d file+src/core/import-file.ts importFromContent call:putPage SEGW lane 1d file (streaming ingest); code/image pages inline+src/core/import-file.ts importFromContent call:refreshPageBody SEGW lane 1d file (streaming ingest); code/image pages inline+src/core/import-file.ts importFromContent field SEGW lane 1d file (streaming ingest); code/image pages inline+src/core/import-file.ts importImageFile field SEGW lane 1d file (streaming ingest); code/image pages inline+src/core/import-identity.ts decideImportIdentity field META+src/core/import-screen.ts assessImportSanity field STREAM+src/core/import-screen.ts screenImportContent call:contentHash META+src/core/import-screen.ts screenImportContent field STREAM+src/core/link-reconciliation.ts reconcileSourceLinks field STREAM segmented page skipped with failure code page_body_segmented; the cursor moves past it (per-segment links, PR 4)+src/core/link-temporal-apply.ts applyTemporalEvidence field STREAM+src/core/link-temporal-evidence.ts deriveTemporalEvidence field STREAM+src/core/markdown-chunks.ts overlaidChunks field STREAM+src/core/markdown-chunks.ts prepareFenceAwareMarkdownChunks call:prepareMarkdownChunks STREAM+src/core/markdown-chunks.ts prepareFenceAwareMarkdownChunks field STREAM+src/core/markdown.ts parseMarkdown field STREAM+src/core/markdown.ts serializePageToMarkdown call:serializeMarkdown SEGW+src/core/markdown.ts serializePageToMarkdown field STREAM+src/core/mentions/aliases.ts deriveEntityAliases field STREAM+src/core/mentions/pass.ts pagesMatchingNames sql STREAM segmented pages excluded in SQL+src/core/mentions/pass.ts reconcileSource field STREAM inline rows only+src/core/mentions/pass.ts reconcileSource sql STREAM segmented pages excluded in SQL (stay due and pending until the per-segment pass)+src/core/mentions/pass.ts refreshAliases sql STREAM segmented pages excluded in SQL+src/core/minions/handlers/facts-absorb.ts makeFactsAbsorbHandler field STREAM+src/core/minions/handlers/subagent-oneshot.ts runSubagentOneshot call:serializeMarkdown SEGW+src/core/ops/admin.ts get_versions field SEGW lane 1e: segmented versions return metadata only+src/core/ops/attribution.ts get_write_attribution field NONE not the page body: timeline entry id param+src/core/ops/attribution.ts rowTarget field NONE not the page body: timeline entry id param+src/core/ops/get-page-body.ts bodyBytes field META+src/core/ops/get-page-body.ts readPartialBody call:serializePageToMarkdown SEGW+src/core/ops/get-page-projection.ts projectFetchText call:serializePageToMarkdown STREAM fetch text of an inline page; spread of a segmented page throws+src/core/ops/get-page-projection.ts projectGetPage call:serializePageToMarkdown STREAM full content render of an inline page+src/core/ops/get-page-projection.ts projectGetPage field STREAM segmented page: getter throws page_body_segmented (windowed read in PR 2)+src/core/ops/pages.ts get_page field STREAM get_page full body: segmented page: getter throws page_body_segmented (windowed read in PR 2)+src/core/ops/pages.ts stripPrivacyFencesForRemoteReader field STREAM segmented page: getter throws page_body_segmented+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/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/page-shape.ts pageBodyBytes field INLINE inline branch of pageBodyBytes; a segmented page answers body_bytes+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+src/core/page-embedding-budget.ts sizeStateField field META lane 1e file: body_bytes for segmented pages+src/core/page-snapshot-batch.ts readPageSnapshotsBatch field STREAM same as readPageSnapshot: overlay skipped for a segmented page+src/core/page-snapshot-batch.ts readPageSnapshotsBatch sql STREAM p.* feeds rowToPage; the byte budget counts a segmented row as 0 (no body shipped); fingerprint over a NULL body is empty+src/core/page-state/credential-reseal.ts PENDING sql STREAM regex over NULL is false: segmented pages postdate the v189 unseal and are chunked by the credential-safe segment chunker; pem regions in PR 2+src/core/page-state/import-guard.ts canonicalFields field META+src/core/page-state/import-guard.ts sameContentAnyKeyOrder field META+src/core/page-state/materialize.ts materializePageSnapshot call:contentHash META inline pages only+src/core/page-state/materialize.ts materializePageSnapshot field SEGW assertInlineBody before the UPDATE+src/core/page-state/materialize.ts materializePageSnapshot sql SEGW assertInlineBody before the UPDATE+src/core/page-state/projection-schema.ts PAGE_PROJECTION_SCHEMA_STATEMENTS sql STREAM trigger DDL: search vector reads timeline (lane 1a adds timeline_lead)+src/core/page-state/projections.ts preparePageProjection call:prepareMarkdownChunks STREAM+src/core/page-state/projections.ts readGuardedProjectionSnapshot field STREAM+src/core/page-state/projections.ts sealImportedPage field STREAM+src/core/page-state/projections.ts sealPageTextProjection field STREAM+src/core/page-state/schema.ts PAGE_STATE_SCHEMA_STATEMENTS sql STREAM revision trigger tuple (lane 1a adds body_generation)+src/core/page-state/snapshot.ts overlayCanonicalBodies field STREAM overlays a caller-supplied body string (file bytes), not a stored segmented body+src/core/page-state/snapshot.ts overlayCanonicalBodies sql STREAM normalizes the caller-supplied body+src/core/page-state/snapshot.ts readSnapshotStatement field STREAM withdrawal overlay runs on inline pages only; segmented page skips it (per-window overlay in PR 2)+src/core/page-state/snapshot.ts readSnapshotStatement sql STREAM p.* feeds rowToPage (projects body_storage/body_bytes); the fingerprint over a NULL body is empty+src/core/page-state/versions.ts createPageVersion field SEGW lane 1e file: segmented versions reference a generation+src/core/page-state/versions.ts createPageVersion sql SEGW lane 1e file: segmented versions reference a generation+src/core/page-window/bounded-lead.ts overlaidBoundedPrefix field LEAD see overlaidBoundedRows+src/core/page-window/bounded-lead.ts overlaidBoundedRows field LEAD rows carry boundedBodyPrefixSql (truth_lead for segmented); a segmented page whose lead holds a facts fence gets an empty lead (fail closed)+src/core/page-window/document.ts projectPageText field STREAM+src/core/page-window/document.ts readPageDocument call:pageDocument STREAM+src/core/page-window/document.ts readPageDocument field STREAM+src/core/persistence/atom-maintenance.ts prepareManagedAtomMutation field META+src/core/persistence/atom-maintenance.ts readAtomOrigin field META+src/core/persistence/atom-retry.ts retryManagedAtomBatch field STREAM+src/core/persistence/canonical-projections.ts canonicalTakeRows field STREAM per-page projection: segmented page: getter throws page_body_segmented+src/core/persistence/canonical-projections.ts compileCanonicalProjections field STREAM per-page projection: segmented page: getter throws page_body_segmented+src/core/persistence/canonical-projections.ts materializeTimeline field STREAM per-page projection: segmented page: getter throws page_body_segmented+src/core/persistence/canonical-projections.ts prepareCanonicalProjections field STREAM per-page projection: segmented page: getter throws page_body_segmented+src/core/persistence/canonical-projections.ts safeBody field STREAM per-page projection: segmented page: getter throws page_body_segmented+src/core/persistence/connector-google-receipts.ts prepareGoogleReceiptPatch call:contentHash META+src/core/persistence/connector-google-receipts.ts prepareGoogleReceiptPatch call:serializePageToMarkdown SEGW+src/core/persistence/connector-sync.ts ManagedConnectorSync.page call:serializePageToMarkdown SEGW+src/core/persistence/connector-sync.ts prepareConnectorMutation call:serializePageToMarkdown SEGW+src/core/persistence/connector-sync.ts prepareConnectorMutation field SEGW+src/core/persistence/core-guard.ts prepareCoreGuard field INLINE+src/core/persistence/effect-facts.ts bodyAlreadyOffered field META+src/core/persistence/effect-links.ts mentionTargets field STREAM per-page effect: segmented page: getter throws page_body_segmented+src/core/persistence/effects.ts gitPage call:serializePageToMarkdown SEGW segmented target skipped (skipped reason page_body_segmented) before the serialize+src/core/persistence/effects.ts mirrorPage call:serializePageToMarkdown SEGW segmented target skipped (skipped reason page_body_segmented) before the serialize; per-segment mirror in PR 2+src/core/persistence/embedding-settlement.ts listEmbeddingCandidates sql META+src/core/persistence/facts-maintenance.ts prepareManagedFactsSession field META+src/core/persistence/facts-prepare.ts prepareManagedFactsMutation call:serializePageToMarkdown SEGW assertInlineBody first+src/core/persistence/facts-prepare.ts prepareManagedFactsMutation field SEGW assertInlineBody on the entity snapshot before the fence write+src/core/persistence/file-repair.ts canonicalRepairFields field META+src/core/persistence/grandfather.ts prepareGrandfatherMutation call:contentHash META+src/core/persistence/grandfather.ts prepareGrandfatherMutation call:serializePageToMarkdown SEGW+src/core/persistence/import-prepare.ts prepareManagedImportMutation call:serializePageToMarkdown SEGW+src/core/persistence/large-page-guard.ts assertLargePageAdmission sql META stored size = body_bytes for a segmented page, octet_length of the columns for an inline page+src/core/persistence/links-maintenance.ts extractManagedStaleLinks field NONE not the page body: result.timeline counter+src/core/persistence/links-maintenance.ts formatManagedStaleExtraction field NONE not the page body: result.timeline counter+src/core/persistence/links-preparation.ts prepareAutomaticLinks field STREAM reads the incoming parsed page, not a stored body+src/core/persistence/loop-fact-retirement.ts prepareLoopFactRetirement call:serializePageToMarkdown SEGW+src/core/persistence/loop-fact-retirement.ts prepareLoopFactRetirement field SEGW+src/core/persistence/memory-mutations.ts planRememberTarget call:serializePageToMarkdown SEGW+src/core/persistence/memory-mutations.ts planRememberTarget field STREAM+src/core/persistence/memory-prepare.ts prepareMemoryMutation call:serializePageToMarkdown SEGW assertInlineBody first+src/core/persistence/memory-prepare.ts prepareMemoryMutation field SEGW assertInlineBody before the fence write+src/core/persistence/page-advisories.ts lineGrammarAdvisory field STREAM+src/core/persistence/page-advisories.ts preparePageAdvisories field STREAM+src/core/persistence/page-edit.ts pageSegments call:serializePageToMarkdown SEGW+src/core/persistence/page-edit.ts pageSegments field SEGW+src/core/persistence/page-input.ts normalizeSubagentPageInput call:serializeMarkdown SEGW+src/core/persistence/page-input.ts normalizeSubagentPageInput field SEGW+src/core/persistence/page-prepare.ts canonical field SEGW lane 1d file; segmented page: getter throws page_body_segmented+src/core/persistence/page-prepare.ts fileMatchesSnapshot field SEGW lane 1d file; segmented page: getter throws page_body_segmented+src/core/persistence/page-prepare.ts preparePageMutation call:serializePageToMarkdown SEGW lane 1d file+src/core/persistence/page-prepare.ts preparePageMutation field SEGW lane 1d file: preserveProtectedTakes reads the snapshot body; segmented page: getter throws page_body_segmented+src/core/persistence/page-purge.ts purgePageInTransaction call:contentHash META+src/core/persistence/page-purge.ts purgePageInTransaction field STREAM+src/core/persistence/page-purge.ts purgePageInTransaction sql STREAM+src/core/persistence/prepared-maintenance.ts stampMaintenancePage call:serializePageToMarkdown SEGW+src/core/persistence/prepared-maintenance.ts verifyMaintenanceOutputs call:serializePageToMarkdown SEGW+src/core/persistence/purged-intent.ts intentCarriesPurgedContent call:contentHash META+src/core/persistence/purged-intent.ts intentCarriesPurgedContent field STREAM+src/core/persistence/reconcile-audit.ts auditCanonicalSource sql META+src/core/persistence/reconcile-merge.ts reconcileCanonical field INLINE+src/core/persistence/reconcile-prepare.ts prepareReconcileMutation call:serializePageToMarkdown INLINE+src/core/persistence/reconcile-prepare.ts prepareReconcileResult call:serializePageToMarkdown INLINE+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/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+src/core/persistence/sync-prepare.ts prepareManagedSyncMutation call:serializePageToMarkdown SEGW lane 1d file+src/core/persistence/sync-prepare.ts prepareManagedSyncMutation field SEGW lane 1d file: preserveProtectedTakes; segmented page: getter throws page_body_segmented+src/core/persistence/takes-prepare.ts prepare call:serializePageToMarkdown SEGW+src/core/persistence/writer-guard-schema.ts MANAGED_WRITER_GUARD_FUNCTION_SQL sql STREAM managed-writer guard tuple (lane 1a adds body_generation)+src/core/pglite-engine.ts PGLiteEngine.putPage call:putPage SEGW delegation to engine-sql putPage+src/core/pglite-engine.ts PGLiteEngine.refreshPageBody call:refreshPageBody SEGW delegation to engine-sql refreshPageBody+src/core/post-upgrade-reembed.ts computeReembedEstimate sql META+src/core/postgres-engine.ts PostgresEngine.putPage call:putPage SEGW delegation to engine-sql putPage+src/core/postgres-engine.ts PostgresEngine.refreshPageBody call:refreshPageBody SEGW delegation to engine-sql refreshPageBody+src/core/quarantine-override.ts quarantineOverrideBinding field META+src/core/quarantine-override.ts quarantineOverrideFor field META+src/core/questions/freshness.ts OWNER_BODY_HASH_SQL sql META owner-evidence change signal: content_hash for a segmented page, md5 of the body for inline (stored evidence unchanged)+src/core/questions/pages.ts readQuestionPage field INLINE see sql row+src/core/questions/pages.ts readQuestionPage sql INLINE question pages are inline by construction; assertInlineBody refuses a segmented one+src/core/questions/pages.ts renderPage call:serializePageToMarkdown INLINE+src/core/questions/pages.ts syncQuestionPage field INLINE+src/core/questions/refresh.ts refreshPin field INLINE owner claims of the question page (readQuestionPage asserts inline)+src/core/questions/refresh.ts retrieveEvidence field LEAD inline candidates only+src/core/questions/refresh.ts retrieveEvidence sql LEAD segmented candidate pages excluded in SQL (skip): their excerpt and laundering check need the body+src/core/reindex-consent.ts estimateReindexSpend sql META+src/core/repair/captured-facts.ts strikeFencedRows call:serializePageToMarkdown SEGW+src/core/repair/captured-facts.ts strikeFencedRows field SEGW+src/core/repair/connector-fences.ts candidates sql STREAM+src/core/repair/connector-fences.ts connectorFencesRepair call:serializePageToMarkdown SEGW+src/core/repair/connector-fences.ts connectorFencesRepair field STREAM+src/core/repair/connector-fences.ts relocateTimelineFences field STREAM+src/core/repair/conversation-labels.ts classifyLabelFacts sql STREAM+src/core/repair/conversation-labels.ts countLabelFacts sql STREAM+src/core/repair/extractor-facts.ts restorePageFacts field STREAM+src/core/repair/extractor-facts.ts restorePageFacts sql STREAM+src/core/repair/fences.ts afterBytes field STREAM+src/core/repair/fences.ts fencesRepair field STREAM+src/core/repair/frontmatter.ts analyzeFile field LEAD+src/core/repair/frontmatter.ts pagesByOrigin sql LEAD+src/core/repair/orphan-children.ts PROBE_SQL sql META+src/core/repair/safe-chunks.ts safeChunksRepair sql META+src/core/repair/slug-conflicts.ts pageContent call:serializePageToMarkdown SEGW+src/core/repair/stale-atoms.ts staleAtoms sql META+src/core/repair/take-supersession.ts readPage call:serializePageToMarkdown SEGW+src/core/repair/timeline-comments.ts timelineCommentsRepair call:serializePageToMarkdown SEGW+src/core/repair/timeline-comments.ts timelineCommentsRepair field STREAM+src/core/repair/timeline-comments.ts timelineCommentsRepair sql STREAM+src/core/repair/timeline.ts classifyTimelinePage field STREAM+src/core/repair/timeline.ts recountTimelinePages sql STREAM+src/core/repair/timeline.ts removedRowIds field STREAM+src/core/repair/timeline.ts scanTimelineHistory sql STREAM+src/core/repair/timeline.ts timelineRepair call:serializePageToMarkdown SEGW+src/core/repair/timeline.ts timelineRepair field STREAM+src/core/repair/visibility.ts planVisibilityRepair sql META+src/core/repair/visibility.ts visibilityRepair call:serializePageToMarkdown SEGW+src/core/schema-migrations/v091-pages-generation-trigger-and-bookmark.ts v091 sql NONE not the page body: historical generation trigger+src/core/schema-migrations/v123-configurable-fts-language.ts v123 sql NONE not the page body: historical+src/core/schema-migrations/v124-page-search-vector-drop-compiled-truth.ts v124 sql NONE not the page body: historical search-vector trigger+src/core/schema-migrations/v189-pages-credential-projection-pending.ts v189 sql NONE not a live reader: historical migration over inline pages (segmented pages did not exist)+src/core/schema-pack/field-usage.ts runFieldUsage field LEAD+src/core/schema-pack/field-usage.ts runFieldUsage sql LEAD+src/core/schema-pack/page-to-alias.ts resolveValue field LEAD+src/core/schema-pack/page-to-alias.ts runPageToAliasCore field LEAD+src/core/schema-pack/page-to-alias.ts runPageToAliasCore sql LEAD+src/core/schema-pack/page-to-link.ts resolveSlug field LEAD+src/core/schema-pack/page-to-link.ts runPageToLinkCore field LEAD+src/core/schema-pack/page-to-link.ts runPageToLinkCore sql LEAD+src/core/search-vector-backfill.ts backfillPageVectors field LEAD+src/core/search-vector-backfill.ts backfillPageVectors sql LEAD+src/core/search/alias-hop.ts aliasInjectedRow field LEAD projectedLead over getPage: segmented page: getter throws page_body_segmented (lead source in PR 2)+src/core/search/chunk-windows.ts mapChunkWindowRows field STREAM+src/core/search/entity-anchor.ts entityAnchoredPages sql STREAM+src/core/search/evidence-delivery.ts deliverEvidence field STREAM+src/core/search/exact-lookup.ts structuralExactLookup field LEAD projectedLead over getPage: segmented page: getter throws page_body_segmented (lead source in PR 2)+src/core/search/provenance-demotion.ts applyGeneratedDemotion field LEAD+src/core/search/provenance-demotion.ts applyGeneratedDemotion sql LEAD+src/core/search/read-enrichment.ts readAliases sql NONE not the page body: SELECT * FROM pages used for identity columns+src/core/search/read-enrichment.ts readChainHop sql META SELECT * FROM pages by id; protectedBodyFilter(ev) reads body_flags for a segmented page+src/core/search/relational-recall.ts hydrate field LEAD synopsis from boundedBodyPrefixSql+src/core/search/safe-chunks.ts bodyWriteChunkVersion sql SEGW spliced into inline body writes only; a segmented row refuses those writes (CHECK)+src/core/search/safe-chunks.ts protectedBodyFilter sql META segmented page: body_flags.has_protected decides, missing flag counts as protected (fail closed)+src/core/shared-skills/migration-export.ts exportInventory call:serializeMarkdown INLINE+src/core/shared-skills/migration-export.ts exportInventory field INLINE+src/core/shared-skills/migration-projection.ts assertExportProjectionRoundtrip field INLINE+src/core/sweep.ts runLinksTimelinePass field STREAM segmented page skipped (skip reason page_body_segmented:links_timeline)+src/core/sweep.ts runMaintenanceSweep sql STREAM LIKE over NULL never matches a segmented page (skip)+src/core/think/gather.ts renderPagesBlockDetailed field LEAD segmented page: getter throws page_body_segmented+src/core/think/gather.ts runGather field LEAD visibleLeads reads Page.compiled_truth from listPages/search: segmented page: getter throws page_body_segmented (lead source in PR 2)+src/core/think/index.ts composeExtractiveFallback field LEAD+src/core/think/index.ts persistSynthesis call:putPage SEGW+src/core/timeline-dedup-repair.ts repairLegacyTimelineSourceRows field STREAM+src/core/timeline-dedup-repair.ts repairLegacyTimelineSourceRows sql STREAM+src/core/timeline-extract.ts pruneTimelineOrphans field STREAM+src/core/timeline-extract.ts pruneTimelineOrphans sql STREAM+src/core/timeline-extract.ts retractCoordinated field STREAM+src/core/timeline-extract.ts retractCoordinated sql STREAM+src/core/timeline-extract.ts retractRemovedTimelineEntries field STREAM+src/core/timeline-extract.ts retractRemovedTimelineEntries sql STREAM+src/core/timeline-write-through.ts writeTimelineEntryThrough field SEGW assertInlineBody before the file or row is touched+src/core/timeline-write-through.ts writeTimelineEntryThrough sql SEGW assertInlineBody before the file or row is touched+src/core/transcripts/recover.ts userlessCodexSessions sql STREAM+src/core/transcripts/secret-audit.ts auditTranscriptSecrets field STREAM+src/core/transcripts/secret-audit.ts auditTranscriptSecrets sql STREAM+src/core/trust/page-handlers.ts markdownWithoutMarker call:serializeMarkdown SEGW+src/core/trust/page-handlers.ts markdownWithoutMarker field SEGW+src/core/trust/page-handlers.ts versionMarkdown call:serializePageToMarkdown SEGW+src/core/trust/page-handlers.ts versionMarkdown field SEGW+src/core/utils.ts contentHash field META hashes a whole inline page; a segmented page hashes as a stream (1.4) and keeps content_hash; called on a segmented Page the getter throws+src/core/utils.ts contentHashLegacy field META legacy formula over an inline page; segmented: getter throws+src/core/utils.ts rowToPage field INLINE installs throwing body getters on a segmented row (guardSegmentedBody); inline rows copy the columns+src/core/utils.ts rowToStalePage field STREAM listStalePagesForExtraction lists inline pages only (segmented skipped in SQL, still counted stale)+src/core/verbs/entity-card-identity.ts readCardIdentity field LEAD+src/core/verbs/entity-card.ts selectEntityCandidates sql LEAD boundedBodyPrefixSql AS compiled_truth+src/core/verbs/entity-names.ts lookupOne field LEAD bounded prefix rows+src/core/verbs/entity-names.ts lookupOne sql LEAD boundedBodyPrefixSql AS compiled_truth+src/core/write-gate-scan.ts SPECS field STREAM+src/core/write-gate-scan.ts SPECS sql STREAM+src/core/write-gate.ts assessPageForGate field STREAM+src/core/write-through.ts writePageThrough call:serializePageToMarkdown SEGW+src/eval/brainbench/metrics/trust-reads.ts canaryHeld sql STREAM+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 INLINEdiff --git a/scripts/run-verify-parallel.sh b/scripts/run-verify-parallel.shindex fff9ce6e21..139c7f80f1 100755--- a/scripts/run-verify-parallel.sh+++ b/scripts/run-verify-parallel.sh@@ -177,6 +177,9 @@ CHECKS=(# Goal (a) (refactor wave 1): engine SQL only shrinks; baseline# scripts/engine-sql-baseline.tsv."check:engine-sql-ratchet"+ # Wave B segmented storage (spec 1.5 layer 4): whole-body page readers only+ # shrink; baseline scripts/page-body-readers-baseline.tsv.+ "check:page-body-readers"# CQ3 / EO17 (refactor wave 1): engine-sql splices only constant text, no# composed $n, no expanded IN lists."check:engine-sql-dynamic"diff --git a/src/core/ai/decide/review-lane.ts b/src/core/ai/decide/review-lane.tsindex 157a3fdeee..d6c20e05df 100644--- a/src/core/ai/decide/review-lane.ts+++ b/src/core/ai/decide/review-lane.ts@@ -21,6 +21,7 @@*/import { randomBytes } from 'node:crypto';import type { BrainEngine } from '../../engine.ts';+import { boundedBodyPrefixSql } from '../../page-window/bounded-lead.ts';import { loadConfigSnapshot } from '../../config-snapshot.ts';import { readDecideConfig, type DecideConfig } from './config.ts';import { CONFLICT_INSTRUCTIONS, CONFLICT_MIN_COSINE, CONFLICT_NEIGHBOURS, CONFLICT_OPTIONS } from './conflict.ts';@@ -243,7 +244,7 @@ async function withdrawAnchor(engine: BrainEngine, row: QueueRow, cfg: DecideConasync function pagePairAnchor(engine: BrainEngine, row: QueueRow): Promise<Anchor | { skip: string }> {const pages = await engine.executeRaw<{ slug: string; title: string; compiled_truth: string }>(- `SELECT slug, title, compiled_truth FROM pages WHERE source_id = $1 AND slug = ANY($2::text[]) AND deleted_at IS NULL`,+ `SELECT slug, title, ${boundedBodyPrefixSql('pages')} AS compiled_truth FROM pages WHERE source_id = $1 AND slug = ANY($2::text[]) AND deleted_at IS NULL`,[row.source_id, [row.a_ref, row.b_ref]]);const a = pages.find(p => p.slug === row.a_ref);const b = pages.find(p => p.slug === row.b_ref);diff --git a/src/core/context/retrieval-reflex.ts b/src/core/context/retrieval-reflex.tsindex c090be18f6..93c03ff266 100644--- a/src/core/context/retrieval-reflex.ts+++ b/src/core/context/retrieval-reflex.ts@@ -44,10 +44,10 @@ import type { EntityCandidate } from './entity-salience.ts';import { reflexPointerRationale } from './reflex-rationale.ts';import { logVolunteerEventsFireAndForget, volunteerEventRowsFrom } from './volunteer-events.ts';import { boundedProjectedPrefix } from '../page-window/document.ts';-import { boundedPrefixSql, boundedRawPrefix, overlaidBoundedRows } from '../page-window/bounded-lead.ts';+import { boundedBodyPrefixSql, boundedRawPrefix, overlaidBoundedRows } from '../page-window/bounded-lead.ts';/** Large pages: candidate rows carry a bounded body prefix (the synopsis reads only its first sentence). */-const PREFIX_SQL = boundedPrefixSql('p.compiled_truth');+const PREFIX_SQL = boundedBodyPrefixSql('p');export { reflexPointerRationale } from './reflex-rationale.ts';diff --git a/src/core/contextual-retrieval-service.ts b/src/core/contextual-retrieval-service.tsindex 6ef55f9648..89e4c23dd3 100644--- a/src/core/contextual-retrieval-service.ts+++ b/src/core/contextual-retrieval-service.ts@@ -65,6 +65,7 @@ import { installPageEmbeddings, readProjectionSnapshot, type ProjectionSnapshotimport { reconcileContextualEmbeddingInputs } from './page-state/contextual-proof.ts';import { digest } from './persistence/digest.ts';import { isLargePageBytes } from './page-size-policy.ts';+import { pageBodyBytes } from './page-body/page-shape.ts';/*** v3 = chunks embed with optional contextual retrieval wrapper. The@@ -394,7 +395,7 @@ export async function reembedPageWithContextualRetrieval(args.synopsisMaxTokens ?? (await resolveSynopsisMaxTokens(args.engine));// Large pages: the title tier until per-chunk synopses are metered per page// (plan B8), and no re-embed while the per-page cap holds or capped the page.- const large = isLargePageBytes(Buffer.byteLength(page.compiled_truth ?? '', 'utf-8') + Buffer.byteLength(page.timeline ?? '', 'utf-8'));+ const large = isLargePageBytes(pageBodyBytes(page));if (large && (await args.engine.executeRaw(`SELECT 1 FROM page_embedding_budget WHERE page_id = $1 AND state <> 'open'`, [page.id])).length) {return { kind: 'skipped', reason: 'budget_limited' };}diff --git a/src/core/cycle/concept-publication.ts b/src/core/cycle/concept-publication.tsindex 8a07c89d98..f145f1b374 100644--- a/src/core/cycle/concept-publication.ts+++ b/src/core/cycle/concept-publication.ts@@ -9,6 +9,7 @@import type { BrainEngine, LinkBatchInput } from '../engine.ts';import { preservedConceptSections, stripPreservedConceptSections } from './concept-sections.ts';import type { Page } from '../types.ts';+import { assertInlineBody } from '../page-body/page-shape.ts';import { serializeMarkdown, parseMarkdown, type ParsedMarkdown } from '../markdown.ts';import { digest } from '../persistence/digest.ts';import { FACTS_FENCE_BEGIN, FACTS_FENCE_END, parseFactsFence, replaceOrInsertFactsFence, stripFactsFence } from '../facts-fence.ts';@@ -105,9 +106,11 @@ export function composeConceptRepublication(page: Pick<Page, 'type' | 'title' |* Curated `## Facets` / `## Merged` sections (#6161: the record of a concept* merge) are carried the same way. Throws a hold* (`concept_preservation_hold`) when the original fences are ambiguous or the- * result would not carry exactly the original rows and sections.+ * result would not carry exactly the original rows and sections. A segmented+ * page refuses with `page_body_segmented`: its fences live in segments.*/-export function preserveCanonicalFences(page: Pick<Page, 'compiled_truth' | 'timeline'>, replacement: string): string {+export function preserveCanonicalFences(page: Pick<Page, 'compiled_truth' | 'timeline' | 'body_storage'>, replacement: string): string {+ assertInlineBody(page, 'preserveCanonicalFences');const hold = conceptPreservationHold(page);if (hold) throw conceptHoldError(hold);const body = page.compiled_truth ?? '';diff --git a/src/core/cycle/extract-atoms-input.ts b/src/core/cycle/extract-atoms-input.tsindex ac41c56956..83d9583d41 100644--- a/src/core/cycle/extract-atoms-input.ts+++ b/src/core/cycle/extract-atoms-input.ts@@ -150,15 +150,15 @@ export async function recordPartialDisposition(engine: SqlEngine, sourceId: striif (!item.identity) throw new AtomPageStateError('unpinned');const rows = await engine.executeRaw(`INSERT INTO extract_atoms_page_state (source_incarnation, page_id, content_hash, fail_count, tombstoned, partial_input_chars)- SELECT s.incarnation, p.id, p.content_hash, 0, false, $8::integer+ SELECT s.incarnation, p.id, p.content_hash, 0, false, $7::integerFROM pages p JOIN sources s ON s.id=p.source_idWHERE p.id=$1 AND s.incarnation=$2::uuid AND p.source_id=$3 AND p.slug=$4- AND p.content_hash=$5 AND p.knowledge_revision=$6::uuid AND p.compiled_truth=$7 AND p.deleted_at IS NULL+ AND p.content_hash=$5 AND p.knowledge_revision=$6::uuid AND p.deleted_at IS NULLFOR SHARE OF p, sON CONFLICT (source_incarnation, page_id, content_hash) DO UPDATESET partial_input_chars=EXCLUDED.partial_input_chars, updated_at=now()RETURNING page_id`,- [item.identity.pageId, item.identity.sourceIncarnation, sourceId, item.slug, item.contentHash, item.identity.revision, item.content, maxInputChars])+ [item.identity.pageId, item.identity.sourceIncarnation, sourceId, item.slug, item.contentHash, item.identity.revision, maxInputChars]).catch((error: unknown) => {const code = error && typeof error === 'object' && 'code' in error ? error.code : undefined;throw new AtomPageStateError(code === '42P01' ? 'schema' : code === '42501' ? 'denied' : 'storage');diff --git a/src/core/cycle/extract-atoms-page-state.ts b/src/core/cycle/extract-atoms-page-state.tsindex acb86f3f5e..f6bbf52149 100644--- a/src/core/cycle/extract-atoms-page-state.ts+++ b/src/core/cycle/extract-atoms-page-state.ts@@ -41,8 +41,8 @@ export class AtomPageStateError extends Error {export async function readAtomPageIdentity(engine: SqlEngine, sourceId: string, item: AtomPageInput): Promise<AtomPageIdentity | undefined> {const [row] = await engine.executeRaw<{ id: number; incarnation: string; knowledge_revision: string }>(`SELECT p.id, s.incarnation, p.knowledge_revision FROM pages p JOIN sources s ON s.id=p.source_id- WHERE p.source_id=$1 AND p.slug=$2 AND p.content_hash=$3 AND p.compiled_truth=$4 AND p.deleted_at IS NULL`,- [sourceId, item.slug, item.contentHash, item.content]);+ WHERE p.source_id=$1 AND p.slug=$2 AND p.content_hash=$3 AND p.deleted_at IS NULL`,+ [sourceId, item.slug, item.contentHash]);return row && { pageId: row.id, sourceIncarnation: row.incarnation, revision: row.knowledge_revision };}@@ -53,16 +53,16 @@ export async function writeAtomPageState(const { pageId, sourceIncarnation, revision } = item.identity;const [row] = await engine.executeRaw<{ fail_count: number }>(`INSERT INTO extract_atoms_page_state (source_incarnation, page_id, content_hash, fail_count, tombstoned)- SELECT s.incarnation, p.id, p.content_hash, $8::integer, $9::boolean+ SELECT s.incarnation, p.id, p.content_hash, $7::integer, $8::booleanFROM pages p JOIN sources s ON s.id=p.source_idWHERE p.id=$1 AND s.incarnation=$2::uuid AND p.source_id=$3 AND p.slug=$4- AND p.content_hash=$5 AND p.knowledge_revision=$6::uuid AND p.compiled_truth=$7 AND p.deleted_at IS NULL+ AND p.content_hash=$5 AND p.knowledge_revision=$6::uuid AND p.deleted_at IS NULLFOR SHARE OF p, sON CONFLICT (source_incarnation, page_id, content_hash) DO UPDATESET fail_count=extract_atoms_page_state.fail_count + EXCLUDED.fail_count,tombstoned=extract_atoms_page_state.tombstoned OR EXCLUDED.tombstoned, updated_at=now()RETURNING fail_count`,- [pageId, sourceIncarnation, sourceId, item.slug, item.contentHash, revision, item.content,+ [pageId, sourceIncarnation, sourceId, item.slug, item.contentHash, revision,outcome === 'failure' ? 1 : 0, outcome === 'complete']).catch((error: unknown) => {const code = error && typeof error === 'object' && 'code' in error ? error.code : undefined;throw new AtomPageStateError(code === '42P01' ? 'schema' : code === '42501' ? 'denied' : 'storage');diff --git a/src/core/cycle/extract-facts.ts b/src/core/cycle/extract-facts.tsindex e32e7532be..e68270ecd9 100644--- a/src/core/cycle/extract-facts.ts+++ b/src/core/cycle/extract-facts.ts@@ -65,6 +65,7 @@ import { digest } from '../persistence/digest.ts';import { getWriteRequest } from '../persistence/journal.ts';import { maintenanceCallerPreflight, maintenancePreflight, submitDatabaseMaintenanceIntent, type MaintenanceAuthority } from '../persistence/prepared-maintenance.ts';import { resolveManagedFactsEmbedding } from '../persistence/facts-maintenance.ts';+import { isSegmentedPage } from '../page-body/page-shape.ts';import { REVISION_BACKFILL_PENDING } from '../page-state/types.ts';import { opError, OperationError } from '../ops/contract.ts';import {@@ -993,6 +994,10 @@ export async function runExtractFacts(revision = page.knowledge_revision ?? null;// #6259: a quarantined page projects no fence facts; its existing index is left as it is.if (isQuarantined(page.frontmatter as Record<string, unknown> | null)) return 'skipped';+ if (isSegmentedPage(page)) {+ result.warnings.push(`${slug}: FACTS_RECONCILE_SEGMENTED: the page body is stored in segments, which fence reconcile cannot read yet; its existing facts index is preserved`);+ return 'skipped';+ }const plan = await planFenceReconcile(engine, page, slug, sourceId, result.warnings);if (!plan) return 'invalid';diff --git a/src/core/cycle/patterns.ts b/src/core/cycle/patterns.tsindex aada7543d2..cb5d1bf991 100644--- a/src/core/cycle/patterns.ts+++ b/src/core/cycle/patterns.ts@@ -25,6 +25,7 @@ import { join, dirname } from 'node:path';import { mkdirSync, writeFileSync } from 'node:fs';import { randomUUID } from 'node:crypto';import type { BrainEngine } from '../engine.ts';+import { boundedBodyPrefixSql } from '../page-window/bounded-lead.ts';import type { PhaseResult, PhaseError } from '../cycle.ts';import { DEFAULT_PRIVATE_QUEUE_LEASE_MS, MinionQueue } from '../minions/queue.ts';import { isQueueQuotaExceededError } from '../minions/admission.ts';@@ -607,7 +608,7 @@ async function gatherReflections(const rows = await engine.executeRaw<{id: number | string; slug: string; title: string | null; compiled_truth: string | null; updated_at: string | Date; seat: string | null; trust_tier: string | null;}>(- `SELECT id, slug, title, compiled_truth, updated_at, frontmatter->>'seat' AS seat, trust_tier+ `SELECT id, slug, title, ${boundedBodyPrefixSql('pages')} AS compiled_truth, updated_at, frontmatter->>'seat' AS seat, trust_tierFROM pagesWHERE slug LIKE $2AND source_id = $3 AND deleted_at IS NULL AND COALESCE(frontmatter->>'visibility','') <> 'private'diff --git a/src/core/cycle/phantom-redirect.ts b/src/core/cycle/phantom-redirect.tsindex 591a03b5f7..70ad627524 100644--- a/src/core/cycle/phantom-redirect.ts+++ b/src/core/cycle/phantom-redirect.ts@@ -38,6 +38,7 @@ import * as path from 'node:path';import type { BrainEngine } from '../engine.ts';import { contentHash } from '../utils.ts';+import { assertInlineBody } from '../page-body/page-shape.ts';import type { Page } from '../types.ts';import {resolvePhantomCanonical,@@ -575,6 +576,8 @@ export async function tryRedirectPhantom(return { outcome: 'drift', canonical };}const canonicalPath = writeTarget.ok ? writeTarget.filePath : path.join(brainDir, `${canonical}.md`);+ const target = await engine.getPage(canonical, { sourceId });+ if (target) assertInlineBody(target, 'phantom redirect');await materializeCanonicalToDisk(engine, canonical, sourceId, canonicalPath);// Disk-side first: parse phantom's fence and append to canonical'sdiff --git a/src/core/engine-sql/pages.ts b/src/core/engine-sql/pages.tsindex 512ba96e46..379cab8384 100644--- a/src/core/engine-sql/pages.ts+++ b/src/core/engine-sql/pages.ts@@ -102,16 +102,18 @@ export async function putPage(// over real content (ON CONFLICT sets compiled_truth = EXCLUDED.* flat).// Only fires when the incoming body is itself blank, so the common// non-empty write pays no extra query. Deletes use deletePage; a deliberate- // clear passes allowEmptyOverwrite. See isBlankBody.+ // clear passes allowEmptyOverwrite. See isBlankBody. A segmented page's+ // body columns are NULL, so its size is body_bytes.if (isBlankBody(page.compiled_truth) && !opts?.allowEmptyOverwrite) {- const { rows: prior } = await exec.run<{ compiled_truth: string | null }>(sqlFragment`- SELECT compiled_truth FROM pages+ const { rows: prior } = await exec.run<{ compiled_truth: string | null; body_storage: string | null; body_bytes: unknown }>(sqlFragment`+ SELECT compiled_truth, body_storage, body_bytes FROM pagesWHERE source_id = ${sourceId} AND slug = ${slug} AND deleted_at IS NULLLIMIT 1`);- if (prior[0] && !isBlankBody(prior[0].compiled_truth)) {+ const segmented = prior[0]?.body_storage === 'segmented';+ if (prior[0] && (segmented || !isBlankBody(prior[0].compiled_truth))) {throw new Error(`putPage: refusing to overwrite non-empty page '${slug}' ` +- `(${prior[0].compiled_truth!.length} chars) with an empty body — ` ++ `(${segmented ? `${Number(prior[0].body_bytes)} bytes, segmented` : `${prior[0].compiled_truth!.length} chars`}) with an empty body — ` +`likely a read-modify-write that read empty. Pass ` +`{ allowEmptyOverwrite: true } to force, or deletePage to remove it.`,);@@ -454,7 +456,7 @@ export async function listPages(exec: ScopedRead, filters?: PageFilters): Promisconst columns = filters?.listColumnsOnly === true? sqlFragment`p.id, p.source_id, p.slug, p.type, p.page_kind, p.title, p.created_at, p.updated_at, p.deleted_at,- p.effective_date, p.effective_date_source, ''::text AS compiled_truth, ''::text AS timeline, '{}'::jsonb AS frontmatter`+ p.effective_date, p.effective_date_source, p.body_storage, p.body_bytes, ''::text AS compiled_truth, ''::text AS timeline, '{}'::jsonb AS frontmatter`: sqlFragment`p.*`;const { rows } = await exec.run(sqlFragment`SELECT ${columns}, to_char(p.updated_at AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.US"Z"') AS updated_at_iso FROM pages p@@ -514,7 +516,8 @@ const toDomainBankRow = ((normalize) => (raw: Record<string, unknown>): DomainBa//// `listPrefixSampledPages`: one page per prefix, tiebroken by inbound-link// count (connection_count via LEFT JOIN to page_links). Stale-bias optional-// for LSD mode (D5). Source-scoped (D5). Excludes close-set slugs.+// for LSD mode (D5). Source-scoped (D5). Excludes close-set slugs, and (like+// listCorpusSample) segmented pages, whose body column is NULL.//// Ranking inside each prefix partition:// 1. stale_score DESC (when staleBias) — never-retrieved beats >90d-stale beats fresh@@ -543,7 +546,7 @@ export async function listPrefixSampledPages(scoped: ScopedReadRunner, opts: DomFROM pages pLEFT JOIN page_retrievals r ON r.page_id = p.idLEFT JOIN page_links pl ON pl.to_page_id = p.id- WHERE p.deleted_at IS NULL+ WHERE p.deleted_at IS NULL AND p.body_storage = 'inline'AND substring(p.slug from '^[^/]+/[^/]+') = ANY(${opts.prefixes}::text[])AND (cardinality(${exclude}::text[]) = 0 OR NOT (p.slug = ANY(${exclude}::text[])))AND (@@ -629,7 +632,7 @@ export async function listCorpusSample(scoped: ScopedReadRunner, opts: CorpusSam(SELECT COUNT(*) FROM page_links pl WHERE pl.to_page_id = p.id) AS connection_countFROM pages pLEFT JOIN page_retrievals r ON r.page_id = p.id- WHERE p.deleted_at IS NULL+ WHERE p.deleted_at IS NULL AND p.body_storage = 'inline'AND (cardinality(${exclude}::text[]) = 0 OR NOT (p.slug = ANY(${exclude}::text[])))AND ((${sourceIds}::text[] IS NOT NULL AND p.source_id = ANY(${sourceIds}::text[]))@@ -736,10 +739,13 @@ export async function listStalePagesForExtraction(exec: ScopedRead, opts: {// #1768: project a deterministic full-µs UTC string alongside updated_at.// to_char (not ::text — DateStyle-fragile) so extractStaleFromDB can stamp// links_extracted_at = the exact updated_at and the staleness predicate clears.+ // A segmented page is not listed (its body columns are NULL: extracting ''+ // would delete its derived links) but stays counted as stale until the+ // per-segment extraction reads it.const { text, params } = renderFragment(sqlFragment`SELECT id, slug, source_id, type, title, compiled_truth, timeline, frontmatter, updated_at,to_char(updated_at AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.US"Z"') AS updated_at_isoFROM pages- WHERE ${stalePagesWhere(opts)}${afterClause}+ WHERE ${stalePagesWhere(opts)} AND body_storage = 'inline'${afterClause}ORDER BY idLIMIT ${opts.batchSize}`);const { rows } = await exec.unsafe(text, params);diff --git a/src/core/error-registry.ts b/src/core/error-registry.tsindex e81241bb84..72caef5ce7 100644--- a/src/core/error-registry.ts+++ b/src/core/error-registry.ts@@ -346,6 +346,7 @@ export const CODES = {page_identity_changed: { class: 'caller', summary: "The page was deleted or replaced while the operation ran.", fix: { argv: ['gbrain', 'get', '--source', '{source_id}', '--', '{slug}'], mcp: { tool: 'get_page', arguments: { slug: '{slug}', source_id: '{source_id}' } }, consent: [], actor: 'agent', why: "Shows which page holds the slug now and its revision; a new attempt needs a new request_id.", requires_exclusive: false } },page_projection_conflict: { class: 'retryable', summary: "Another worker installed a newer search projection of the page while this command prepared its own.", why: "The projection guard keeps the newer installation instead of overwriting it; the canonical page revision did not change.", docs: 'docs/guides/repair.md#page-projection-conflict', suggestion: "Re-run the same command; it re-reads the current projection. If it conflicts again, wait for the other worker to finish." },page_not_found: { class: 'caller', summary: "No page with that slug exists in the selected source.", legacy_error: 'page_identity_changed', fix: { argv: ['gbrain', 'get', '--source', '{source_id}', '--', '{slug}'], mcp: { tool: 'get_page', arguments: { slug: '{slug}', source_id: '{source_id}' } }, consent: [], actor: 'agent', why: "Confirms whether the page exists in this source before anything is recreated.", requires_exclusive: false } },+ page_body_segmented: { class: 'caller', summary: "This page's body is stored in segments, and the path that hit it reads or writes the whole body as one string, so it stopped before reading or changing anything.", why: "With pages.segmented_storage on, a page over 1 MiB keeps its body in segments instead of the page row; a whole-body path would otherwise see an empty body and could overwrite the page or drop the unread rest. Windowed reads and segment-aware writers replace these paths.", docs: 'docs/guides/windowed-reads.md#page_body_segmented', suggestion: "Read the page's revision and stored size with get_page body: 'none' (size.body_bytes); windowed reads of a segmented body arrive with the segment reader.", fix: { argv: ['gbrain', 'get', '--source', '{source_id}', '--body', 'none', '--', '{slug}'], mcp: { tool: 'get_page', arguments: { slug: '{slug}', source_id: '{source_id}', body: 'none' } }, consent: [], actor: 'agent', why: "Returns the page's revision and size without its body.", requires_exclusive: false } },page_shrink_refused: { class: 'caller', summary: "put_page refused to replace a large page with content much smaller than the stored body; nothing was written.", why: "Above the inline read size (mcp.inline_body_bytes, 256 KB) a get_page read returns a window, not the body, so a replacement far smaller than the page is most often a window sent back as the whole page, which would delete the unread rest.", docs: 'docs/guides/windowed-reads.md#page_shrink_refused', suggestion: "Change part of the page with edit_page (revision from get_page body: 'none'). Pass allow_shrink: true only when the smaller content is the intended complete page.", fix: { argv: ['gbrain', 'get', '--source', '{source_id}', '--', '{slug}'], mcp: { tool: 'get_page', arguments: { slug: '{slug}', source_id: '{source_id}', body: 'none' } }, consent: [], actor: 'agent', why: "Returns the page's revision and size without its body; edit_page with that revision changes only the text it names.", requires_exclusive: false } },page_too_large_for_inline: { class: 'caller', summary: "The whole page does not fit one result on this connection, so get_page did not return its body.", why: "A result is measured as the complete encoded frame; a body over the connection's cap (mcp.max_result_bytes_stdio, 4 MiB; mcp.max_result_bytes_http, 1 MiB) would be cut or rejected by the client. Nothing was truncated: windowed reads cover the whole page in pieces.", docs: 'docs/guides/windowed-reads.md#page_too_large_for_inline', legacy_error: 'invalid_params', suggestion: "Read the outline (body: 'outline'), then windows (body: 'window' with lines, bytes, around_chunk_id or the returned next_cursor). To replace the page, edit it with edit_page and the revision from body: 'none'.", fix: { argv: ['gbrain', 'get', '--source', '{source_id}', '--', '{slug}'], mcp: { tool: 'get_page', arguments: { slug: '{slug}', source_id: '{source_id}', body: 'outline' } }, consent: [], actor: 'agent', why: "Returns the page's size, revision and outline; each entry names the lines to read with body: 'window'.", requires_exclusive: false, verify: { mcp: { tool: 'get_page', arguments: { slug: '{slug}', source_id: '{source_id}', body: 'none' } } } } },parse_error: { class: 'caller', summary: "The request body is not valid JSON." },diff --git a/src/core/facts/forget.ts b/src/core/facts/forget.tsindex c53a3d24ff..0584f5ffd3 100644--- a/src/core/facts/forget.ts+++ b/src/core/facts/forget.ts@@ -20,6 +20,7 @@ import { parseFactsFence, renderFactsTable, type ParsedFact } from '../facts-fenimport { parseMarkdown } from '../markdown.ts';import { sanitizeText } from '../batch-rows.ts';import { contentHash } from '../utils.ts';+import { assertInlineBody } from '../page-body/page-shape.ts';import { recordFactWithdrawal } from './withdrawal.ts';import { maintenanceTransaction } from '../persistence/attribution.ts';import { withdrawnFact } from './withdrawal-overlay.ts';@@ -181,6 +182,7 @@ export async function forgetFactInFence(const slug = row.source_markdown_slug;const page = await engine.getPage(slug, { sourceId: row.source_id });if (!page) return;+ assertInlineBody(page, 'forget fence strike');const struck = strikeFenceRow(page.compiled_truth ?? '', row.row_num, strike);if (struck === null) return;// The FILE was not rewritten on this tier, so the row must NOT keep the@@ -290,6 +292,7 @@ export async function forgetFactInFence(const reparsed = parseMarkdown(tmpBody, `${slug}.md`);const page = await engine.getPage(slug, { sourceId: row.source_id });if (page) {+ assertInlineBody(page, 'forget fence mirror');await maintenanceTransaction(engine, tx => tx.refreshPageBody(slug, row.source_id,sanitizeText(reparsed.compiled_truth), sanitizeText(reparsed.timeline),page.content_hash || contentHash(page)));diff --git a/src/core/facts/proposal-supersede.ts b/src/core/facts/proposal-supersede.tsindex ae5fe92b95..3195bd928e 100644--- a/src/core/facts/proposal-supersede.ts+++ b/src/core/facts/proposal-supersede.ts@@ -21,6 +21,7 @@ import type { BrainEngine } from '../engine.ts';import type { GBrainConfig } from '../config.ts';import { formatFenceDate, parseFactsFence, type ParsedFact } from '../facts-fence.ts';import { parseMarkdown, serializePageToMarkdown } from '../markdown.ts';+import { assertInlineBody } from '../page-body/page-shape.ts';import { sanitizeText } from '../batch-rows.ts';import { contentHash } from '../utils.ts';import { withPageLock } from '../page-lock.ts';@@ -215,6 +216,7 @@ function publishFile(filePath: string, body: string): void {async function mirrorBody(tx: BrainEngine, slug: string, sourceId: string, body: string, fromFile: boolean): Promise<string | null> {const page = await tx.getPage(slug, { sourceId });if (!page) return null;+ assertInlineBody(page, 'proposal fence mirror');if (fromFile) {const reparsed = parseMarkdown(body, `${slug}.md`);await tx.refreshPageBody(slug, sourceId, sanitizeText(reparsed.compiled_truth), sanitizeText(reparsed.timeline), page.content_hash || contentHash(page));diff --git a/src/core/facts/purge-verify.ts b/src/core/facts/purge-verify.tsindex 772bd0628b..e71088646a 100644--- a/src/core/facts/purge-verify.ts+++ b/src/core/facts/purge-verify.ts@@ -54,6 +54,19 @@ export function __setPurgeProbeLimitsForTests(limits: Partial<typeof probeLimitsprobeLimits = limits ? { ...probeLimits, ...limits } : { ...PURGE_PROBE_LIMITS };}+/**+ * Wave B PR 1: segment text is not probed yet (segment probe in PR 2), so a page-text report over a source+ * holding segmented pages is `unverified` instead of passing on NULL body columns.+ */+async function unprobedSegmentedPages(engine: BrainEngine, sourceId: string, report: StoreReport): Promise<StoreReport> {+ if (report.status === 'incomplete' || report.status === 'would_remove') return report;+ const [row] = await engine.executeRaw<{ n: number }>(`SELECT count(*)::int AS n FROM pages WHERE source_id=$1 AND deleted_at IS NULL AND body_storage='segmented'`, [sourceId]);+ const n = Number(row?.n ?? 0);+ if (!n) return report;+ return { ...report, status: 'unverified', reason: 'segmented_body',+ detail: `${n} page(s) in this source store their body in segments, which this receipt does not search yet; the claim may survive there.` };+}+type ProbeResult = { count: number } | { unverified: string };/** One bounded probe: `sql` selects matching rows (no LIMIT); the adapter caps rows and the statement time. */@@ -230,6 +243,7 @@ export async function verifyFactPurge(engine: BrainEngine, input: { target: Purgconst prose = { status: 'out_of_scope' as const, reason: 'source_prose', detail: 'The claim text survives outside a facts fence (page prose); purge the page or edit it to remove it.' };await swept('pages', `SELECT 1 FROM pages WHERE source_id=$1 AND deleted_at IS NULL AND (strpos(lower(compiled_truth),$2)>0 OR strpos(lower(timeline),$2)>0)`,[src, needle], plan.pages.length, removed.pages, prose);+ stores[stores.length - 1] = await unprobedSegmentedPages(engine, src, stores[stores.length - 1]!);await swept('content_chunks', `SELECT 1 FROM content_chunks c JOIN pages p ON p.id=c.page_id WHERE p.source_id=$1 AND strpos(lower(c.chunk_text),$2)>0`,[src, needle], plan.pages.length, removed.chunks, prose);await swept('page_versions', `SELECT 1 FROM page_versions v JOIN pages p ON p.id=v.page_id WHERE p.source_id=$1@@ -362,7 +376,7 @@ export async function verifyPagePurge(engine: BrainEngine, input: { sourceId: stif (at >= 0 && stores[at]!.status !== 'incomplete') stores[at] = report; else if (at < 0) stores.push(report);}stores.push(all.size ? { store: 'source_prose', status: 'out_of_scope', reason: 'source_prose', remaining: all.size, items: [...all].sort(),- detail: 'Other pages still state a claim from the purged page in their prose; edit or purge them.' } : { store: 'source_prose', status: 'not_present' });+ detail: 'Other pages still state a claim from the purged page in their prose; edit or purge them.' } : await unprobedSegmentedPages(engine, src, { store: 'source_prose', status: 'not_present' }));}const [source] = await engine.executeRaw<{ local_path: string | null }>('SELECT local_path FROM sources WHERE id=$1', [src]);const files = source?.local_path ? (context?.paths ?? []).filter(p => !p.startsWith('/') && !p.includes('..')).map(p => join(source.local_path!, p)) : [];diff --git a/src/core/facts/purge.ts b/src/core/facts/purge.tsindex fd246d7cc9..e116a74e81 100644--- a/src/core/facts/purge.ts+++ b/src/core/facts/purge.ts@@ -26,6 +26,7 @@ import { opError, OperationError } from '../ops/contract.ts';import { readFix } from '../ops/op-fix.ts';import { faultPoint } from '../persistence/fault-points.ts';import { contentHash, rowToPage } from '../utils.ts';+import { assertInlineBody } from '../page-body/page-shape.ts';import { discoverWithdrawalTargets, withdrawalDiscoveryFailure } from './withdrawal-discovery.ts';import { dropPurgedFenceRows } from './purge-overlay.ts';import { derivedRowsFrom, hideDerivedRows, type DerivationRef } from './derivation-inputs.ts';@@ -156,6 +157,7 @@ async function rewritePageBodies(tx: BrainEngine, sourceId: string, pages: Purgeconst rewritten: string[] = [];for (const row of rows) {const page = rowToPage(row);+ assertInlineBody(page, 'purge page rewrite');const compiled = await dropPurgedFenceRows(tx, sourceId, page.compiled_truth, page.slug);const timeline = await dropPurgedFenceRows(tx, sourceId, page.timeline ?? '', page.slug);if (compiled === page.compiled_truth && timeline === (page.timeline ?? '')) continue;diff --git a/src/core/link-reconciliation.ts b/src/core/link-reconciliation.tsindex 8439a10b86..623eeaffe8 100644--- a/src/core/link-reconciliation.ts+++ b/src/core/link-reconciliation.ts@@ -8,6 +8,7 @@ import { buildSourceLocalReferenceIndex } from './source-local-reference-index.timport { collectWantedLinks, isWantedPagesEnabled } from './wanted-links.ts';import { readLineGrammarSettings } from './line-grammar.ts';import { DerivedLinkSettingsChangedError } from './derived-links.ts';+import { isSegmentedPage } from './page-body/page-shape.ts';export interface LinkPageMetadata {slug: string;@@ -92,6 +93,11 @@ export async function reconcileSourceLinks(return result;}const page = snapshot.page;+ if (isSegmentedPage(page)) {+ result.failures.push({ originSlug, code: 'page_body_segmented' });+ result.nextAfterSlug = page.slug;+ continue;+ }const sourcesOf = makeLinkSourceResolver(page.slug, sourceId, endpoints, policy);const extracted = await extractPageLinks(page.slug, `${page.compiled_truth}\n${page.timeline}`, page.frontmatter,page.type, resolver, { pack: opts.pack, globalBasename: opts.globalBasename, lineGrammar,diff --git a/src/core/mentions/pass.ts b/src/core/mentions/pass.tsindex 0711b7771f..233ab49829 100644--- a/src/core/mentions/pass.ts+++ b/src/core/mentions/pass.ts@@ -38,6 +38,10 @@** MENTION_EXTRACTOR_VERSION is separate from LINK_EXTRACTOR_VERSION_TS, so a* gazetteer change never reruns link or timeline extraction.+ *+ * A segmented page (body in segments, NULL body columns) is never scanned:+ * mentions derived from its title alone would delete the ones its body holds.+ * It stays due, and counted as pending, until the per-segment pass.*/import { createHash } from 'node:crypto';@@ -256,7 +260,7 @@ async function refreshAliases(engine: BrainEngine, managed: boolean, sourceId: sconst pages = await engine.executeRaw<DuePage>(`SELECT p.id, p.slug, p.source_id, p.knowledge_revision::text AS revision, p.title, p.type, p.compiled_truth, p.timeline, NULL AS mention_ignore, p.frontmatterFROM pages p LEFT JOIN page_mention_state s ON s.page_id = p.id- WHERE p.source_id = $1 AND p.deleted_at IS NULL AND p.type = ANY($2::text[]) AND p.id > $3+ WHERE p.source_id = $1 AND p.deleted_at IS NULL AND p.body_storage = 'inline' AND p.type = ANY($2::text[]) AND p.id > $3AND (s.page_id IS NULL OR s.alias_revision IS DISTINCT FROM p.knowledge_revision OR s.alias_version IS DISTINCT FROM $4)ORDER BY p.id LIMIT $5`, [sourceId, types, after, ALIAS_DERIVATION_VERSION, ALIAS_BATCH]);if (!pages.length) break;@@ -323,7 +327,7 @@ async function pagesMatchingNames(engine: BrainEngine, sourceIds: string[], addeconst rows = await engine.executeRaw<{ id: number; slug: string; source_id: string; body: string; mention_ignore: unknown }>(`SELECT id, slug, source_id, COALESCE(title, '') || E'\\n\\n' || COALESCE(compiled_truth, '') || E'\\n\\n' || COALESCE(timeline, '') AS body,frontmatter->'mention_ignore' AS mention_ignore- FROM pages WHERE deleted_at IS NULL AND source_id = ANY($1::text[]) AND id > $2+ FROM pages WHERE deleted_at IS NULL AND body_storage = 'inline' AND source_id = ANY($1::text[]) AND id > $2${ascii ? `AND lower(COALESCE(title, '') || ' ' || COALESCE(compiled_truth, '') || ' ' || COALESCE(timeline, '')) LIKE ANY($4::text[])` : ''}ORDER BY id LIMIT $3`,ascii ? [sourceIds, after, PREFILTER_BATCH, patterns] : [sourceIds, after, PREFILTER_BATCH]);@@ -430,7 +434,7 @@ async function reconcileSource(engine: BrainEngine, sourceId: string, gazetteer:`SELECT p.id, p.slug, p.source_id, p.knowledge_revision::text AS revision, p.title, p.type, p.compiled_truth, p.timeline,p.frontmatter->'mention_ignore' AS mention_ignoreFROM pages p LEFT JOIN page_mention_state s ON s.page_id = p.id- WHERE p.source_id = $1 AND p.deleted_at IS NULL AND p.id > $3 AND ${DUE_PREDICATE}+ WHERE p.source_id = $1 AND p.deleted_at IS NULL AND p.body_storage = 'inline' AND p.id > $3 AND ${DUE_PREDICATE}ORDER BY p.id LIMIT $4`, [sourceId, MENTION_EXTRACTOR_VERSION, after, RECONCILE_BATCH]);if (!pages.length) return;after = pages[pages.length - 1]!.id;diff --git a/src/core/mentions/referrers.ts b/src/core/mentions/referrers.tsindex 86598c6b04..717cfcf9da 100644--- a/src/core/mentions/referrers.ts+++ b/src/core/mentions/referrers.ts@@ -22,6 +22,7 @@*/import type { BrainEngine } from '../engine.ts';+import { boundedBodyPrefixSql } from '../page-window/bounded-lead.ts';import { privateLinkOriginFilterFragment, privatePagesFilterFragment, privatePagesFilterFragmentFast } from '../search/private-visibility.ts';import { isIdentityUnionEnabled, listEntityIdentities } from '../entity-identity.ts';import { stripTakesFence } from '../takes-fence.ts';@@ -133,7 +134,7 @@ async function hydrate(engine: BrainEngine, rows: RawRow[], keep: ('private' | 'if (!rows.length) return [];const pages = new Map((await engine.executeRaw<{ id: number; title: string | null; body: string | null; date_source: string;trust_tier: string; write_origin: unknown; flagged: boolean; frontmatter: Record<string, unknown> | null }>(- `SELECT id, title, left(compiled_truth, 4000) AS body,+ `SELECT id, title, left(${boundedBodyPrefixSql('pages')}, 4000) AS body,CASE WHEN effective_date IS NULL THEN 'updated_at' ELSE COALESCE(effective_date_source, 'effective_date') END AS date_source,trust_tier, write_origin, ${activationSuppressedSql('pages', 'pages')} AS flagged, frontmatterFROM pages WHERE id = ANY($1::int[])`, [rows.map(r => r.id)])).map(r => [Number(r.id), r]));diff --git a/src/core/ops/get-page-body.ts b/src/core/ops/get-page-body.tsindex 8893fdcd19..bd54ab8cc7 100644--- a/src/core/ops/get-page-body.ts+++ b/src/core/ops/get-page-body.ts@@ -33,6 +33,7 @@ import type { OperationContext, ParamDef } from './contract.ts';import { opError, OperationError } from './contract.ts';import { invalidParam, readFix } from './op-fix.ts';import { serializePageToMarkdown } from '../markdown.ts';+import { isSegmentedPage } from '../page-body/page-shape.ts';import { deepResearchPageUrl, encodeDeepResearchId } from '../deep-research-id.ts';import { encodedFrameBytes, EGRESS_CAP_CONFIG_KEYS, egressTransport, FRAME_RESERVE_BYTES, resultByteCap } from '../egress-budget.ts';import { DEFAULT_INLINE_BODY_BYTES, chunkDocumentSpan, readPageDocument, spanHoldsChunk, type PageDocument } from '../page-window/document.ts';@@ -268,6 +269,15 @@ function setNext(out: Record<string, unknown>, page: Page, cursor: string, markdout.next = { tool: 'get_page', arguments: { slug: page.slug, source_id: page.source_id, cursor, ...(markdown ? { view: 'markdown' } : {}) } };}+/** The `body: 'none'` response: `out` plus chunk and embedding counts, no text. */+async function noneResult(ctx: OperationContext, page: Page, out: Record<string, unknown>, truncated: boolean): Promise<Record<string, unknown>> {+ const [counts] = await ctx.engine.executeRaw<{ total: unknown; embedded: unknown }>(+ `SELECT count(*) AS total, count(*) FILTER (WHERE embedded_at IS NOT NULL) AS embedded FROM content_chunks WHERE page_id = $1`, [page.id]);+ const fm = (page.frontmatter ?? {}) as Record<string, unknown>;+ return { ...out, chunks: { total: Number(counts?.total ?? 0), embedded: Number(counts?.embedded ?? 0) },+ ...(fm.embed_skip ? { embed_skip: true } : {}), truncated };+}+/*** The partial (none / outline / window / auto-above-threshold) response. Never* carries compiled_truth, timeline or content.@@ -282,6 +292,10 @@ export async function readPartialBody(ctx: OperationContext, input: PartialReadIconst omitted = quarantined?.body_omitted === true;const mode = req.mode === 'auto' ? 'outline' : req.mode;if (omitted) return { ...base, body: mode, truncated: true, body_omitted: true };+ // Wave B PR 1: a segmented body is never loaded; `none` reports its stored size (windows arrive with the segment reader).+ if (mode === 'none' && isSegmentedPage(page)) {+ return noneResult(ctx, page, { ...base, body: mode, view: req.view, body_storage: 'segmented', size: { body_bytes: Number(page.body_bytes ?? 0) } }, true);+ }const markdown = req.view === 'markdown';const doc: PageDocument = markdown@@ -294,13 +308,7 @@ export async function readPartialBody(ctx: OperationContext, input: PartialReadI};const out: Record<string, unknown> = { ...base, body: mode, view: req.view, size };- if (mode === 'none') {- const [counts] = await ctx.engine.executeRaw<{ total: unknown; embedded: unknown }>(- `SELECT count(*) AS total, count(*) FILTER (WHERE embedded_at IS NOT NULL) AS embedded FROM content_chunks WHERE page_id = $1`, [page.id]);- const fm = (page.frontmatter ?? {}) as Record<string, unknown>;- return { ...out, chunks: { total: Number(counts?.total ?? 0), embedded: Number(counts?.embedded ?? 0) },- ...(fm.embed_skip ? { embed_skip: true } : {}), truncated: doc.bytes.length > 0 };- }+ if (mode === 'none') return noneResult(ctx, page, out, doc.bytes.length > 0);if (mode === 'outline') {const limit = Math.min(MAX_OUTLINE_LIMIT, DEFAULT_OUTLINE_LIMIT);diff --git a/src/core/ops/pages.ts b/src/core/ops/pages.tsindex fce30c0054..e3cfda00fc 100644--- a/src/core/ops/pages.ts+++ b/src/core/ops/pages.ts@@ -33,6 +33,7 @@ import { listPagesPagination, listingTruncatedNotice } from './list-pages-paginaimport { OperationError, opError, type Operation, type OperationContext } from './contract.ts';import { invalidParam, readFix } from './op-fix.ts';import { isDatetimeInputError } from '../utils.ts';+import { isSegmentedPage } from '../page-body/page-shape.ts';import { rethrowNamingRevisionSource } from './put-page-revision-source.ts';import {assertExplicitSourceLive,@@ -194,7 +195,8 @@ const get_page: Operation = {// Only explicitly trusted local reads retain protected body sections.// Holder grants and page-visibility opt-outs do not bypass this boundary.const isUntrustedReader = ctx.remote !== false;- const visibleBody = isUntrustedReader+ // A segmented page keeps its throwing body getters: only body: 'none' answers it in Wave B PR 1.+ const visibleBody = isUntrustedReader && !isSegmentedPage(page)? stripPrivacyFencesForRemoteReader(page): page;// v0.42 (#1699) agent-warning channel: surface the page's content_flagdiff --git a/src/core/page-body/page-shape.ts b/src/core/page-body/page-shape.tsnew file mode 100644index 0000000000..dbf7710299--- /dev/null+++ b/src/core/page-body/page-shape.ts@@ -0,0 +1,72 @@+/**+ * Segmented page storage (Wave B): how a page object says where its body+ * lives. A segmented page (`body_storage = 'segmented'`) keeps its body in+ * `page_body_manifest` + `page_segment_texts`; its `compiled_truth` and+ * `timeline` columns are NULL. Every reader that turns a page row into a+ * `Page` (`rowToPage`, the snapshot readers) gives such a page enumerable+ * getters for the body fields that throw `page_body_segmented`, so a path+ * that needs the whole body as one string fails before it reads or writes+ * anything, and so do `{...page}`, `JSON.stringify(page)` and `structuredClone`.+ *+ * `Page` itself stays one shape (making it a union broke over a thousand+ * sites): the runtime getters and `scripts/check-page-body-readers.ts` are the+ * enforcement, not the type checker.+ */+import { opError } from '../ops/contract.ts';+import type { Page } from '../types.ts';+import type { BodyStorage } from './types.ts';++/** A segmented page as metadata: no body strings, only its size. */+export type SegmentedPage = Omit<Page, 'compiled_truth' | 'timeline'> & { body_storage: 'segmented'; body_bytes: number };++type BodyShape = { body_storage?: BodyStorage | null; body_bytes?: number | null };++/** The body fields a page-like object exposes; `content` where the object carries a rendered page. */+export type SegmentedBodyField = 'compiled_truth' | 'timeline' | 'content';++/** True when the page's body lives in segments (its body fields throw). */+export function isSegmentedPage(page: BodyShape): boolean {+ return page.body_storage === 'segmented';+}++/** The refusal every whole-body path gives a segmented page; `site` names the path in the message. */+export function pageBodySegmentedError(page: { slug?: string; source_id?: string }, site: string) {+ const slug = page.slug ?? '<unknown>';+ const sourceId = page.source_id ?? 'default';+ return opError('page_body_segmented',+ `${site}: page ${slug} (source ${sourceId}) stores its body in segments, and this path reads or writes the whole body as one string. Nothing was read or changed.`,+ "Read the page's revision and stored size with get_page body: 'none' (size.body_bytes). Windowed reads of a segmented body arrive with the segment reader; until then this path cannot process the page.",+ { fix: { argv: ['gbrain', 'get', '--source', sourceId, '--body', 'none', '--', slug],+ mcp: { tool: 'get_page', arguments: { slug, source_id: sourceId, body: 'none' } },+ consent: [], actor: 'agent', requires_exclusive: false, why: "Returns the page's revision and size without its body." } });+}++/** Throws `page_body_segmented` for a segmented page; `site` names the caller. Inline pages pass. */+export function assertInlineBody(page: BodyShape & { slug?: string; source_id?: string }, site: string): void {+ if (isSegmentedPage(page)) throw pageBodySegmentedError(page, site);+}++/**+ * UTF-8 bytes of the page body: `body_bytes` for a segmented page (its body is+ * never loaded), else the bytes of `compiled_truth` + `timeline`.+ */+export function pageBodyBytes(page: BodyShape & { compiled_truth?: string | null; timeline?: string | null }): number {+ if (isSegmentedPage(page)) return Number(page.body_bytes ?? 0);+ return Buffer.byteLength(page.compiled_truth ?? '', 'utf8') + Buffer.byteLength(page.timeline ?? '', 'utf8');+}++/**+ * Replace the body fields of a segmented page object with enumerable getters+ * and setters that throw `page_body_segmented`. Enumerable on purpose: spread,+ * `JSON.stringify` and `Object.assign` read them and throw instead of copying+ * an empty body.+ */+export function guardSegmentedBody<T extends object>(page: T, site: string,+ fields: readonly SegmentedBodyField[] = ['compiled_truth', 'timeline']): T {+ const ref = page as { slug?: string; source_id?: string };+ for (const field of fields) {+ const refuse = (): never => { throw pageBodySegmentedError(ref, `${site}.${field}`); };+ Object.defineProperty(page, field, { enumerable: true, configurable: false, get: refuse, set: refuse });+ }+ return page;+}diff --git a/src/core/page-snapshot-batch.ts b/src/core/page-snapshot-batch.tsindex a8ee3884d1..f8c4300ead 100644--- a/src/core/page-snapshot-batch.ts+++ b/src/core/page-snapshot-batch.ts@@ -25,6 +25,7 @@ import { readPageSnapshot, resolveGlobalPurges } from './page-state/snapshot.ts'import type { GlobalPurgeMarker, PageSnapshot, PageWithdrawal } from './page-state/types.ts';import { REVISION_BACKFILL_PENDING } from './page-state/types.ts';import type { ReadQuery } from './search/read-enrichment.ts';+import { isSegmentedPage } from './page-body/page-shape.ts';import { rowToPage } from './utils.ts';export const PAGE_SNAPSHOT_BATCH_MAX_BYTES = 32 * 1024 * 1024;@@ -88,8 +89,10 @@ export async function readPageSnapshotsBatch(const globalPurges: GlobalPurgeMarker = { count: Number(raw?.count ?? 0), latest: raw?.latest == null ? null : String(raw.latest), world_only: false };const withdrawals = [...row.snapshot_withdrawals as PageWithdrawal[], ...await resolveGlobalPurges(query, page.source_id, globalPurges,[String(row.fingerprint_body ?? ''), String(row.fingerprint_timeline ?? '')])];- page.compiled_truth = overlayWithdrawalBody(page.compiled_truth, String(row.fingerprint_body ?? ''), withdrawals);- page.timeline = overlayWithdrawalBody(page.timeline, String(row.fingerprint_timeline ?? ''), withdrawals);+ if (!isSegmentedPage(page)) {+ page.compiled_truth = overlayWithdrawalBody(page.compiled_truth, String(row.fingerprint_body ?? ''), withdrawals);+ page.timeline = overlayWithdrawalBody(page.timeline, String(row.fingerprint_timeline ?? ''), withdrawals);+ }snapshots.set(key, { page, tags: row.snapshot_tags as string[], revision: row.knowledge_revision == null ? REVISION_BACKFILL_PENDING : String(row.knowledge_revision),sourceIncarnation: String(row.source_incarnation), withdrawals, ...(globalPurges.count > 0 ? { globalPurges } : {}) });}diff --git a/src/core/page-state/materialize.ts b/src/core/page-state/materialize.tsindex 9584498bf8..0f451a8f4c 100644--- a/src/core/page-state/materialize.ts+++ b/src/core/page-state/materialize.ts@@ -1,5 +1,6 @@import type { BrainEngine } from '../engine.ts';import { contentHash } from '../utils.ts';+import { assertInlineBody } from '../page-body/page-shape.ts';import { assertPageRevision, type PageSnapshot } from './types.ts';import { withCoordinatedWrite } from '../persistence/context.ts';import { maintenanceAttribution } from '../persistence/attribution.ts';@@ -14,6 +15,7 @@ export async function materializePageSnapshot(engine: BrainEngine, snapshot: Pagconst current = await tx.readPageSnapshot(slug, { sourceId, includeDeleted: true });assertPageRevision(current, { expectedRevision: snapshot.revision });if (!current || current.sourceIncarnation !== snapshot.sourceIncarnation) throw new Error('Page source incarnation changed');+ assertInlineBody(current.page, 'materializePageSnapshot');const previous = await tx.executeRaw<{ revision: string | null }>("SELECT current_setting('gbrain.materializing_revision',true) AS revision");await tx.executeRaw("SELECT set_config('gbrain.materializing_revision',$1,true)", [current.revision]);// Only database-derived canonical bytes may use the bypass. Callers cannotdiff --git a/src/core/page-state/snapshot.ts b/src/core/page-state/snapshot.tsindex 236ce37b3a..b1a07f75df 100644--- a/src/core/page-state/snapshot.ts+++ b/src/core/page-state/snapshot.ts@@ -1,6 +1,7 @@import { fenceClaimHashes, overlayWithdrawalBody } from '../facts/withdrawal-overlay.ts';import { privatePagesFilterFragment } from '../search/private-visibility.ts';import type { ReadQuery } from '../search/read-enrichment.ts';+import { isSegmentedPage } from '../page-body/page-shape.ts';import { rowToPage } from '../utils.ts';import type { GlobalPurgeMarker, PageSnapshot, PageSnapshotOptions, PageWithdrawal } from './types.ts';import { PageSnapshotAmbiguousError, REVISION_BACKFILL_PENDING } from './types.ts';@@ -126,8 +127,10 @@ async function readSnapshotStatement(query: ReadQuery, slug: string, opts?: Pageconst globalPurges: GlobalPurgeMarker = { count: Number(raw?.count ?? 0), latest: raw?.latest == null ? null : String(raw.latest), world_only: opts?.excludePrivate === true };const withdrawals = [...row.snapshot_withdrawals as PageWithdrawal[], ...await resolveGlobalPurges(query, page.source_id, globalPurges,[String(row.fingerprint_body ?? ''), String(row.fingerprint_timeline ?? '')])];- page.compiled_truth = overlayWithdrawalBody(page.compiled_truth, String(row.fingerprint_body ?? ''), withdrawals);- page.timeline = overlayWithdrawalBody(page.timeline, String(row.fingerprint_timeline ?? ''), withdrawals);+ if (!isSegmentedPage(page)) {+ page.compiled_truth = overlayWithdrawalBody(page.compiled_truth, String(row.fingerprint_body ?? ''), withdrawals);+ page.timeline = overlayWithdrawalBody(page.timeline, String(row.fingerprint_timeline ?? ''), withdrawals);+ }return { page, tags: row.snapshot_tags as string[], revision: row.knowledge_revision == null ? REVISION_BACKFILL_PENDING : String(row.knowledge_revision),sourceIncarnation: String(row.source_incarnation), withdrawals, ...(globalPurges.count > 0 ? { globalPurges } : {}) };}diff --git a/src/core/page-window/bounded-lead.ts b/src/core/page-window/bounded-lead.tsindex 2928d04667..4f5bf6bca4 100644--- a/src/core/page-window/bounded-lead.ts+++ b/src/core/page-window/bounded-lead.ts@@ -14,16 +14,26 @@* snapshot read (the same overlay readPageSnapshot applies), so a withdrawn* world fact never shows in a lead. A page the snapshot read no longer* returns, or a snapshot read that fails, gets an empty lead (fail closed:- * a lead is decoration, so the row stays and only its text is withheld).+ * a lead is decoration, so the row stays and only its text is withheld). So+ * does a segmented page whose lead holds a facts fence: its overlay applies+ * per window (segment reader), not to a snapshot body.*/import type { BrainEngine } from '../engine.ts';+import { isSegmentedPage } from '../page-body/page-shape.ts';import { pageSnapshotKey } from '../page-snapshot-batch.ts';import { safeSplitIndex } from '../text-safe.ts';import { BOUNDED_PREFIX_BYTES, boundedProjectedPrefix } from './document.ts';-/** SQL for the bounded raw prefix a fan-out query selects instead of the whole column (fixed column names only). */-export function boundedPrefixSql(column: string): string {- return `left(${column}, ${BOUNDED_PREFIX_BYTES})`;+/**+ * SQL for the bounded raw prefix of a page's compiled truth that a fan-out+ * query selects instead of the whole column (fixed table aliases only). A+ * segmented page has no `compiled_truth`; its `truth_lead` holds the same raw+ * prefix, so the sanitize path downstream is unchanged. This is the one+ * sanctioned COALESCE of the body column (scripts/check-page-body-readers.ts+ * allows it by name).+ */+export function boundedBodyPrefixSql(alias: string): string {+ return `left(coalesce(${alias}.compiled_truth, ${alias}.truth_lead), ${BOUNDED_PREFIX_BYTES})`;}/** The first `maxBytes` UTF-8 bytes of a raw body, cut on a code point; nothing is sanitized. */@@ -59,7 +69,9 @@ export async function overlaidBoundedRows<T extends { slug: string; source_id: stry {for (let rest = pending; rest.length > 0;) {const batch = await engine.readPageSnapshotsBatch(rest);- for (const [key, snapshot] of batch.snapshots) overlaid.set(key, boundedRawPrefix(snapshot.page.compiled_truth));+ for (const [key, snapshot] of batch.snapshots) {+ if (!isSegmentedPage(snapshot.page)) overlaid.set(key, boundedRawPrefix(snapshot.page.compiled_truth));+ }rest = rest.slice(Math.max(1, batch.covered));}} catch {diff --git a/src/core/persistence/effect-model.ts b/src/core/persistence/effect-model.tsindex e771ce6fc8..60661ca0cb 100644--- a/src/core/persistence/effect-model.ts+++ b/src/core/persistence/effect-model.ts@@ -29,7 +29,7 @@ export function contentRepairCommit(path: string, receipt: Pick<ContentRepairRecreturn { subject: contentRepairCommitSubject(path), line: `${safe(path)} (frontmatter_slug_conflict)`, trailer: contentRepairTrailer(receipt) };}export interface ParkedTarget { slug?: string; error_code: string }-export interface SkippedTarget { slug: string; reason: 'metafile' | 'file_database_drift' }+export interface SkippedTarget { slug: string; reason: 'metafile' | 'file_database_drift' | 'page_body_segmented' }/** A Git or withdrawal target parks after this many consecutive execution failures. */export const PARK_AFTER_FAILURES = 5;export interface EffectRecovery {diff --git a/src/core/persistence/effects.ts b/src/core/persistence/effects.tsindex a0ffced3c7..8564ffdc70 100644--- a/src/core/persistence/effects.ts+++ b/src/core/persistence/effects.ts@@ -13,6 +13,7 @@ import { OperationError, opError } from '../ops/contract.ts';import { readFix } from '../ops/op-fix.ts';import type { Action } from '../agent-output.ts';import { serializePageToMarkdown } from '../markdown.ts';+import { isSegmentedPage } from '../page-body/page-shape.ts';import { isWriteTargetContained } from '../path-confine.ts';import { materializePageSnapshot } from '../page-state/materialize.ts';import { installPageEmbeddings, readProjectionSnapshot } from '../page-state/projections.ts';@@ -143,6 +144,14 @@ async function recordSkippedTarget(engine: BrainEngine, effect: PersistenceEffec[effect.id, effect.execution_token, JSON.stringify([target]), SKIPPED_TARGET_LIMIT]);}+/** Record a scan target as skipped and move past it without writing the page or its file. */+async function skipTarget(engine: BrainEngine, effect: PersistenceEffect, snapshot: PageSnapshot, reason: SkippedTarget['reason']): Promise<void> {+ await engine.transaction(async tx => {+ await recordSkippedTarget(tx, effect, { slug: snapshot.page.slug, reason });+ await finishPage(tx, effect, snapshot);+ });+}+/*** #5396: sync never imports a metafile (RESOLVER.md carries the managed durability block by design),* so its legacy page and file diverge; a scan never publishes either one to the other.@@ -166,6 +175,8 @@ async function mirrorPage(engine: BrainEngine, effect: PersistenceEffect, bindin`Source ${effect.source_id} was replaced after this withdrawal mirror was queued, so the effect ends without writing; the new source has its own effects. Check the owner if files still look stale.`,{ fix: effectStatusFix(effect) });if (isMetafilePage(snapshot)) { await materializeAndAdvance(engine, effect, snapshot, opts.hostId, 'metafile'); return; }+ // Wave B PR 1: a segmented body has no whole-body mirror yet (per-segment mirror in PR 2).+ if (isSegmentedPage(snapshot.page)) { await skipTarget(engine, effect, snapshot, 'page_body_segmented'); return; }const content = serializePageToMarkdown(snapshot.page, snapshot.tags);let file: Awaited<ReturnType<typeof prepareFileTarget>>;try {@@ -238,18 +249,15 @@ async function gitPage(engine: BrainEngine, effect: PersistenceEffect, binding:const snapshot = await selectedEffectPage(engine, effect);if (!snapshot) { await completeEffect(engine, effect); return; }attempt.target = snapshot.page.slug;- const skip = async (reason: SkippedTarget['reason']) => engine.transaction(async tx => {- await recordSkippedTarget(tx, effect, { slug: snapshot.page.slug, reason });- await finishPage(tx, effect, snapshot);- });- if (isMetafilePage(snapshot)) { await skip('metafile'); return; }+ if (isMetafilePage(snapshot)) { await skipTarget(engine, effect, snapshot, 'metafile'); return; }+ if (isSegmentedPage(snapshot.page)) { await skipTarget(engine, effect, snapshot, 'page_body_segmented'); return; }let file: Awaited<ReturnType<typeof prepareFileTarget>>;try {file = await prepareFileTarget(engine, { ...effect, slug: snapshot.page.slug }, snapshot,snapshot.page.deleted_at ? null : serializePageToMarkdown(snapshot.page, snapshot.tags), opts.hostId, { allowMissing: true });} catch (error) {if (!isFileDatabaseDrift(error)) throw error;- await skip('file_database_drift');+ await skipTarget(engine, effect, snapshot, 'file_database_drift');return;}if (!file) throw opError('source_changed', 'The Git binding changed.',diff --git a/src/core/persistence/facts-prepare.ts b/src/core/persistence/facts-prepare.tsindex 236f743121..56bf1ff072 100644--- a/src/core/persistence/facts-prepare.ts+++ b/src/core/persistence/facts-prepare.ts@@ -7,6 +7,7 @@ import type { Action } from '../agent-output.ts';import type { RegistryCode } from '../error-registry.ts';import { parseFactsFence, upsertFactRow, formatFenceDate, renderFactsTable, replaceOrInsertFactsFence } from '../facts-fence.ts';import { serializePageToMarkdown } from '../markdown.ts';+import { assertInlineBody } from '../page-body/page-shape.ts';import { assertFactNotWithdrawn, decideSingleFact, factWithdrawnRefusal, type FactCandidate } from '../facts/single-prepare.ts';import { assertFactNotPurged, isFactWithdrawn } from '../facts/withdrawal.ts';import { samePageRewording, warnSamePageShadow } from '../facts/same-page-shadow.ts';@@ -146,6 +147,7 @@ export async function prepareManagedFactsMutation(engine: BrainEngine, row: Writ`The request holds no facts, or facts attributed to a page other than ${row.slug}, so none were published.`);}// #6188 (D20): the entity's stored fence is normalized in this same write; a residual refuses typed `target_fence_malformed`.+ if (snapshot) assertInlineBody(snapshot.page, 'facts fence write');const target = snapshot ? await normalizeTargetFences(engine, { sourceId: row.source_id, slug: row.slug, kind: 'facts', page: snapshot.page }) : null;let body = target?.page.compiled_truth ?? '';const parsed = parseFactsFence(body);diff --git a/src/core/persistence/large-page-guard.ts b/src/core/persistence/large-page-guard.tsindex a5f1401e90..acd401bb2b 100644--- a/src/core/persistence/large-page-guard.ts+++ b/src/core/persistence/large-page-guard.ts@@ -3,19 +3,18 @@* a window of it. Above the inline read size a get_page read returns an* outline and windows, not the body, so a replacement must name the revision* it read (force does not stand in for it) and may not be much smaller than- * the stored body unless the caller says so with allow_shrink: true.+ * the stored body unless the caller says so with allow_shrink: true. The+ * stored size of a segmented page is its `body_bytes` (its body columns are NULL).*/import { DEFAULT_INLINE_BODY_BYTES } from '../ops/get-page-body.ts';import { opError, OperationError } from '../ops/contract.ts';+import { pageBodyBytes } from '../page-body/page-shape.ts';import type { PageSnapshot } from '../page-state/types.ts';import type { BrainEngine } from '../engine.ts';/** A replacement under this fraction of the stored body counts as a shrink. */export const SHRINK_REFUSE_FRACTION = 0.5;-const bodyBytes = (compiled: string | null | undefined, timeline: string | null | undefined) =>- Buffer.byteLength(compiled ?? '', 'utf8') + Buffer.byteLength(timeline ?? '', 'utf8');-const sizeFix = (slug: string, sourceId: string) => ({ argv: ['gbrain', 'get', '--source', sourceId, '--', slug],mcp: { tool: 'get_page', arguments: { slug, source_id: sourceId, body: 'none' } },consent: [], actor: 'agent' as const, requires_exclusive: false, why: "Returns the page's revision and size without its body." });@@ -31,7 +30,8 @@ const sizeFix = (slug: string, sourceId: string) => ({ argv: ['gbrain', 'get', 'export async function assertLargePageAdmission(engine: Pick<BrainEngine, 'executeRaw'>, slug: string, sourceId: string, intent: Record<string, unknown>): Promise<void> {if (typeof intent.content !== 'string') return;const [row] = await engine.executeRaw<{ bytes: unknown }>(- `SELECT octet_length(compiled_truth) + COALESCE(octet_length(timeline), 0) AS bytes FROM pages WHERE slug = $1 AND source_id = $2 AND deleted_at IS NULL`, [slug, sourceId]);+ `SELECT CASE WHEN body_storage = 'segmented' THEN body_bytes ELSE octet_length(compiled_truth) + COALESCE(octet_length(timeline), 0) END AS bytes+ FROM pages WHERE slug = $1 AND source_id = $2 AND deleted_at IS NULL`, [slug, sourceId]);const stored = Number(row?.bytes ?? 0);if (stored <= DEFAULT_INLINE_BODY_BYTES) return;if (intent.expected_revision === undefined && intent.force === true) {@@ -60,7 +60,7 @@ export function assertLargePageReplacement(snapshot: PageSnapshot,incoming: { compiled_truth: string; timeline?: string | null },): void {- const stored = bodyBytes(snapshot.page.compiled_truth, snapshot.page.timeline);+ const stored = pageBodyBytes(snapshot.page);if (stored <= DEFAULT_INLINE_BODY_BYTES || intent.allow_shrink === true) return;- assertNotShrunk(slug, sourceId, stored, bodyBytes(incoming.compiled_truth, incoming.timeline));+ assertNotShrunk(slug, sourceId, stored, pageBodyBytes(incoming));}diff --git a/src/core/persistence/memory-prepare.ts b/src/core/persistence/memory-prepare.tsindex 0609734916..e82b1adcc6 100644--- a/src/core/persistence/memory-prepare.ts+++ b/src/core/persistence/memory-prepare.ts@@ -7,6 +7,7 @@ import { pageIdentityError } from './page-identity.ts';import { assertPageRevision } from '../page-state/types.ts';import { parseFactsFence, renderFactsTable, replaceOrInsertFactsFence, upsertFactRow, formatFenceDate } from '../facts-fence.ts';import { serializePageToMarkdown } from '../markdown.ts';+import { assertInlineBody } from '../page-body/page-shape.ts';import { assertFactNotWithdrawn, decideReplacement, decideSingleFact, prepareFactEmbedding, type SingleFactIntent } from '../facts/single-prepare.ts';import { factEmbeddingDisabled } from '../embedding-disabled.ts';import { engineMutationPrecondition, parseMutationPrecondition } from './preconditions.ts';@@ -144,6 +145,7 @@ export async function prepareMemoryMutation(engine: BrainEngine, row: WriteRequelet rowNum: number | undefined;let fencesNormalized: Record<string, unknown> = {};if (p.fence === true && snapshot) {+ assertInlineBody(snapshot.page, 'remember facts fence write');// #6188 (D20): the stored fence is normalized in this same write; a residual refuses typed `target_fence_malformed`.const target = await normalizeTargetFences(engine, { sourceId: row.source_id, slug: row.slug, kind: 'facts', page: snapshot.page });if (target.fixes.length) fencesNormalized = { fences_normalized: pageFencesNormalized({ sourceId: row.source_id, slug: row.slug, fixes: target.fixes,diff --git a/src/core/persistence/semantic-pages.ts b/src/core/persistence/semantic-pages.tsindex d443be041b..4ff5c43ec5 100644--- a/src/core/persistence/semantic-pages.ts+++ b/src/core/persistence/semantic-pages.ts@@ -6,6 +6,7 @@ import type { BrainEngine } from '../engine.ts';import type { GBrainConfig } from '../config.ts';import { serializePageToMarkdown } from '../markdown.ts';import { opError, OperationError } from '../ops/contract.ts';+import { assertInlineBody } from '../page-body/page-shape.ts';import { pageIdentityError } from './page-identity.ts';import { renderTimelineEntry, spliceTimelineBlock } from '../timeline-write-through.ts';import { extractTimelineFromContent } from '../timeline-extract.ts';@@ -45,6 +46,7 @@ export function regeneratedByWriter(sourceKind: string | null | undefined, page:export async function prepareSemanticPageMutation(engine: BrainEngine, row: WriteRequest, config: GBrainConfig): Promise<PreparedMutation> {const snapshot = await engine.readPageSnapshot(row.slug, { sourceId: row.source_id });if (!snapshot || snapshot.page.id !== row.page_id) throw pageIdentityError(snapshot != null, 'The accepted page was replaced by another page.');+ assertInlineBody(snapshot.page, row.operation);const p = row.intent!;if (p.expected_revision !== undefined) assertPageRevision(snapshot,engineMutationPrecondition(parseMutationPrecondition(p)));if (row.operation === 'add_tag' || row.operation === 'remove_tag') {diff --git a/src/core/questions/freshness.ts b/src/core/questions/freshness.tsindex 1170629992..e15caeeca4 100644--- a/src/core/questions/freshness.ts+++ b/src/core/questions/freshness.ts@@ -27,6 +27,12 @@ export type EvidenceKind = 'page' | 'fact' | 'timeline' | 'take' | 'owner';/** Content hashes computed in SQL, identically at capture and at read. */export const FACT_HASH_SQL = (a: string) => `md5(${a}.fact || '|' || ${a}.visibility || '|' || COALESCE(${a}.entity_slug, '') || '|' || ${a}.kind)`;export const TIMELINE_HASH_SQL = (a: string) => `md5(${a}.date::text || '|' || ${a}.summary || '|' || ${a}.detail)`;+/**+ * The owner-evidence change signal of a question page: md5 of its body, or its+ * content_hash once the body is segmented (no body column to hash; a stored+ * md5 never equals it, so the owner's claims read as edited).+ */+export const OWNER_BODY_HASH_SQL = (a: string) => `CASE WHEN ${a}.body_storage = 'segmented' THEN ${a}.content_hash ELSE md5(${a}.compiled_truth) END`;export const TAKE_HASH_SQL = (a: string) => `md5(${a}.claim || '|' || ${a}.holder || '|' || COALESCE(${a}.weight::text, '') || '|' || COALESCE(${a}.resolved_outcome::text, ''))`;export interface EvaluatedSentence extends AnswerSentence {@@ -128,7 +134,7 @@ export async function evaluateAnswer(const rows = pin.answer.length === 0 ? [] : await engine.executeRaw<EvidenceJoinRow>(`SELECT e.sentence_id, e.kind, e.source_id, e.page_id, e.page_generation, e.page_revision, e.content_hash,p.id AS p_id, p.generation AS p_generation, p.knowledge_revision::text AS p_revision, p.deleted_at AS p_deleted,- s.archived AS p_source_archived, md5(p.compiled_truth) AS p_body_hash,+ s.archived AS p_source_archived, ${OWNER_BODY_HASH_SQL('p')} AS p_body_hash,f.id AS f_id, f.expired_at AS f_expired, (f.valid_until IS NOT NULL AND f.valid_until <= now()) AS f_valid_until_passed,f.superseded_by AS f_superseded, ${FACT_HASH_SQL('f')} AS f_hash,(f.id IS NOT NULL AND NOT ${quarantinedProvenanceFilterFragment('f')}) AS f_source_quarantined,diff --git a/src/core/questions/pages.ts b/src/core/questions/pages.tsindex a4d99325c6..cca832802e 100644--- a/src/core/questions/pages.ts+++ b/src/core/questions/pages.ts@@ -14,6 +14,8 @@ import type { BrainEngine } from '../engine.ts';import type { OperationContext } from '../ops/contract.ts';import type { Page } from '../types.ts';import { serializePageToMarkdown } from '../markdown.ts';+import { assertInlineBody } from '../page-body/page-shape.ts';+import type { BodyStorage } from '../page-body/types.ts';import { submitPageMutation } from '../persistence/page-mutations.ts';import { PINNED_QUESTION_MARKER, QUESTION_PAGE_TYPE, normalizeQuestion } from './identity.ts';import { pinId, pinScope, type PinRow } from './store.ts';@@ -30,11 +32,13 @@ export interface QuestionPageState {archived: boolean;}+/** A question page is inline by construction; one grown past the inline bound refuses with `page_body_segmented`. */export async function readQuestionPage(engine: BrainEngine, pin: Pick<PinRow, 'source_id' | 'slug'>): Promise<QuestionPageState | null> {- const [row] = await engine.executeRaw<{ id: number; generation: string | number; revision: string | null; compiled_truth: string; archived: boolean }>(- `SELECT id, generation, knowledge_revision::text AS revision, compiled_truth,+ const [row] = await engine.executeRaw<{ id: number; generation: string | number; revision: string | null; compiled_truth: string; archived: boolean; body_storage: BodyStorage }>(+ `SELECT id, generation, knowledge_revision::text AS revision, compiled_truth, body_storage,COALESCE(frontmatter->>'status', '') = 'archived' AS archivedFROM pages WHERE source_id = $1 AND slug = $2 AND deleted_at IS NULL`, [pin.source_id, pin.slug]);+ if (row) assertInlineBody({ ...pin, body_storage: row.body_storage }, 'readQuestionPage');return row ? { page_id: row.id, generation: Number(row.generation), revision: row.revision ?? '', compiled_truth: row.compiled_truth ?? '', archived: row.archived } : null;}diff --git a/src/core/questions/refresh.ts b/src/core/questions/refresh.tsindex 9fb38e1387..f90b08f8bd 100644--- a/src/core/questions/refresh.ts+++ b/src/core/questions/refresh.ts@@ -29,7 +29,7 @@ import { classifyLlmCallFailure } from '../think/index.ts';import { PINNED_QUESTION_MARKER, normalizeQuestion, sentenceId } from './identity.ts';import { entityAnchoredPages, prefixAnchoredPages } from '../search/entity-anchor.ts';import { quarantinedProvenanceFilterFragment, quarantineFilterFragment } from '../quarantine.ts';-import { FACT_HASH_SQL, TAKE_HASH_SQL, TIMELINE_HASH_SQL, evaluateAnswer, type EvidenceKind } from './freshness.ts';+import { FACT_HASH_SQL, OWNER_BODY_HASH_SQL, TAKE_HASH_SQL, TIMELINE_HASH_SQL, evaluateAnswer, type EvidenceKind } from './freshness.ts';import { ownerClaims, readQuestionPage } from './pages.ts';import { acquireLease, getPin, pinId, releaseLease, type AnswerSentence, type PinRow } from './store.ts';@@ -171,7 +171,8 @@ export async function retrieveEvidence(engine: BrainEngine, pin: PinRow): Promisconst candidates = slugs.size === 0 ? [] : await engine.executeRaw<CandidatePage>(`SELECT id, slug, source_id, generation, knowledge_revision::text AS revision, type, compiled_truth, updated_at,(frontmatter ? '${PINNED_QUESTION_MARKER}') AS marker- FROM pages WHERE source_id = $1 AND slug = ANY($2::text[]) AND deleted_at IS NULL AND ${quarantineFilterFragment('pages')}`, [pin.source_id, [...slugs]]);+ FROM pages WHERE source_id = $1 AND slug = ANY($2::text[]) AND deleted_at IS NULL AND body_storage = 'inline'+ AND ${quarantineFilterFragment('pages')}`, [pin.source_id, [...slugs]]);const laundered = launderingIndex(await engine.executeRaw<PublishedAnswer>(`SELECT q.answer, q.last_refresh_at AS published_at,COALESCE(array_agg(e.page_id) FILTER (WHERE e.page_id IS NOT NULL), ARRAY[]::integer[]) AS cited@@ -321,7 +322,7 @@ async function revalidate(tx: BrainEngine, rows: EvidenceRow[]): Promise<stringconst pageIds = [...new Set(pageRows.map(r => r.page_id!))];if (pageIds.length) {const current = new Map((await tx.executeRaw<{ id: number; generation: string | number; revision: string | null; deleted: boolean; body: string }>(- `SELECT id, generation, knowledge_revision::text AS revision, deleted_at IS NOT NULL AS deleted, md5(compiled_truth) AS body+ `SELECT id, generation, knowledge_revision::text AS revision, deleted_at IS NOT NULL AS deleted, ${OWNER_BODY_HASH_SQL('pages')} AS bodyFROM pages WHERE id = ANY($1::integer[]) FOR SHARE`, [pageIds])).map(r => [r.id, r]));for (const r of pageRows) {const c = current.get(r.page_id!);diff --git a/src/core/search/relational-recall.ts b/src/core/search/relational-recall.tsindex 1adbd438f9..7583e13289 100644--- a/src/core/search/relational-recall.ts+++ b/src/core/search/relational-recall.ts@@ -33,7 +33,7 @@ import { resolveEntitySlugWithSource } from '../entities/resolve.ts';import { buildVisibilityClause } from './sql-ranking.ts';import { hasReadPolicy, pageReadFilter } from './read-policy-sql.ts';import { boundedProjectedPrefix } from '../page-window/document.ts';-import { boundedPrefixSql, overlaidBoundedRows } from '../page-window/bounded-lead.ts';+import { boundedBodyPrefixSql, overlaidBoundedRows } from '../page-window/bounded-lead.ts';import { parseRelationalQuery, type RelationalQuery, type RelationVocab } from './relational-intent.ts';import { edgeValidityEnabled, type EdgeTemporalOpts } from '../link-validity.ts';import { stampEvidence, type EvidenceOpts } from './evidence.ts';@@ -190,7 +190,7 @@ async function hydrate(page_id: number; slug: string; source_id: string; title: string; type: string; synopsis: string | null;}>(`SELECT p.id AS page_id, p.slug, p.source_id, p.title, p.type,- ${boundedPrefixSql('p.compiled_truth')} AS synopsis+ ${boundedBodyPrefixSql('p')} AS synopsisFROM pages pJOIN sources s ON s.id = p.source_idJOIN unnest($1::text[], $2::text[]) AS refs(source_id, slug)diff --git a/src/core/search/safe-chunks.ts b/src/core/search/safe-chunks.tsindex 22bba5bc49..5d423ba666 100644--- a/src/core/search/safe-chunks.ts+++ b/src/core/search/safe-chunks.ts@@ -15,9 +15,15 @@ export function protectedTextFilter(expression: string): string {return `COALESCE(${expression}, '') ~ '${PROTECTED_MARKER}'`;}-/** Fixed SQL aliases only. Check full bodies because fragments can lose markers. */+/**+ * Fixed SQL aliases only. Check full bodies because fragments can lose markers.+ * A segmented page has no body columns: its `body_flags.has_protected` (set by+ * the ingest from the segmenter's regions) decides, and a page without the+ * flag counts as protected (fail closed).+ */export function protectedBodyFilter(alias: string): string {- return `(${protectedTextFilter(`${alias}.compiled_truth`)} OR ${protectedTextFilter(`${alias}.timeline`)})`;+ return `(CASE WHEN ${alias}.body_storage = 'segmented' THEN ${alias}.body_flags->>'has_protected' IS DISTINCT FROM 'false'+ ELSE (${protectedTextFilter(`${alias}.compiled_truth`)} OR ${protectedTextFilter(`${alias}.timeline`)}) END)`;}/** A body-only write cannot certify old fragments, even after fence removal. */diff --git a/src/core/sweep.ts b/src/core/sweep.tsindex c8c4515c5b..3946b1eef2 100644--- a/src/core/sweep.ts+++ b/src/core/sweep.ts@@ -55,6 +55,7 @@ import type { FactsBackstopCtx } from './facts/backstop.ts';import type { CapabilityReport } from './capability.ts';import { maintenanceTransaction } from './persistence/attribution.ts';import { managedPersistenceEnabled } from './persistence/ownership.ts';+import { isSegmentedPage } from './page-body/page-shape.ts';/** Delay before the serve-startup sweep fires (post-connect settle). */export const STARTUP_SWEEP_DELAY_MS = 3_000;@@ -386,6 +387,10 @@ async function runLinksTimelinePass(const slug = recent[i].slug;const page = await engine.getPage(slug, { sourceId });if (!page) continue;+ if (isSegmentedPage(page)) {+ skip('page_body_segmented:links_timeline');+ continue;+ }const snapshot = await engine.readPageSnapshot(slug, { sourceId });if (!snapshot || snapshot.page.compiled_truth !== page.compiled_truth || snapshot.page.timeline !== page.timeline|| snapshot.page.type !== page.type || JSON.stringify(snapshot.page.frontmatter) !== JSON.stringify(page.frontmatter)) continue;diff --git a/src/core/timeline-write-through.ts b/src/core/timeline-write-through.tsindex 106f4e0901..669065a58d 100644--- a/src/core/timeline-write-through.ts+++ b/src/core/timeline-write-through.ts@@ -1,4 +1,5 @@import { bodyWriteChunkVersion } from './search/safe-chunks.ts';+import { assertInlineBody } from './page-body/page-shape.ts';/*** #1856 — write-through for manual timeline entries.*@@ -323,6 +324,7 @@ export async function writeTimelineEntryThrough(// error instead of inventing a second error shape here.return { handled: false, skipped: 'page_not_found' };}+ assertInlineBody(page, 'timeline write-through');const rendered = renderTimelineEntry(entry, slug);if (!rendered) {diff --git a/src/core/types.ts b/src/core/types.tsindex 16dff0bd0a..07497896b5 100644--- a/src/core/types.ts+++ b/src/core/types.ts@@ -1,3 +1,5 @@+import type { BodyStorage } from './page-body/types.ts';+// Page types// v0.38: `PageType` opens from a closed 23-element union to `string`. The// closed union was always a fiction — every gbrain user accumulated organic@@ -92,6 +94,15 @@ export interface Page {timeline: string;frontmatter: Record<string, unknown>;content_hash?: string;+ /**+ * Wave B: where the body lives. On a `segmented` page `compiled_truth` and+ * `timeline` are getters that throw `page_body_segmented`+ * (`page-body/page-shape.ts`); read its size from `body_bytes`. Absent on+ * paths that do not project the column (an inline page).+ */+ body_storage?: BodyStorage;+ /** Wave B: UTF-8 bytes of truth + timeline; always set on a segmented page (`pageBodyBytes`). */+ body_bytes?: number | null;/** Source-relative canonical file identity; snapshot reads expose it for guarded import comparisons. */source_path?: string | null;/** Opaque canonical state; independent of indexing and telemetry updates. */diff --git a/src/core/utils.ts b/src/core/utils.tsindex 4dd5edddc2..33437f5d61 100644--- a/src/core/utils.ts+++ b/src/core/utils.ts@@ -6,6 +6,8 @@ import type { StaleTakeRow } from './takes-row-types.ts';// truth for the hash-ephemeral frontmatter keys shared with the importer.import { QUARANTINE_KEY, CONTENT_FLAG_KEY } from './quarantine.ts';import { EMBED_SKIP_KEY } from './embed-skip.ts';+import { guardSegmentedBody } from './page-body/page-shape.ts';+import type { BodyStorage } from './page-body/types.ts';/*** SHA-256 hash a token/secret for storage. Never store plaintext tokens.@@ -217,15 +219,18 @@ export function rowToPage(row: Record<string, unknown>): Page {const contextualRetrievalMode = row.contextual_retrieval_mode === undefined? undefined: (row.contextual_retrieval_mode as Page['contextual_retrieval_mode']);- return {+ const segmented = row.body_storage === 'segmented';+ const page: Page = {id: row.id as number,slug: row.slug as string,type: row.type as string,title: row.title as string,- compiled_truth: row.compiled_truth as string,- timeline: row.timeline as string,+ compiled_truth: segmented ? '' : row.compiled_truth as string,+ timeline: segmented ? '' : row.timeline as string,frontmatter: (typeof row.frontmatter === 'string' ? JSON.parse(row.frontmatter) : row.frontmatter) as Record<string, unknown>,content_hash: row.content_hash as string | undefined,+ ...(row.body_storage !== undefined && { body_storage: row.body_storage as BodyStorage }),+ ...(row.body_bytes !== undefined && { body_bytes: row.body_bytes == null ? null : Number(row.body_bytes) }),...(row.source_path !== undefined && { source_path: row.source_path as string | null }),...(row.knowledge_revision != null && { knowledge_revision: String(row.knowledge_revision) }),...(row.text_projection_revision !== undefined && { text_projection_revision: row.text_projection_revision as string | null }),@@ -260,6 +265,7 @@ export function rowToPage(row: Record<string, unknown>): Page {// silently mis-attribute).source_id: (row.source_id as string | undefined) ?? 'default',};+ return segmented ? guardSegmentedBody(page, 'rowToPage') : page;}/**diff --git a/src/core/verbs/entity-card.ts b/src/core/verbs/entity-card.tsindex f510419ca8..a23174a2f5 100644--- a/src/core/verbs/entity-card.ts+++ b/src/core/verbs/entity-card.ts@@ -39,7 +39,7 @@ import { readMentionCoverage, type MentionCoverage } from '../mentions/coverage.import { encodeCursor, readReferrerGroups, PAGE_DEFAULT_LIMIT, type ReferenceRow } from '../mentions/referrers.ts';import { readCardIdentity, type CardIdentity } from './entity-card-identity.ts';import { factEntitySlugs } from '../mentions/siblings.ts';-import { boundedPrefixSql, overlaidBoundedRows } from '../page-window/bounded-lead.ts';+import { boundedBodyPrefixSql, overlaidBoundedRows } from '../page-window/bounded-lead.ts';const EDGE_CAP = 10;const OPEN_THREADS_CAP = 3;@@ -277,7 +277,7 @@ export async function selectEntityCandidates(let rows: CardPageRow[] = [];try {rows = await engine.executeRaw<CardPageRow>(- `SELECT slug, source_id, title, type, frontmatter, ${boundedPrefixSql('compiled_truth')} AS compiled_truth, updated_at,+ `SELECT slug, source_id, title, type, frontmatter, ${boundedBodyPrefixSql('pages')} AS compiled_truth, updated_at,GREATEST(last_retrieved_at, (SELECT r.last_retrieved_at FROM page_retrievals r WHERE r.page_id = pages.id)) AS last_retrieved_atFROM pagesWHERE deleted_at IS NULL@@ -302,7 +302,7 @@ export async function selectEntityCandidates(if (missing.length) {try {const extra = await engine.executeRaw<CardPageRow>(- `SELECT slug, source_id, title, type, frontmatter, ${boundedPrefixSql('compiled_truth')} AS compiled_truth, updated_at,+ `SELECT slug, source_id, title, type, frontmatter, ${boundedBodyPrefixSql('pages')} AS compiled_truth, updated_at,GREATEST(last_retrieved_at, (SELECT r.last_retrieved_at FROM page_retrievals r WHERE r.page_id = pages.id)) AS last_retrieved_atFROM pagesWHERE deleted_at IS NULL AND source_id = $1 AND slug = ANY($2::text[])${privatePredicate}`,diff --git a/src/core/verbs/entity-names.ts b/src/core/verbs/entity-names.tsindex 5cec71f2bf..53c5fb1e8e 100644--- a/src/core/verbs/entity-names.ts+++ b/src/core/verbs/entity-names.ts@@ -17,7 +17,7 @@ import type { BrainEngine } from '../engine.ts';import { entityLookupScope, readAka, selectEntityCandidates, type EntityLookupScope } from './entity-card.ts';import { readSiblingIdentity } from './entity-card-identity.ts';import { boundedProjectedPrefix } from '../page-window/document.ts';-import { boundedPrefixSql, overlaidBoundedRows } from '../page-window/bounded-lead.ts';+import { boundedBodyPrefixSql, overlaidBoundedRows } from '../page-window/bounded-lead.ts';import { redactFindings } from '../secret-scan.ts';export const ENTITY_NAMES_MAX = 50;@@ -66,7 +66,7 @@ async function lookupOne(engine: BrainEngine, sourceId: string, name: string, scconst bodies = new Map<string, string | null>([[row.slug, row.compiled_truth]]);if (siblingPages.length) {const sib = await engine.executeRaw<{ slug: string; source_id: string; compiled_truth: string | null }>(- `SELECT slug, source_id, ${boundedPrefixSql('compiled_truth')} AS compiled_truth FROM pages WHERE source_id = $1 AND slug = ANY($2::text[]) AND deleted_at IS NULL`,+ `SELECT slug, source_id, ${boundedBodyPrefixSql('pages')} AS compiled_truth FROM pages WHERE source_id = $1 AND slug = ANY($2::text[]) AND deleted_at IS NULL`,[sourceId, siblingPages.map(p => p.slug)]).catch(() => []);for (const s of await overlaidBoundedRows(engine, sib)) bodies.set(s.slug, s.compiled_truth);}diff --git a/test/bounded-lead.test.ts b/test/bounded-lead.test.tsindex e945684a46..744cfa67af 100644--- a/test/bounded-lead.test.ts+++ b/test/bounded-lead.test.ts@@ -23,7 +23,7 @@ import { stripFactsFence } from '../src/core/facts-fence.ts';import { redactFindings } from '../src/core/secret-scan.ts';import { sanitizeRemoteBody } from '../src/core/remote-body.ts';import { BOUNDED_PREFIX_BYTES } from '../src/core/page-window/document.ts';-import { boundedPrefixSql, boundedRawPrefix, overlaidBoundedRows, prefixNeedsOverlay, projectedLead } from '../src/core/page-window/bounded-lead.ts';+import { boundedBodyPrefixSql, boundedRawPrefix, overlaidBoundedRows, prefixNeedsOverlay, projectedLead } from '../src/core/page-window/bounded-lead.ts';import { structuralExactLookup } from '../src/core/search/exact-lookup.ts';import { applyAliasHop } from '../src/core/search/alias-hop.ts';import { normalizeAlias } from '../src/core/search/alias-normalize.ts';@@ -115,13 +115,13 @@ afterAll(async () => { await engine.disconnect(); });const pageBody = async (slug: string) => (await engine.getPage(slug, { sourceId: 'default' }))!.compiled_truth;describe('bounded-lead building blocks', () => {- test('boundedRawPrefix cuts on a code point within the byte budget; boundedPrefixSql bounds the column', () => {+ test('boundedRawPrefix cuts on a code point within the byte budget; boundedBodyPrefixSql bounds the column or its lead', () => {const body = 'é'.repeat(BOUNDED_PREFIX_BYTES);const prefix = boundedRawPrefix(body);expect(Buffer.byteLength(prefix, 'utf8')).toBeLessThanOrEqual(BOUNDED_PREFIX_BYTES);expect(prefix).toBe('é'.repeat(prefix.length));expect(boundedRawPrefix('short')).toBe('short');- expect(boundedPrefixSql('p.compiled_truth')).toBe(`left(p.compiled_truth, ${BOUNDED_PREFIX_BYTES})`);+ expect(boundedBodyPrefixSql('p')).toBe(`left(coalesce(p.compiled_truth, p.truth_lead), ${BOUNDED_PREFIX_BYTES})`);expect(prefixNeedsOverlay('x <!--- gbrain:facts:begin -->')).toBe(true);expect(prefixNeedsOverlay(small('x').replace(FACTS, ''))).toBe(false);});diff --git a/test/fixtures/guards/check-page-body-readers.ts/bad-stale/scripts/page-body-readers-baseline.tsv b/test/fixtures/guards/check-page-body-readers.ts/bad-stale/scripts/page-body-readers-baseline.tsvnew file mode 100644index 0000000000..81d412290b--- /dev/null+++ b/test/fixtures/guards/check-page-body-readers.ts/bad-stale/scripts/page-body-readers-baseline.tsv@@ -0,0 +1,3 @@+# fixture baseline+src/core/reader.ts readBody field INLINE inline by construction+src/core/reader.ts removed call:putPage SEGWdiff --git a/test/fixtures/guards/check-page-body-readers.ts/bad-stale/src/core/reader.ts b/test/fixtures/guards/check-page-body-readers.ts/bad-stale/src/core/reader.tsnew file mode 100644index 0000000000..d38527cc32--- /dev/null+++ b/test/fixtures/guards/check-page-body-readers.ts/bad-stale/src/core/reader.ts@@ -0,0 +1,9 @@+export function boundedBodyPrefixSql(alias: string): string {+ return `left(coalesce(${alias}.compiled_truth, ${alias}.truth_lead), 65536)`;+}++export function readBody(page: { compiled_truth: string }): string {+ return page.compiled_truth;+}++export const leadSql = `SELECT ${boundedBodyPrefixSql('p')} AS lead, p.chunk_source = 'timeline' AS t FROM pages p WHERE p.id = $1`;diff --git a/test/fixtures/guards/check-page-body-readers.ts/bad/scripts/page-body-readers-baseline.tsv b/test/fixtures/guards/check-page-body-readers.ts/bad/scripts/page-body-readers-baseline.tsvnew file mode 100644index 0000000000..386839c660--- /dev/null+++ b/test/fixtures/guards/check-page-body-readers.ts/bad/scripts/page-body-readers-baseline.tsv@@ -0,0 +1,2 @@+# fixture baseline+src/core/reader.ts readBody field INLINE inline by constructiondiff --git a/test/fixtures/guards/check-page-body-readers.ts/bad/src/core/reader.ts b/test/fixtures/guards/check-page-body-readers.ts/bad/src/core/reader.tsnew file mode 100644index 0000000000..f41422e68f--- /dev/null+++ b/test/fixtures/guards/check-page-body-readers.ts/bad/src/core/reader.ts@@ -0,0 +1,13 @@+export function boundedBodyPrefixSql(alias: string): string {+ return `left(coalesce(${alias}.compiled_truth, ${alias}.truth_lead), 65536)`;+}++export function readBody(page: { compiled_truth: string }): string {+ return page.compiled_truth;+}++export const leadSql = `SELECT ${boundedBodyPrefixSql('p')} AS lead, p.chunk_source = 'timeline' AS t FROM pages p WHERE p.id = $1`;++export function unlisted(page: { timeline: string }): string {+ return page.timeline;+}diff --git a/test/fixtures/guards/check-page-body-readers.ts/good/scripts/page-body-readers-baseline.tsv b/test/fixtures/guards/check-page-body-readers.ts/good/scripts/page-body-readers-baseline.tsvnew file mode 100644index 0000000000..386839c660--- /dev/null+++ b/test/fixtures/guards/check-page-body-readers.ts/good/scripts/page-body-readers-baseline.tsv@@ -0,0 +1,2 @@+# fixture baseline+src/core/reader.ts readBody field INLINE inline by constructiondiff --git a/test/fixtures/guards/check-page-body-readers.ts/good/src/core/reader.ts b/test/fixtures/guards/check-page-body-readers.ts/good/src/core/reader.tsnew file mode 100644index 0000000000..d38527cc32--- /dev/null+++ b/test/fixtures/guards/check-page-body-readers.ts/good/src/core/reader.ts@@ -0,0 +1,9 @@+export function boundedBodyPrefixSql(alias: string): string {+ return `left(coalesce(${alias}.compiled_truth, ${alias}.truth_lead), 65536)`;+}++export function readBody(page: { compiled_truth: string }): string {+ return page.compiled_truth;+}++export const leadSql = `SELECT ${boundedBodyPrefixSql('p')} AS lead, p.chunk_source = 'timeline' AS t FROM pages p WHERE p.id = $1`;diff --git a/test/scripts/check-page-body-readers.test.ts b/test/scripts/check-page-body-readers.test.tsnew file mode 100644index 0000000000..c1f43a2ee6--- /dev/null+++ b/test/scripts/check-page-body-readers.test.ts@@ -0,0 +1,133 @@+/**+ * Wave B segmented storage (spec 1.5 layer 4): scripts/check-page-body-readers.ts+ * fails on a new whole-body page reader with no baseline row, on stale,+ * duplicate and malformed rows, and lets boundedBodyPrefixSql through by+ * name. The repo's own tree passes against the committed baseline.+ */+import { afterEach, describe, expect, test } from 'bun:test';+import { spawnSync } from 'node:child_process';+import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join, resolve } from 'node:path';+import { namesBodyColumn } from '../../scripts/check-page-body-readers.ts';++const REPO = resolve(import.meta.dir, '..', '..');+const GUARD = join(REPO, 'scripts', 'check-page-body-readers.ts');+const BASELINE = 'scripts/page-body-readers-baseline.tsv';+const dirs: string[] = [];+afterEach(() => {+ for (const d of dirs.splice(0)) rmSync(d, { recursive: true, force: true });+});++function tree(files: Record<string, string>, baseline: string[] = []): string {+ const root = mkdtempSync(join(tmpdir(), 'gbrain-page-body-readers-'));+ dirs.push(root);+ for (const [rel, body] of Object.entries({ [BASELINE]: ['# baseline', ...baseline, ''].join('\n'), ...files })) {+ mkdirSync(join(root, rel, '..'), { recursive: true });+ writeFileSync(join(root, rel), body);+ }+ return root;+}++function run(root: string, args: string[] = []) {+ const r = spawnSync('bun', [GUARD, ...args], { encoding: 'utf8', env: { ...process.env, GBRAIN_GUARD_ROOT: root } });+ return { code: r.status, out: `${r.stdout}\n${r.stderr}` };+}++const flagged = (out: string) => [...out.matchAll(/new page body reader in (\S+) \((\S+)\)/g)].map((m) => `${m[1]} ${m[2]}`).sort();++describe('check-page-body-readers.ts: detection', () => {+ test('every reader form is flagged, keyed by unit and kind', () => {+ const root = tree({+ 'src/core/readers.ts': [+ 'export function field(p: { compiled_truth: string }) { return p.compiled_truth; }',+ 'export function element(p: Record<string, string>) { return p["timeline"]; }',+ 'export function destructure(p: { compiled_truth: string; timeline: string }) { const { timeline } = p; return timeline; }',+ 'export function qualifiedColumn() { return "left(p.compiled_truth, 10)"; }',+ 'export function bareColumn() { return "SELECT compiled_truth FROM pages WHERE id = $1"; }',+ 'export function starFromPages() { return "SELECT p.* FROM pages p WHERE p.slug = $1"; }',+ 'declare const engine: { putPage(...a: unknown[]): void };',+ 'export function writer() { engine.putPage("a", {}); }',+ 'declare function serializePageToMarkdown(...a: unknown[]): string;',+ 'export class Engine { render() { return serializePageToMarkdown({}, []); } }',+ 'if (import.meta.main) console.log("x".length, ({} as { timeline: string }).timeline);',+ ].join('\n'),+ });+ const r = run(root);+ expect(r.code).toBe(1);+ expect(flagged(r.out)).toEqual([+ '<module> field', 'Engine.render call:serializePageToMarkdown', 'bareColumn sql', 'destructure field', 'element field', 'field field',+ 'qualifiedColumn sql', 'starFromPages sql', 'writer call:putPage',+ ]);+ });++ test('quoted values, other tables, prose and generated files are not readers; boundedBodyPrefixSql is allowed by name', () => {+ expect(namesBodyColumn("SELECT id FROM content_chunks WHERE chunk_source = 'compiled_truth'")).toBe(false);+ expect(namesBodyColumn("SELECT * FROM timeline_entries WHERE page_id = $1")).toBe(false);+ expect(namesBodyColumn('compiled_truth')).toBe(false);+ expect(namesBodyColumn('the timeline of a page')).toBe(false);+ expect(namesBodyColumn('SELECT timeline FROM pages WHERE id = $1')).toBe(true);+ const root = tree({+ 'src/core/lead.ts': [+ 'export function boundedBodyPrefixSql(alias: string): string {',+ ' return `left(coalesce(${alias}.compiled_truth, ${alias}.truth_lead), 65536)`;',+ '}',+ "export const leadSql = `SELECT ${boundedBodyPrefixSql('p')} AS lead FROM pages p WHERE p.id = $1`;",+ "export const chunkSql = \"SELECT id FROM content_chunks WHERE chunk_source = 'timeline' AND page_id = $1\";",+ ].join('\n'),+ 'src/core/schema.generated.ts': 'export const s = "SELECT compiled_truth FROM pages WHERE id = $1";',+ });+ const r = run(root);+ expect(r.out).toContain('check-page-body-readers: ok (0 baseline rows)');+ expect(r.code).toBe(0);+ });+});++describe('check-page-body-readers.ts: baseline rules', () => {+ const reader = { 'src/core/reader.ts': 'export function readBody(p: { compiled_truth: string }) { return p.compiled_truth; }\n' };++ test('a listed reader passes', () => {+ const r = run(tree(reader, ['src/core/reader.ts\treadBody\tfield\tINLINE\tinline by construction']));+ expect(r.out).toContain('check-page-body-readers: ok (1 baseline rows)');+ expect(r.code).toBe(0);+ });++ test('a new unlisted reader fails and names its file, line and unit', () => {+ const r = run(tree({ ...reader, 'src/core/new.ts': 'export function grow(p: { timeline: string }) {\n return p.timeline;\n}\n' },+ ['src/core/reader.ts\treadBody\tfield\tINLINE\t']));+ expect(r.code).toBe(1);+ expect(r.out).toContain('src/core/new.ts:2 new page body reader in grow (field)');+ expect(r.out).toContain('See: docs/TESTING.md#page-body-readers');+ });++ test('a removed reader leaves a stale row that fails; --prune drops it and nothing else', () => {+ const root = tree(reader, ['src/core/reader.ts\treadBody\tfield\tINLINE\t', 'src/core/reader.ts\tgone\tcall:putPage\tSEGW\t']);+ const r = run(root);+ expect(r.code).toBe(1);+ expect(r.out).toContain(`${BASELINE}:3 stale row: src/core/reader.ts gone call:putPage no longer reads the body`);+ expect(run(root, ['--prune']).code).toBe(0);+ expect(readFileSync(join(root, BASELINE), 'utf8')).toBe('# baseline\nsrc/core/reader.ts\treadBody\tfield\tINLINE\t\n');+ expect(run(root).code).toBe(0);+ });++ test('duplicate, malformed, unknown-action and note-less NONE rows fail', () => {+ const r = run(tree(reader, [+ 'src/core/reader.ts\treadBody\tfield\tINLINE\t',+ 'src/core/reader.ts\treadBody\tfield\tINLINE\t',+ 'src/core/reader.ts\treadBody',+ 'src/core/reader.ts\tother\tfield\tMAYBE\t',+ 'src/core/reader.ts\tthird\tfield\tNONE\t',+ ]));+ expect(r.code).toBe(1);+ expect(r.out).toContain(`${BASELINE}:3 duplicate row`);+ expect(r.out).toContain(`${BASELINE}:4 malformed row`);+ expect(r.out).toContain("unknown action 'MAYBE'");+ expect(r.out).toContain('a NONE row needs a note');+ });++ test('the repository tree passes against the committed baseline', () => {+ const r = spawnSync('bun', [GUARD], { encoding: 'utf8', cwd: REPO, env: { ...process.env, GBRAIN_GUARD_ROOT: REPO } });+ expect(`${r.stdout}${r.stderr}`).toContain('check-page-body-readers: ok');+ expect(r.status).toBe(0);+ });+});