Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
Segmented pages: chronicle decision/execution and links/facts effects skip or materialize instead of throwing
garrytan1a1e1caf676e
diff --git a/docs/architecture/key-files/core-persistence.md b/docs/architecture/key-files/core-persistence.mdindex 3c9e50a4a1..3bb4c3e9cb 100644--- a/docs/architecture/key-files/core-persistence.md+++ b/docs/architecture/key-files/core-persistence.md@@ -30,7 +30,7 @@ Managed facts extraction (withdrawn-candidate skip and recovery, conversation fa- `src/core/persistence/health.ts` — pure advisory age/reason/action policy shared by receipts and trusted diagnostics. The nested public contract is optional, validated and explicitly allowlisted; thresholds are 30/120 seconds and polls 1/5/30 seconds. The journal batches at most 100 authorized receipts into one projected root query with a 500ms caller budget, retaining one in-flight query per engine until settlement. Database-only pending lookups use a partial source-incarnation/sequence index shared by both engines. Synchronous service reads coalesce only for the same request ID, retain at most four unresolved reads per engine until settlement, and permit cancellation only by the read's initiating waiter or shutdown. No health observation changes authority or durable state. Real authenticated legacy/OAuth recovery and the synthetic three-client import live in `test/e2e/persistence-http-liveness.test.ts`.-- `src/core/persistence/effect-facts.ts` + `page-advisories.ts` + `derived-extraction-gate.ts` — bounded writer-lint/facts-backstop outbox. `dispatchFactsBackstopEffect` stamps the job's `notabilityFilter` from `facts.page_write_notability_filter` (default `all`; `facts/notability-filter.ts`), read inside the dispatch transaction so retries keep one filter (#6231). `derivedExtractionSkip` is the writer-confinement rule facts and Life Chronicle share (slug-bound/delegated/restricted → `slug_bound_client`; an operation-bound grant without `extract_facts` → `operation_bound_client`). Eligibility, anti-loop, selected configuration, original/current grants and source/page revision guards precede scheduling; a write that keeps the `compiled_truth` (the only text extraction reads) of a live, already-eligible page skips with `body_unchanged` only when a facts-absorb job bound to that page id has completed and no facts-backstop effect or startable facts-absorb job for it is still pending (the new revision would supersede it), so a timeline or frontmatter-only republish such as `repair timeline` queues no extraction for an extracted page, while a page no extraction ever completed for still queues one. Page publication records the effect; job insertion and completion use its stable idempotency key. Managed backstop retains the committed original page request as the facts-absorb job authority, including OAuth/stdio origin; no fabricated CLI authority or blanket managed skip. Legacy unsupported raw queue/fence paths remain refused. Tests: `test/persistence-facts-backstop.test.ts`, `test/managed-facts-backstop.test.ts`.+- `src/core/persistence/effect-facts.ts` + `page-advisories.ts` + `derived-extraction-gate.ts` — bounded writer-lint/facts-backstop outbox. `dispatchFactsBackstopEffect` stamps the job's `notabilityFilter` from `facts.page_write_notability_filter` (default `all`; `facts/notability-filter.ts`), read inside the dispatch transaction so retries keep one filter (#6231). `derivedExtractionSkip` is the writer-confinement rule facts and Life Chronicle share (slug-bound/delegated/restricted → `slug_bound_client`; an operation-bound grant without `extract_facts` → `operation_bound_client`). Eligibility, anti-loop, selected configuration, original/current grants and source/page revision guards precede scheduling; a write that keeps the `compiled_truth` (the only text extraction reads) of a live, already-eligible page skips with `body_unchanged` only when a facts-absorb job bound to that page id has completed and no facts-backstop effect or startable facts-absorb job for it is still pending (the new revision would supersede it), so a timeline or frontmatter-only republish such as `repair timeline` queues no extraction for an extracted page, while a page no extraction ever completed for still queues one. Wave B: a write stored segmented (`stringWriteStorage`) skips with `page_body_segmented` and queues no effect, and `readFactsBackstopJobPage` returns that skip for a segmented page, so a facts-absorb job never reads its throwing body (`test/large-pages/segmented-derived-work.test.ts`). Page publication records the effect; job insertion and completion use its stable idempotency key. Managed backstop retains the committed original page request as the facts-absorb job authority, including OAuth/stdio origin; no fabricated CLI authority or blanket managed skip. Legacy unsupported raw queue/fence paths remain refused. Tests: `test/persistence-facts-backstop.test.ts`, `test/managed-facts-backstop.test.ts`.- `src/core/persistence/effect-recovery-scan.ts` — bounded owner-scoped recovery selection rotates through durable effect IDs even when an earlier root has no available native lock, and wraps to retry prior roots. It never changes recovery authority or releases reservations. `test/persistence-effect-recovery-fairness.test.ts` holds two real native roots, recovers a later mirror, then verifies wraparound cleanup and exact counters on both engines.diff --git a/docs/guides/error-codes.md b/docs/guides/error-codes.mdindex 53a974100b..b2cc2fe711 100644--- a/docs/guides/error-codes.md+++ b/docs/guides/error-codes.md@@ -436,7 +436,7 @@ More: [docs/guides/shared-brain-skills.md#troubleshoot-leave-and-recover](../../|---|---|---|---|---|---|---|| Automatic event extraction (auto_chronicle) skipped or failed this page; `reason` says why and `fix`, when present, is the next step. | A capability this request needs is not configured or not reachable on this brain. | Read the receipt or doctor `auto_chronicle` check: its `why` explains the reason and its `fix`, when present, is the next step (paid fixes need the user's agreement). | agent | `gbrain doctor --json` | 1 | no |-Reasons: `auto_chronicle_off`, `auto_chronicle_invalid`, `slug_bound_client`, `operation_bound_client`, `no_extract`, `history`, `not_yet_happened`, `too_short`, `dream_generated`, `no_write_decision`, `not_chronicle_shaped`, `already_extracted`, `superseded`, `daily_limit`, `judge_llm_unavailable`, `no_pricing`, `budget_exhausted`, `campaign_exhausted`, `judge_chat_error`, `judge_truncated`, `judge_parse_failed`, `malformed_proposal`, `publish_error`, `judge_refused`, `page_missing`, `no_events`, `future_dated`, `date_imprecise`, `no_chat_provider`.+Reasons: `auto_chronicle_off`, `auto_chronicle_invalid`, `slug_bound_client`, `operation_bound_client`, `no_extract`, `history`, `not_yet_happened`, `too_short`, `dream_generated`, `page_body_segmented`, `no_write_decision`, `not_chronicle_shaped`, `already_extracted`, `superseded`, `daily_limit`, `judge_llm_unavailable`, `no_pricing`, `budget_exhausted`, `campaign_exhausted`, `judge_chat_error`, `judge_truncated`, `judge_parse_failed`, `malformed_proposal`, `publish_error`, `judge_refused`, `page_missing`, `no_events`, `future_dated`, `date_imprecise`, `no_chat_provider`.More: [docs/guides/life-chronicle.md#skip-and-failure-codes](../../docs/guides/life-chronicle.md#skip-and-failure-codes)diff --git a/docs/guides/life-chronicle.md b/docs/guides/life-chronicle.mdindex 2cf7f63f03..14625128a1 100644--- a/docs/guides/life-chronicle.md+++ b/docs/guides/life-chronicle.md@@ -254,6 +254,7 @@ brackets are filled in with real values on each surface.| `not_yet_happened` | decision | The calendar event has not ended yet; it is picked up automatically after its end time, with no edit needed. | — | — | — || `too_short` | decision | The page body is under 80 characters, too short to hold events. | — | — | — || `dream_generated` | decision | Dream-generated pages are never mined for events. | — | — | — |+| `page_body_segmented` | decision | The page body is over the 24 MiB single-string ceiling and is stored in segments; extraction reads the whole body as one string, so it skips this page. | — | — | — || `no_write_decision` | discovery | This revision has no recorded write decision (written by an older binary or before this release activated), so only a trusted backfill extracts it. | `gbrain chronicle-backfill --source <source> --since <YYYY-MM-DD> --limit 50 --yes` (preview: `gbrain chronicle-backfill --source <source> --since <YYYY-MM-DD> --limit 50 --dry-run`) | agent | paid || `not_chronicle_shaped` | decision | The page is no longer a meeting, conversation or calendar page, so the events extracted from it were retired. | — | — | — || `already_extracted` | decision | This exact content was already extracted; its events are current, so no new call is made. | — | — | — |diff --git a/docs/guides/windowed-reads.md b/docs/guides/windowed-reads.mdindex 318ffa8272..bf46a0fb09 100644--- a/docs/guides/windowed-reads.md+++ b/docs/guides/windowed-reads.md@@ -98,9 +98,10 @@ writes the whole body as one string. It stopped before reading or changinganything, 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.+reader. Queue work (fact reconcile, the facts backstop, link and mention+passes, effect scans) skips a segmented page with this code as its logged+reason instead of stopping. Life Chronicle extraction reads a segmented page+up to 24 MiB as one string and skips a larger one with this code.## page_shrink_refuseddiff --git a/src/core/chronicle/backfill.ts b/src/core/chronicle/backfill.tsindex 44c20dee91..9f9ddb186e 100644--- a/src/core/chronicle/backfill.ts+++ b/src/core/chronicle/backfill.ts@@ -140,7 +140,7 @@ export async function runChronicleBackfill(engine: BrainEngine, opts: ChronicleBid: number; source_id: string; slug: string; type: string; compiled_truth: string | null; frontmatter: Record<string, unknown> | null;effective_date: Date | string | null; effective_date_source: string | null; content_hash: string | null; done: boolean;}>(- `SELECT p.id, p.source_id, p.slug, p.type, p.compiled_truth, p.frontmatter, p.effective_date, p.effective_date_source, p.content_hash,+ `SELECT p.id, p.source_id, p.slug, p.type, coalesce(p.compiled_truth, p.truth_lead) AS compiled_truth, p.frontmatter, p.effective_date, p.effective_date_source, p.content_hash,EXISTS (SELECT 1 FROM chronicle_page_state c WHERE c.page_id=p.id AND c.content_hash=p.content_hashAND c.extractor_version=$3 AND (c.state='extracted' OR (c.state IN ('pending','failed') AND c.trigger='backfill' AND c.attempts < ${CHRONICLE_DEFAULTS.maxAttempts}))) AS doneFROM pages pdiff --git a/src/core/chronicle/execute.ts b/src/core/chronicle/execute.tsindex db6d78e331..4e0ac3529d 100644--- a/src/core/chronicle/execute.ts+++ b/src/core/chronicle/execute.ts@@ -18,6 +18,9 @@ import { recordOnTracker } from '../ai/budget-record.ts';import { getCurrentBudgetTracker, withBudgetTracker } from '../ai/gateway.ts';import type { ExtractAtomsCostGate } from '../cycle/extract-atoms-cost-gate.ts';import type { MaintenanceAuthority } from '../persistence/prepared-maintenance.ts';+import { materializedPage } from '../persistence/segmented-apply.ts';+import { isSegmentedPage, pageBodyBytes } from '../page-body/page-shape.ts';+import { PAGE_MAX_BYTES } from '../page-size-policy.ts';import { CHRONICLE_DEFAULTS, CHRONICLE_EXTRACTOR_VERSION, type ChronicleLedgerRow } from './contract.ts';import type { ChronicleReasonCode } from './reasons.ts';import type { ChronicleSettings } from './config.ts';@@ -175,12 +178,17 @@ export async function executeChronicleRow(ctx: ChronicleExecContext, row: Chroniawait finish(engine, row, row.attempts, { state: 'skipped', reason: 'no_extract', nextAttemptAt: null });return done('skipped', 'no_extract');}+ if (isSegmentedPage(snapshot.page) && pageBodyBytes(snapshot.page) > PAGE_MAX_BYTES) {+ await finish(engine, row, row.attempts, { state: 'skipped', reason: 'page_body_segmented', nextAttemptAt: null });+ return done('skipped', 'page_body_segmented');+ }+ const page = await materializedPage(engine, snapshot.page);const auto = row.trigger === 'auto';const eligible = isChronicleEligible({- type: snapshot.page.type, slug: snapshot.page.slug, body: snapshot.page.compiled_truth ?? '',- dreamGenerated: snapshot.page.frontmatter?.dream_generated === true,- effectiveDate: snapshot.page.effective_date ?? null, effectiveDateSource: snapshot.page.effective_date_source ?? null,- frontmatter: snapshot.page.frontmatter ?? null, changedAt: row.decided_at,+ type: page.type, slug: page.slug, body: page.compiled_truth ?? '',+ dreamGenerated: page.frontmatter?.dream_generated === true,+ effectiveDate: page.effective_date ?? null, effectiveDateSource: page.effective_date_source ?? null,+ frontmatter: page.frontmatter ?? null, changedAt: row.decided_at,}, { now, recentDays: auto ? settings.recentDays : null, settleSeconds: auto ? settings.settleSeconds : null });if (!eligible.ok) {if ('wait' in eligible) {@@ -193,8 +201,8 @@ export async function executeChronicleRow(ctx: ChronicleExecContext, row: Chronireturn done('skipped', reason);}- const judgeCtx = chronicleJudgeContext(snapshot.page);- const invite = endedInviteProposal(snapshot.page, judgeCtx.attendees, now);+ const judgeCtx = chronicleJudgeContext(page);+ const invite = endedInviteProposal(page, judgeCtx.attendees, now);if (auto && !invite && !(await reserveChronicleSlot(engine, settings.dailyLimit, { sourceId: row.source_id, pageId: Number(row.page_id), contentHash: row.content_hash }))) {await setNextAttempt(engine, row, null);return { kind: 'deferred', reason: 'daily_limit' };diff --git a/src/core/chronicle/ledger.ts b/src/core/chronicle/ledger.tsindex b641946018..261c5d791c 100644--- a/src/core/chronicle/ledger.ts+++ b/src/core/chronicle/ledger.ts@@ -7,6 +7,9 @@ import type { BrainEngine } from '../engine.ts';import type { PageSnapshot } from '../page-state/types.ts';import type { WriteAuthority, WriteRequest } from '../persistence/model.ts';import { derivedExtractionSkip } from '../persistence/derived-extraction-gate.ts';+import { isSegmentedPage, pageBodyBytes } from '../page-body/page-shape.ts';+import type { BodyStorage } from '../page-body/types.ts';+import { PAGE_MAX_BYTES } from '../page-size-policy.ts';import { CHRONICLE_ACTIVATED_AT_KEY, autoChronicleSetting, chronicleSettings, type ChronicleSettings } from './config.ts';import { CHRONICLE_EXTRACTOR_VERSION, type ChronicleLedgerRow, type ChronicleTrigger } from './contract.ts';import { isChronicleEligible, isChronicleShaped } from './eligibility.ts';@@ -21,7 +24,10 @@ export const RETIRE_REASONS = ['not_chronicle_shaped', 'dream_generated', 'too_sexport interface ChronicleDecisionPage {type: string;slug: string;+ /** For a segmented page, its `truth_lead` (the page row has no `compiled_truth`). */compiled_truth?: string | null;+ body_storage?: BodyStorage | null;+ body_bytes?: number | null;frontmatter?: Record<string, unknown> | null;effective_date?: Date | string | null;effective_date_source?: string | null;@@ -62,6 +68,7 @@ export function decideChronicle(input: {}return skip(eligible.reason.startsWith('kind:') ? 'not_chronicle_shaped' : eligible.reason);}+ if (isSegmentedPage(page) && pageBodyBytes(page) > PAGE_MAX_BYTES) return skip('page_body_segmented');return { state: 'pending', reason: null, nextAttemptAt: new Date(input.now.getTime() + input.settings.settleSeconds * 1000) };}@@ -190,7 +197,10 @@ export async function recordChronicleDecision(tx: BrainEngine, row: DecidingRequ}const now = new Date();const setting = autoChronicleSetting(enabledRaw);- const decision = decideChronicle({ page, authority: row.authority ?? null, noExtract,+ const decisionPage: ChronicleDecisionPage = isSegmentedPage(page) ? { type: page.type, slug: page.slug, frontmatter: page.frontmatter,+ effective_date: page.effective_date, effective_date_source: page.effective_date_source, body_storage: page.body_storage, body_bytes: page.body_bytes,+ compiled_truth: (await tx.executeRaw<{ truth_lead: string | null }>('SELECT truth_lead FROM pages WHERE id=$1', [page.id]))[0]?.truth_lead } : page;+ const decision = decideChronicle({ page: decisionPage, authority: row.authority ?? null, noExtract,enabled: setting === 'on', invalidSetting: setting === 'invalid', settings, now });const receiptCtx: ChronicleReasonContext = { sourceId: base.sourceId, since: now.toISOString().slice(0, 10),dailyLimit: settings.dailyLimit, recentDays: settings.recentDays };diff --git a/src/core/chronicle/reasons.ts b/src/core/chronicle/reasons.tsindex 2286bea959..1cb5928ec5 100644--- a/src/core/chronicle/reasons.ts+++ b/src/core/chronicle/reasons.ts@@ -75,6 +75,8 @@ export const CHRONICLE_REASONS = {meaning: () => 'The page body is under 80 characters, too short to hold events.' },dream_generated: { stage: 'decision',meaning: () => 'Dream-generated pages are never mined for events.' },+ page_body_segmented: { stage: 'decision',+ meaning: () => 'The page body is over the 24 MiB single-string ceiling and is stored in segments; extraction reads the whole body as one string, so it skips this page.' },no_write_decision: { stage: 'discovery',meaning: () => 'This revision has no recorded write decision (written by an older binary or before this release activated), so only a trusted backfill extracts it.',fix: backfill('agent', FIX_BY_BACKFILL) },diff --git a/src/core/cycle/chronicle.ts b/src/core/cycle/chronicle.tsindex d9e17f8216..356cd1d68a 100644--- a/src/core/cycle/chronicle.ts+++ b/src/core/cycle/chronicle.ts@@ -66,8 +66,9 @@ async function discover(engine: BrainEngine, sourceId: string, ctx: {const pages = await engine.executeRaw<{id: number; slug: string; type: string; compiled_truth: string | null; frontmatter: Record<string, unknown> | null;effective_date: Date | string | null; effective_date_source: string | null; content_hash: string; updated_at: Date | string;+ body_storage: 'inline' | 'segmented'; body_bytes: number | null;}>(- `SELECT p.id, p.slug, p.type, p.compiled_truth, p.frontmatter, p.effective_date, p.effective_date_source, p.content_hash, p.updated_at+ `SELECT p.id, p.slug, p.type, coalesce(p.compiled_truth, p.truth_lead) AS compiled_truth, p.body_storage, p.body_bytes, p.frontmatter, p.effective_date, p.effective_date_source, p.content_hash, p.updated_atFROM pages pWHERE p.source_id=$1 AND p.deleted_at IS NULL AND p.content_hash IS NOT NULL AND p.updated_at >= $2::timestamptzAND p.type <> 'event' AND p.slug NOT LIKE 'life/%'diff --git a/src/core/error-registry.ts b/src/core/error-registry.tsindex 655deafc13..927f017dc5 100644--- a/src/core/error-registry.ts+++ b/src/core/error-registry.ts@@ -94,7 +94,7 @@ export const CODES = {catalog_capacity_exceeded: { class: 'caller', summary: "The shared-skills catalog visible to this connection exceeds the delivery limits.", docs: 'docs/guides/shared-brain-skills.md#troubleshoot-leave-and-recover' },catalog_unavailable: { class: 'retryable', summary: "Shared skill storage is not ready on this brain." },changed_since_preview: { class: 'caller', summary: "The file changed after its repair was previewed, so nothing was written.", why: "A repair writes exactly the bytes the operator approved; it binds approval to the previewed file hash and refuses when the file moved on.", suggestion: 'Preview the repair again, review the new proposal, and approve its new hash.' },- chronicle_skipped: { class: 'unavailable', summary: "Automatic event extraction (auto_chronicle) skipped or failed this page; `reason` says why and `fix`, when present, is the next step.", reasons: ['auto_chronicle_off', 'auto_chronicle_invalid', 'slug_bound_client', 'operation_bound_client', 'no_extract', 'history', 'not_yet_happened', 'too_short', 'dream_generated', 'no_write_decision', 'not_chronicle_shaped', 'already_extracted', 'superseded', 'daily_limit', 'judge_llm_unavailable', 'no_pricing', 'budget_exhausted', 'campaign_exhausted', 'judge_chat_error', 'judge_truncated', 'judge_parse_failed', 'malformed_proposal', 'publish_error', 'judge_refused', 'page_missing', 'no_events', 'future_dated', 'date_imprecise', 'no_chat_provider'], docs: 'docs/guides/life-chronicle.md#skip-and-failure-codes', suggestion: 'Read the receipt or doctor `auto_chronicle` check: its `why` explains the reason and its `fix`, when present, is the next step (paid fixes need the user\'s agreement).' },+ chronicle_skipped: { class: 'unavailable', summary: "Automatic event extraction (auto_chronicle) skipped or failed this page; `reason` says why and `fix`, when present, is the next step.", reasons: ['auto_chronicle_off', 'auto_chronicle_invalid', 'slug_bound_client', 'operation_bound_client', 'no_extract', 'history', 'not_yet_happened', 'too_short', 'dream_generated', 'page_body_segmented', 'no_write_decision', 'not_chronicle_shaped', 'already_extracted', 'superseded', 'daily_limit', 'judge_llm_unavailable', 'no_pricing', 'budget_exhausted', 'campaign_exhausted', 'judge_chat_error', 'judge_truncated', 'judge_parse_failed', 'malformed_proposal', 'publish_error', 'judge_refused', 'page_missing', 'no_events', 'future_dated', 'date_imprecise', 'no_chat_provider'], docs: 'docs/guides/life-chronicle.md#skip-and-failure-codes', suggestion: 'Read the receipt or doctor `auto_chronicle` check: its `why` explains the reason and its `fix`, when present, is the next step (paid fixes need the user\'s agreement).' },checkpoint_missing: { class: 'caller', summary: "The approved source plan is missing; do not restart from a different revision." },checkpoint_validation_timeout: { class: 'retryable', summary: "Validating the managed-sync checkpoint timed out." },claim_already_used: { class: 'caller', summary: "Google connect credential error: claim already used.", docs: 'docs/guides/google-connect.md#troubleshooting' },diff --git a/src/core/persistence/effect-facts.ts b/src/core/persistence/effect-facts.tsindex 46d7e6d362..a0755d7989 100644--- a/src/core/persistence/effect-facts.ts+++ b/src/core/persistence/effect-facts.ts@@ -13,6 +13,8 @@ import { authorizeStoredRequest, authorizeWrite } from './authority.ts';import { completeEffect } from './effect-journal.ts';import { guardEffectSource } from './effect-recovery.ts';import { derivedExtractionSkip } from './derived-extraction-gate.ts';+import { bodyStorageOf, stringWriteStorage } from './segmented-apply.ts';+import { isSegmentedPage, pageBodyBytes } from '../page-body/page-shape.ts';import type { PersistenceEffect } from './effect-model.ts';import type { WriteRequest } from './model.ts';@@ -94,6 +96,7 @@ export async function prepareFactsBackstop(engine: BrainEngine, row: WriteRequesif (!(await isFactsExtractionEnabled(engine))) return { skipped: 'extraction_disabled' };const eligible = isFactsBackstopEligible(row.slug, page);if (!eligible.ok) return { skipped: eligible.reason };+ if ((await stringWriteStorage(engine, pageBodyBytes(page), bodyStorageOf(before?.page))).storage === 'segmented') return { skipped: 'page_body_segmented' };if (await bodyAlreadyOffered(engine, row.slug, page, before)) return { skipped: 'body_unchanged' };return { queued: true };}@@ -117,6 +120,7 @@ export async function readFactsBackstopJobPage(engine: BrainEngine, data: Recordthrow error;}}+ if (isSegmentedPage(snapshot.page)) return { skipped: 'page_body_segmented' } as const;return { page: snapshot.page };}diff --git a/src/core/persistence/effect-links.ts b/src/core/persistence/effect-links.tsindex 4701a9ef8c..d5584b0c7e 100644--- a/src/core/persistence/effect-links.ts+++ b/src/core/persistence/effect-links.ts@@ -10,6 +10,7 @@ import { REMOTE_AUTO_LINKS_KEY, REMOTE_MENTION_LINK_SOURCE, type PersistenceEffeimport { guardEffectSource } from './effect-recovery.ts';import type { SqlEngine, WriteAuthority, WriteRequest } from './model.ts';import { excludesPrivateWrites } from './page-visibility.ts';+import { isSegmentedPage } from '../page-body/page-shape.ts';import { isRemoteWantedPagesEnabled, replaceWantedLinks } from '../wanted-links.ts';/** `mcp.remote_auto_links`: unset is on; false/0/no/off (any case) turns the remote `links` effect off. */@@ -67,8 +68,9 @@ async function targetGrant(tx: SqlEngine, a: WriteAuthority): Promise<(slug: str* mention edges (link_source `mcp-remote-mention`, origin = the page) against* the targets that exist at execution time, in the page's source, visible to* the writer and inside its slug grant. Only this producer's edges are added- * or removed. A changed or deleted page, a revoked grant or a disabled config- * finishes the effect as skipped with its reason. The links table carries no+ * or removed. A changed or deleted page, a revoked grant, a disabled config or+ * a segmented page (its body is not read; its edges are kept) finishes the+ * effect as skipped with its reason. The links table carries no* writer guard or row attribution, so the source guard and the page keys of* the page and its targets are what serialize this with publications.*/@@ -80,6 +82,7 @@ export async function runLinksEffect(engine: BrainEngine, effect: PersistenceEffconst snapshot = await engine.readPageSnapshot(effect.data.slug, { sourceId });if (!snapshot || snapshot.page.id !== effect.data.page_id || snapshot.revision !== effect.revision) return skip(engine, 'superseded');if (!await isAutoLinkEnabled(engine) || !await isRemoteAutoLinksEnabled(engine)) return skip(engine, 'disabled');+ if (isSegmentedPage(snapshot.page)) return skip(engine, 'page_body_segmented');const { targets, skipped } = await mentionTargets(engine, snapshot, sourceId);await engine.transaction(async tx => {await tx.executeRaw("SELECT set_config('synchronous_commit','on',true),set_config('lock_timeout','1s',true),set_config('statement_timeout','5s',true)");diff --git a/test/large-pages/segmented-derived-work.test.ts b/test/large-pages/segmented-derived-work.test.tsnew file mode 100644index 0000000000..0b4b3544df--- /dev/null+++ b/test/large-pages/segmented-derived-work.test.ts@@ -0,0 +1,214 @@+/**+ * Wave B derived work on segmented pages (pages.segmented_storage on): the+ * Life Chronicle decision and execution, the remote `links` effect and the+ * facts backstop meet pages whose body fields throw `page_body_segmented`.+ *+ * 1. Protects: a coordinated publication of a chronicle-shaped segmented page+ * commits with a pending chronicle decision; the unmanaged discovery never+ * reads a segmented page as `too_short` (which would retire its events);+ * execution judges a segmented page within the single-string ceiling and+ * skips one above it as `page_body_segmented`; backfill counts segmented+ * pages as eligible; a remote write's `links` effect on a segmented page+ * finishes skipped instead of retrying forever; the facts backstop neither+ * queues for a segmented page nor lets a facts-absorb job throw on one.+ * 2. Fails when: any of these paths reads `compiled_truth` of a segmented page+ * object, or sees its NULL column as an empty body.+ */+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';+import { randomUUID } from 'node:crypto';+import { mkdtempSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';+import type { BrainEngine } from '../../src/core/engine.ts';+import type { OperationContext } from '../../src/core/ops/contract.ts';+import { importFromContent } from '../../src/core/import-file.ts';+import { PAGE_MAX_BYTES } from '../../src/core/page-size-policy.ts';+import { submissionAuthority } from '../../src/core/persistence/authority.ts';+import { admitWrite, claimNextWrite } from '../../src/core/persistence/journal.ts';+import { localHostId, registerLocalWriter } from '../../src/core/persistence/identity.ts';+import { preparePageMutation } from '../../src/core/persistence/page-prepare.ts';+import { publishMutation } from '../../src/core/persistence/coordinator.ts';+import { runPersistenceEffects } from '../../src/core/persistence/effects.ts';+import { disposePersistenceConsumer } from '../../src/core/persistence/service.ts';+import { decideChronicle } from '../../src/core/chronicle/ledger.ts';+import { upsertChronicleRow } from '../../src/core/chronicle/ledger.ts';+import { runChronicleBackfill } from '../../src/core/chronicle/backfill.ts';+import { runPhaseChronicle } from '../../src/core/cycle/chronicle.ts';+import { makeFactsAbsorbHandler } from '../../src/core/minions/handlers/facts-absorb.ts';+import { isolatedPersistencePostgres } from '../helpers/persistence-postgres.ts';+import { withEnv } from '../helpers/with-env.ts';+import { conversationBody } from '../helpers/conversation-page.ts';++const config = { engine: 'pglite' as const, embedding_disabled: true };+const CLIENT = 'client-segmented-derived';+const today = new Date().toISOString().slice(0, 10);+const body = conversationBody(1_200_000, { seed: 61 });+const meeting = (title: string) => `---\ntype: meeting\ntitle: ${title}\ndate: ${today}\n---\n\n${body}\n`;+const note = (title: string) => `---\ntype: note\ntitle: ${title}\n---\n\nSee [[people/alice-example]].\n\n${body}\n`;+const home = mkdtempSync(join(tmpdir(), 'gbrain-segmented-derived-'));+const engines: BrainEngine[] = [];+let closePostgres: (() => Promise<void>) | undefined;++beforeAll(async () => {+ const lite = new PGLiteEngine(); await lite.connect({}); await lite.initSchema(); engines.push(lite);+ if (process.env.DATABASE_URL) { const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL); engines.push(pg.engine); closePostgres = pg.close; }+}, 120_000);++afterAll(async () => {+ await withEnv({ GBRAIN_HOME: home }, async () => {+ for (const engine of engines) { await disposePersistenceConsumer(engine); await engine.disconnect(); }+ await closePostgres?.();+ });+ rmSync(home, { recursive: true, force: true });+});++beforeEach(async () => {+ for (const engine of engines) {+ await engine.executeRaw('DELETE FROM chronicle_page_state');+ await engine.executeRaw('DELETE FROM persistence_effects');+ await engine.executeRaw('DELETE FROM pages');+ await engine.setConfig('pages.segmented_storage', 'on');+ await engine.setConfig('chronicle.auto_settle_seconds', '0');+ await engine.setConfig('chronicle.activated_at', new Date(Date.now() - 60_000).toISOString());+ }+});++async function sourceIncarnation(engine: BrainEngine, sourceId = 'default'): Promise<string> {+ return (await engine.executeRaw<{ incarnation: string }>('SELECT incarnation FROM sources WHERE id=$1', [sourceId]))[0]!.incarnation;+}++/** One coordinated put_page through admission, preparation and publication; `remote` writes as an OAuth client. */+async function coordinatedPut(engine: BrainEngine, slug: string, content: string, remote = false) {+ return withEnv({ GBRAIN_HOME: home }, async () => {+ await registerLocalWriter(engine, 'cli');+ if (remote) {+ await engine.executeRaw(`INSERT INTO oauth_clients(client_id,client_secret_hash,client_name,scope,source_id)+ VALUES($1,'fixture-hash','segmented-client','read write','default') ON CONFLICT (client_id) DO NOTHING`, [CLIENT]);+ }+ const ctx: OperationContext = { engine, config, dryRun: false, remote, sourceId: 'default', logger: { info() {}, warn() {}, error() {} },+ ...(remote ? { auth: { token: 'fixture', clientId: CLIENT, principal: { kind: 'oauth_client', id: CLIENT }, scopes: ['read', 'write'], sourceId: 'default' } as OperationContext['auth'] } : {}) };+ const incarnation = await sourceIncarnation(engine);+ const authority = await submissionAuthority(ctx, 'put_page', 'default', incarnation, slug);+ await admitWrite(engine, { principal: authority.principal, authority, operation: 'put_page', sourceId: 'default', sourceIncarnation: incarnation,+ slug, pageId: null, requestId: randomUUID(), callerIntent: { content }, intent: { content } });+ const row = (await claimNextWrite(engine, localHostId()))!;+ return publishMutation(engine, row, await preparePageMutation(engine, row, config));+ });+}++async function storage(engine: BrainEngine, slug: string): Promise<{ id: number; body_storage: string; content_hash: string }> {+ const [row] = await engine.executeRaw<{ id: number; body_storage: string; content_hash: string }>(+ "SELECT id, body_storage, content_hash FROM pages WHERE source_id='default' AND slug=$1", [slug]);+ return { ...row!, id: Number(row!.id) };+}++const ledger = (engine: BrainEngine) => engine.executeRaw<{ slug: string; state: string; reason: string | null; scheduled: boolean }>(+ 'SELECT slug, state, reason, next_attempt_at IS NOT NULL AS scheduled FROM chronicle_page_state ORDER BY slug, decided_at');++describe('Life Chronicle on segmented pages', () => {+ test('a coordinated put_page of a chronicle-shaped segmented page commits with a pending decision', async () => {+ for (const engine of engines) {+ // A trusted write with auto_link off and a remote write both reach the in-transaction chronicle decision.+ await engine.setConfig('auto_link', 'false');+ try {+ for (const [slug, remote] of [['meetings/segmented-daily', false], ['meetings/segmented-weekly', true]] as const) {+ const committed = await coordinatedPut(engine, slug, meeting(slug), remote);+ expect({ state: committed.state, error: committed.error_code }).toEqual({ state: 'committed', error: null });+ expect((await storage(engine, slug)).body_storage).toBe('segmented');+ expect(committed.outcome?.chronicle_backstop).toMatchObject({ pending: 'next_cycle' });+ }+ } finally { await engine.unsetConfig('auto_link'); }+ expect(await ledger(engine)).toEqual([+ { slug: 'meetings/segmented-daily', state: 'pending', reason: null, scheduled: true },+ { slug: 'meetings/segmented-weekly', state: 'pending', reason: null, scheduled: true }]);+ }+ }, 300_000);++ test('the write decision skips a segmented page over the single-string ceiling as page_body_segmented, never too_short', () => {+ const settings = { recentDays: 30, settleSeconds: 0 };+ const page = { type: 'meeting', slug: 'meetings/huge', frontmatter: { date: today }, body_storage: 'segmented' as const };+ const over = decideChronicle({ page: { ...page, body_bytes: PAGE_MAX_BYTES + 1, compiled_truth: 'x'.repeat(200) }, authority: null,+ noExtract: false, enabled: true, settings, now: new Date() });+ expect(over).toEqual({ state: 'skipped', reason: 'page_body_segmented', nextAttemptAt: null });+ });++ test('unmanaged discovery decides a segmented page from its truth lead and the phase judges its materialized body', async () => {+ for (const engine of engines) {+ await importFromContent(engine, 'meetings/segmented-standup', meeting('Standup'), { sourceId: 'default', noEmbed: true });+ const page = await storage(engine, 'meetings/segmented-standup');+ expect(page.body_storage).toBe('segmented');+ // An earlier revision produced events: a too_short decision would schedule their retirement.+ await upsertChronicleRow(engine, { sourceId: 'default', pageId: page.id, contentHash: 'earlier-revision', slug: 'meetings/segmented-standup',+ state: 'pending', reason: null, trigger: 'auto', nextAttemptAt: null });+ await engine.executeRaw(`UPDATE chronicle_page_state SET state='extracted', event_hashes=ARRAY['h1'], event_slugs=ARRAY['life/events/e1']+ WHERE content_hash='earlier-revision'`);+ const judged: string[] = [];+ const run = await runPhaseChronicle(engine, { judge: async (input) => { judged.push(input.body); return { events: [] }; } });+ expect(run.details.reasons).not.toHaveProperty('too_short');+ expect(judged).toHaveLength(1);+ expect(judged[0]!.slice(0, 200)).toBe(body.slice(0, 200));+ const rows = await engine.executeRaw<{ state: string; reason: string | null }>(+ 'SELECT state, reason FROM chronicle_page_state WHERE content_hash=$1', [page.content_hash]);+ expect(rows).toEqual([{ state: 'extracted', reason: 'no_events' }]);+ }+ }, 300_000);++ test('execution skips a segmented page over the single-string ceiling as page_body_segmented without throwing', async () => {+ for (const engine of engines) {+ await importFromContent(engine, 'meetings/segmented-offsite', meeting('Offsite'), { sourceId: 'default', noEmbed: true });+ const page = await storage(engine, 'meetings/segmented-offsite');+ await upsertChronicleRow(engine, { sourceId: 'default', pageId: page.id, contentHash: page.content_hash, slug: 'meetings/segmented-offsite',+ state: 'pending', reason: null, trigger: 'auto', nextAttemptAt: null });+ await engine.executeRaw('UPDATE pages SET body_bytes=$2 WHERE id=$1', [page.id, PAGE_MAX_BYTES + 1]);+ let calls = 0;+ await runPhaseChronicle(engine, { judge: async () => { calls++; return { events: [] }; } });+ expect(calls).toBe(0);+ expect(await ledger(engine)).toEqual([{ slug: 'meetings/segmented-offsite', state: 'skipped', reason: 'page_body_segmented', scheduled: false }]);+ }+ }, 300_000);++ test('backfill counts a segmented chronicle page as eligible', async () => {+ for (const engine of engines) {+ await importFromContent(engine, 'meetings/segmented-review', meeting('Review'), { sourceId: 'default', noEmbed: true });+ const result = await runChronicleBackfill(engine, { dryRun: true, sourceId: 'default' });+ expect(result.skipped).not.toHaveProperty('too_short');+ expect(result.eligible).toBe(1);+ }+ }, 300_000);+});++describe('page-write effects on segmented pages', () => {+ test('a remote write of a segmented page finishes its links effect as skipped instead of retrying', async () => {+ for (const engine of engines) {+ const committed = await coordinatedPut(engine, 'notes/segmented-remote', note('Remote'), true);+ expect(committed.state).toBe('committed');+ expect((await storage(engine, 'notes/segmented-remote')).body_storage).toBe('segmented');+ await withEnv({ GBRAIN_HOME: home }, () => runPersistenceEffects(engine, config, { hostId: localHostId() }));+ const effects = await engine.executeRaw<{ state: string; error_code: string | null; outcome: Record<string, unknown> | null }>(+ "SELECT state, error_code, outcome FROM persistence_effects WHERE request_id=$1::uuid AND kind='links'", [committed.id]);+ expect(effects).toEqual([{ state: 'committed', error_code: null, outcome: { links: 'skipped', reason: 'page_body_segmented' } }]);+ }+ }, 300_000);++ test('a write of a segmented page reports the facts backstop skipped and queues no facts-backstop effect', async () => {+ for (const engine of engines) {+ await engine.setConfig('facts.extraction_enabled', 'true');+ const committed = await coordinatedPut(engine, 'notes/segmented-facts', note('Facts'), true);+ expect(committed.state).toBe('committed');+ expect(committed.outcome?.facts_backstop).toEqual({ skipped: 'page_body_segmented' });+ expect(await engine.executeRaw("SELECT kind FROM persistence_effects WHERE request_id=$1::uuid AND kind='facts-backstop'", [committed.id])).toEqual([]);+ }+ }, 300_000);++ test('a facts-absorb job for a segmented page returns skipped instead of throwing', async () => {+ for (const engine of engines) {+ await importFromContent(engine, 'notes/segmented-absorb', note('Absorb'), { sourceId: 'default', noEmbed: true });+ expect((await storage(engine, 'notes/segmented-absorb')).body_storage).toBe('segmented');+ const handler = makeFactsAbsorbHandler(engine);+ const result = await withEnv({ GBRAIN_HOME: home }, () => handler({ id: 1, name: 'facts-absorb', signal: new AbortController().signal,+ data: { slug: 'notes/segmented-absorb', sourceId: 'default', source: 'sync:import' } } as never));+ expect(result).toEqual({ skipped: 'page_body_segmented', slug: 'notes/segmented-absorb', sourceId: 'default' });+ }+ }, 300_000);+});diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txtindex 803b52b54d..fde864e06a 100644--- a/test/postgres-unit-arms.txt+++ b/test/postgres-unit-arms.txt@@ -67,6 +67,7 @@ test/large-pages/chunk-visibility.test.tstest/large-pages/managed-streamed-import.test.tstest/large-pages/segment-vector-reuse.test.tstest/large-pages/segmented-body-unreachable.test.ts+test/large-pages/segmented-derived-work.test.tstest/large-pages/segmented-embedding.test.tstest/large-pages/segmented-versions.test.tstest/link-cross-source.test.ts