Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
WIP G4 wave 2: rollup halt fix, duplicate_claim pointer, memory/unattributed home, multi-page publication scaffolding
garrytan896578cec956
diff --git a/docs/architecture/canonical-writers.tsv b/docs/architecture/canonical-writers.tsvindex 30cd0cf5a1..facebef3f8 100644--- a/docs/architecture/canonical-writers.tsv+++ b/docs/architecture/canonical-writers.tsv@@ -236,7 +236,7 @@ src/core/repair/redacted-facts.ts 1 coordinator `gbrain repair redacted-facts` (src/core/repair/ontology-facts.ts 1 coordinator `gbrain repair ontology-facts` (#6264) gives preview-approved ontology observations their own provenance back, clears their fence row number and expiry. On a managed brain the UPDATE runs only inside coordinatedDatabaseWrite (the ontology_propose path: write authority checked, source incarnation revalidated, entity and page keys locked); an unmanaged brain runs it in one maintenance transaction. It writes database-only ontology rows and never a page or file.src/core/repair/facts-rehome.ts 1 coordinator `gbrain repair facts-rehome` (B-7, #6925) moves preview-approved database-only facts off a page-less entity_slug onto the page the strict resolver reaches. On a managed brain the UPDATE runs only inside coordinatedDatabaseWrite (the relink_facts operation: write authority checked, source incarnation revalidated, both slugs locked); an unmanaged brain runs one maintenance transaction per slug. It rechecks the slug, target and fact ids against the preview and never writes a page or file.src/core/repair/consolidate-ties.ts 1 coordinator `gbrain repair consolidate-ties` (#6023) sets preview-approved typed facts that consolidation closed at their own effective instant back to open validity. On a managed brain the UPDATE runs only inside coordinatedDatabaseWrite (the relink_facts operation: write authority checked, source incarnation revalidated, the entity key locked); an unmanaged brain runs one maintenance transaction per fact. It rechecks the fact, take and instant against the preview and never writes a page or file.-src/core/repair/duplicate-facts.ts 2 coordinator `gbrain repair duplicate-facts` (#7043) supersedes preview-approved copies of one active fact (expired_at and superseded_by pointing at the kept oldest row). On a managed brain each UPDATE runs only inside coordinatedDatabaseWrite (the relink_facts operation: write authority checked, source incarnation revalidated, the entity keys locked); an unmanaged brain runs one maintenanceTransaction per group. A fenced copy is first struck in its page through a revision-bound put_page (submitPageMutation), and its superseded_by link is written after that page write. It rechecks every row against the preview and never deletes a row.+src/core/repair/duplicate-facts.ts 2 coordinator `gbrain repair duplicate-facts` (#7043) supersedes preview-approved copies of one active fact (expired_at and superseded_by pointing at the kept row: the copy that is a row of its page's facts fence, else the oldest). On a managed brain each UPDATE runs only inside coordinatedDatabaseWrite (the relink_facts operation: write authority checked, source incarnation revalidated, the entity keys locked); an unmanaged brain runs one maintenanceTransaction per group. A fenced copy is first struck in its page through a revision-bound put_page (submitPageMutation), and its superseded_by link is written after that page write. It rechecks every row against the preview and never deletes a row.src/core/repair/fact-claim-dates.ts 1 coordinator `gbrain repair fact-claim-dates` (#7247) moves preview-approved facts' valid_from to the date their claim states. Fence rows change only in the page through revision-bound put_page (the coordinator re-projects the facts row from the canonical text); the one direct UPDATE sets valid_from of database-only facts in one maintenanceTransaction on an unmanaged brain, rechecking each row's previewed valid_from, and is never reached on a managed brain.src/core/repair/conversation-labels.ts 4 coordinator `gbrain repair conversation-labels` expires preview-approved label-misattributed conversation facts, expires the page completion marker and writes the not-extractable outcome, under the page key: one database-only managed_maintenance_conversation_label_retire request per batch of up to 25 pages on a managed brain (the preparer reclassifies each page under its lock), one maintenanceTransaction per batch on an unmanaged brain.src/core/persistence/atom-maintenance.ts 1 coordinator A managed atom retirement stamps retired_by/retired_at on the tombstone inside the coordinator publication of its managed_atom_delete request, after the page deletion path removed the canonical file, so the database row and file change commit or roll back together.diff --git a/docs/architecture/system-of-record.md b/docs/architecture/system-of-record.mdindex 6cf9e6db90..9d3d486c2d 100644--- a/docs/architecture/system-of-record.md+++ b/docs/architecture/system-of-record.md@@ -296,7 +296,7 @@ or a physical projection that leaves attribution untouched):- `src/core/repair/atoms-restore.ts` (3): the unmanaged `gbrain repair atoms-restore` apply archives the retired atom's version, restores it and drops its `retired_by`/`retired_at` stamp in one `maintenanceTransaction`; managed brains publish a `managed_maintenance_restore_reextract_atom` request instead.- `src/core/repair/captured-facts.ts` (1): a request on managed brains; the unmanaged captured-facts expiry runs in `maintenanceTransaction`.- `src/core/repair/consolidate-ties.ts` (1): `gbrain repair consolidate-ties` reopens facts inside `coordinatedDatabaseWrite` on managed brains (the `relink_facts` operation) and in one `maintenanceTransaction` per fact on unmanaged brains.-- `src/core/repair/duplicate-facts.ts` (2): `gbrain repair duplicate-facts` supersedes duplicate fact copies inside `coordinatedDatabaseWrite` on managed brains (the `relink_facts` operation) and in one `maintenanceTransaction` per group on unmanaged brains; a fenced copy is struck through a revision-bound `put_page` first.+- `src/core/repair/duplicate-facts.ts` (2): `gbrain repair duplicate-facts` supersedes duplicate fact copies onto the kept row (the fenced copy, else the oldest) inside `coordinatedDatabaseWrite` on managed brains (the `relink_facts` operation) and in one `maintenanceTransaction` per group on unmanaged brains; a fenced copy is struck through a revision-bound `put_page` first.- `src/core/repair/conversation-labels.ts` (4): a request on managed brains; the unmanaged label retirement runs in `maintenanceTransaction`.- `src/core/repair/extractor-facts.ts` (1): a request on managed brains; the unmanaged extractor-facts restore runs in `maintenanceTransaction`.- `src/core/repair/fact-claim-dates.ts` (1): `gbrain repair fact-claim-dates` updates database-only facts' `valid_from` in one `maintenanceTransaction` on unmanaged brains only; fence rows move through revision-bound `put_page`, and a managed brain never takes the direct update.diff --git a/src/commands/doctor/checks/fence-integrity.ts b/src/commands/doctor/checks/fence-integrity.tsindex 39147364cf..5b00ee9aa2 100644--- a/src/commands/doctor/checks/fence-integrity.ts+++ b/src/commands/doctor/checks/fence-integrity.ts@@ -24,7 +24,10 @@* claim), from the planner's read-only result: pages, fact ids and reason* classes, never the claim. Those rows stay active and searchable and* nothing is lost, so the finding has no command (`next: report`) and never- * suggests `forget_fact`; its verify re-counts the rows.+ * suggests `forget_fact`; its verify re-counts the rows. A `duplicate_claim`+ * row (its page's fence already carries the claim) is the exception: the fix+ * is the read-only `gbrain repair duplicate-facts --source <id>` preview,+ * which keeps the fence row and supersedes the copy onto it (GBRA-190).** #6610: it also lists `unbound_legacy_facts`, the unfenced rows of a classic* database-only page that stay unfenced because the source has a checkout but@@ -134,11 +137,21 @@ async function unrenderableLegacyFacts(engine: BrainEngine, sourceIds: string[]return { total: pages.reduce((sum, page) => sum + page.rows.length, 0), complete, pages, unbound };}+/** The sources of the unadopted rows that copy a claim their page's fence already carries, in page order. */+function duplicateClaimSources(found: Omit<UnrenderableLegacyFacts, 'unbound'>): string[] {+ return [...new Set(found.pages.filter(page => page.rows.some(row => row.reason === 'duplicate_claim')).map(page => page.source_id))];+}+function unrenderableSentence(found: Omit<UnrenderableLegacyFacts, 'unbound'>): string {const pages = found.pages.slice(0, 5).map(page => `${page.slug} (${page.source_id}): ${[...new Set(page.rows.map(row => row.class))].sort().join(', ')}`).join('; ');+ const duplicates = found.pages.reduce((sum, page) => sum + page.rows.filter(row => row.reason === 'duplicate_claim').length, 0);+ const sources = duplicateClaimSources(found);return `${found.total} legacy fact row(s) on ${found.pages.length} page(s) cannot be adopted into their facts fence: ${pages}${found.pages.length > 5 ? '; …' : ''}. `+ 'They stay active and searchable and nothing is lost: the fence codec would change their text (or the page already carries the claim), so gbrain leaves them as legacy rows '- + 'and those pages skip destructive fact reconciliation. There is no safe automatic fix; report the pages and reason classes with the gbrain version. Do not forget or expire a row to clear this count.'+ + 'and those pages skip destructive fact reconciliation. '+ + (duplicates ? `${duplicates} of them copy a claim their page's facts table already carries (duplicate_claim): ${sources.map(id => `gbrain repair duplicate-facts --source ${id}`).join('; ')} previews retiring each copy onto its fence row (read-only; applying it needs the user's agreement), and the page then reconciles again. ` : '')+ + (duplicates < found.total ? 'For the other rows there is no safe automatic fix; report the pages and reason classes with the gbrain version. ' : '')+ + 'Do not forget or expire a row to clear this count.'+ (found.complete ? '' : ' The scan did not finish within its time budget, so more rows may be affected; run gbrain doctor --only fence_integrity again.');}@@ -219,6 +232,9 @@ export async function fenceIntegrityResult(engine: BrainEngine, opts: { timeoutM'fence_integrity', { docs: DOCS }): uncommitted.length ? agentFix(['gbrain', 'sources', 'status', uncommitted[0]!.source_id], 'Lists the uncommitted fence repairs of this legacy source with the exact gbrain git commit-push step for each file.','fence_integrity', { docs: DOCS })+ : duplicateClaimSources(unrenderable).length ? agentFix(['gbrain', 'repair', 'duplicate-facts', '--source', duplicateClaimSources(unrenderable)[0]!, '--json'],+ `Previews, read-only, the groups of active copies of one fact in ${duplicateClaimSources(unrenderable)[0]} and the row each keeps: a legacy copy of a claim its page's facts table carries keeps the fence row and is superseded onto it. Show the preview to the user; it prints the apply command with --expect <hash>, which runs only with their agreement.`,+ 'fence_integrity', { docs: 'docs/guides/repair.md#duplicate-facts' }): unbound.length && !unrenderable.total ? agentFix(['gbrain', 'config', 'set', UNBOUND_WRITE_KEY, 'database_only'],`Allows database-only writes to sources with a checkout but no canonical owner, so the next extract_facts run fences these rows into their database pages. It is brain-wide (every database-only page of such a source stays database-only after binding), so ask the user first.`,'fence_integrity', { ask_user: true, docs: UNBOUND_SOURCE_DOCS,diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex 4c1af63423..1e72ef858b 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -1302,6 +1302,8 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;{ since: '0.60.460.0', text: 'A legacy fact row whose `notability` or `confidence` is empty (a long-lived database whose column lost its NOT NULL) is now adopted into its page\'s `## Facts` table with the column default (notability `medium`, confidence 1) instead of being refused as unadoptable (`parse`) on every run, which held its page out of fact reconciliation and booked an `integrity_guard` halt each cycle. The fence cell is written first and the row derives its values from it. A row with no kind or visibility is still refused.' },{ since: '0.60.460.0', text: '`gbrain repair duplicate-facts` keeps the copy that is a row of a page\'s `## Facts` table over an older database-only copy of the same fact, so the legacy copy is superseded onto the fence row instead of holding it (which left the legacy row unfenced and its page out of fact reconciliation). With no fenced copy it still keeps the oldest row. It stays preview-first and explicit.' },{ since: '0.60.460.0', text: 'Dream consolidation on a managed brain now closes a fenced fact in its page: the closing `valid_until` is written into the fact\'s row in the entity page\'s `## Facts` fence, published with the take, and the database row takes its value from that cell, so a later sync or re-import keeps the fact closed. Before, only the database row was closed and the next re-import of the page reopened it. A fact with no fence row is still closed in the database. A fenced fact whose fence row is on another page is left open. Facts an earlier release closed in the database only are not changed (GBRA-190).' },+ { since: 'TBD', text: 'An `extract_facts` run whose empty-fence guard holds a page (a fact row of it is not in the page\'s `## Facts` table yet) is now booked in `gbrain extract status` and doctor `extract_health` as a completed round instead of an `integrity_guard` halt. The guard holds only that page while every other page reconciles, so one held page no longer reads as a facts halt on every cycle; doctor `fence_integrity` still names the held rows (GBRA-190).' },+ { since: 'TBD', text: 'Doctor `fence_integrity` now points a legacy fact row that copies a claim its page\'s `## Facts` table already carries (`duplicate_claim`) at the read-only `gbrain repair duplicate-facts --source <id>` preview, which keeps the fence row and supersedes the copy onto it after the user agrees. Before, every unadoptable row got only a report with no command (GBRA-190).' },];/** The newest disclosed change's release: the notice id moves only when a release adds rows. */diff --git a/src/core/cycle/extract-facts.ts b/src/core/cycle/extract-facts.tsindex 2b691da46e..f3b9b8d65d 100644--- a/src/core/cycle/extract-facts.ts+++ b/src/core/cycle/extract-facts.ts@@ -41,8 +41,9 @@* (`source_id = sourceId`, the source-isolation invariant): a row counts when* `row_num IS NULL`, its `entity_slug` resolves to a live page in this* source, it is not soft-expired (`expired_at IS NULL`; `forget_fact` drains- * rows that way) and the source has a `local_path`. `legacyRowsPending`,- * `guardTriggered` and the halt rollup still report the run; status returns+ * rows that way) and the source has a `local_path`. `legacyRowsPending`+ * and `guardTriggered` still report the run (its rollup is a completed round,+ * since the other pages reconcile); status returns* `warn` naming each failed page. Rows with no backing page or checkout* (slugify-floor / stub-guard-blocked slugs from the inline writer) are* structurally unfenceable and never gate, and neither are the rows of a@@ -849,19 +850,6 @@ export async function runExtractFacts('a row the fence codec cannot render stays active and searchable (doctor fence_integrity lists it); the phantom-redirect pass holds only the phantoms that own such rows. ' +'Individual rows can instead be drained via `forget_fact`.'),);- // #3683: a guard-triggered run books its halt here for doctor- // extract_health's halt_rate (the completion rollup below is skipped for- // it). upsertExtractRollup is best-effort internally (never throws).- if (!opts.dryRun) {- await upsertExtractRollup(engine, {- kind: 'facts.fence',- source_id: sourceId,- cost_delta: 0,- round_completed_delta: 0,- halt_delta: 1,- halt_reason: 'integrity_guard',- });- }}// ── v0.35.5: phantom-redirect pre-pass ──────────────────────────@@ -1138,9 +1126,9 @@ export async function runExtractFacts(console.error(`[extract_facts] receipt write failed: ${(err as Error).message}`);}}- if (!opts.dryRun && !result.guardTriggered) {- // #3683: a guard-triggered run booked its halt above (one rollup per- // run), so this path is always a completed round.+ if (!opts.dryRun) {+ // GBRA-190 G4: a page held by the empty-fence guard is skipped while every other page reconciles, so the run is a+ // completed round, not an `integrity_guard` halt; doctor fence_integrity names the held rows. One rollup per run.await upsertExtractRollup(engine, {kind: 'facts.fence',source_id: sourceId,diff --git a/src/core/facts/extract-from-fence.ts b/src/core/facts/extract-from-fence.tsindex 0e294bf51b..f82e96cdab 100644--- a/src/core/facts/extract-from-fence.ts+++ b/src/core/facts/extract-from-fence.ts@@ -44,6 +44,12 @@ import type { ParsedFact } from '../facts-fence.ts';import { computeEffectiveDate } from '../effective-date.ts';/** #7247: the page dates that say when its content happened. A page's creation or import time is not one. */+/**+ * The page a fact saved without an entity is a row of (GBRA-190 G4, D3). Its fence rows belong to no entity: they+ * project with `entity_slug` NULL, so their withdrawal is source-wide ('*'), as a subjectless fact's always was.+ */+export const UNATTRIBUTED_MEMORY_SLUG = 'memory/unattributed';+export const FACT_DATE_SOURCES: ReadonlySet<string> = new Set(['event_date', 'date', 'published', 'filename']);/** #7247: the fallback valid_from for a page's fence rows without a cell, or null when the page states no such date. */@@ -265,7 +271,7 @@ export function extractFactsFromFenceText(const row: FenceExtractedFact = {fact: f.claim,kind: f.kind as FactKind,- entity_slug: slug,+ entity_slug: slug === UNATTRIBUTED_MEMORY_SLUG ? null : slug,visibility: f.visibility as FactVisibility,notability: f.notability,context: f.context ?? null,diff --git a/src/core/facts/fence-fact-append.ts b/src/core/facts/fence-fact-append.tsindex 5a4fa551dd..f5a6bdabed 100644--- a/src/core/facts/fence-fact-append.ts+++ b/src/core/facts/fence-fact-append.ts@@ -12,6 +12,9 @@* number past both the fence and every facts row indexed from the page (a row the fence lost still owns its number,* #6696 C9), optionally strikes the superseded row of the same page, and prepares the page write. The stored fence is* normalized first (#6188); a fence that does not parse cleanly refuses typed (`target_fence_malformed`, #6385 R12).+ * - A request on `memory/unattributed` (`UNATTRIBUTED_MEMORY_SLUG`) with no page yet creates it: a `note` whose body is+ * the one facts fence. Its rows project with no entity (extract-from-fence.ts), so a fact saved without an entity+ * has a file home (GBRA-190 G4, D3). No other page is ever created here.* - `index-existing`: the file already holds the row (a fence-guard hold names it by `payload.row_num`). The cell at* that row number must read back as the fact (`fenceCellReadBackProblem`), else it refuses `fence_row_changed` and* nothing is written. No file changes: the facts row derives from the cell (`extractFactsFromFenceText`, the row a@@ -23,6 +26,7 @@ import type { BrainEngine, NewFact } from '../engine.ts';import type { GBrainConfig } from '../config.ts';import type { Action } from '../agent-output.ts';import type { PageSnapshot } from '../page-state/types.ts';+import type { Page } from '../types.ts';import { opError } from '../ops/contract.ts';import { readFix } from '../ops/op-fix.ts';import { factsFenceSection, fenceCellReadBackProblem, formatFenceDate, parseFactsFence, strikeFactRowInPage, upsertFactRow } from '../facts-fence.ts';@@ -38,7 +42,7 @@ import { pageFencesNormalized } from '../fence-repair/report.ts';import { withPendingFenceRows } from '../eligibility/fence-overlay.ts';import { withPageTierKept } from '../trust/fence-append.ts';import type { TrustTier } from '../trust/tier.ts';-import { extractFactsFromFenceText } from './extract-from-fence.ts';+import { extractFactsFromFenceText, UNATTRIBUTED_MEMORY_SLUG } from './extract-from-fence.ts';import { fenceRowOf, type FenceRowInput } from './unfenced-facts.ts';export type FenceFactAppendInput = {@@ -69,13 +73,19 @@ export function requestReceiptFix(row: WriteRequest): Action {: readFix(`Shows source ${row.source_id}'s writer and requests in flight, including ${row.request_id}, read-only.`, { argv: ['gbrain', 'sources', 'writer', 'status', '--source', row.source_id, '--json'] });}-export async function prepareFenceFactAppend(engine: BrainEngine, row: WriteRequest, config: GBrainConfig, snapshot: PageSnapshot,+export async function prepareFenceFactAppend(engine: BrainEngine, row: WriteRequest, config: GBrainConfig, snapshot: PageSnapshot | null,input: FenceFactAppendInput, signal?: AbortSignal): Promise<FenceFactAppend> {const { fact } = input;const page = { sourceId: row.source_id, slug: row.slug };+ if (!snapshot && (row.slug !== UNATTRIBUTED_MEMORY_SLUG || input.mode === 'index-existing')) {+ throw opError('storage_error', 'The facts fence target page does not exist.',+ `Request ${row.request_id} writes a facts row on ${row.slug} in source ${row.source_id}, which has no page, so nothing was written. Inspect the request; if it repeats, run gbrain doctor --json and report it to the user.`,+ { fix: requestReceiptFix(row) });+ }// Wave B: a segmented page is read back whole up to the single-string ceiling.- if (segmentedOverCeiling(snapshot.page)) throw pageBodyOverCeilingError(snapshot.page, `${row.operation} facts fence write`);- const base = await materializedPage(engine, snapshot.page);+ if (snapshot && segmentedOverCeiling(snapshot.page)) throw pageBodyOverCeilingError(snapshot.page, `${row.operation} facts fence write`);+ const base = snapshot ? await materializedPage(engine, snapshot.page)+ : { slug: row.slug, source_id: row.source_id, type: 'note', title: 'Unattributed memory', compiled_truth: '', timeline: '', frontmatter: {} } as unknown as Page;const insert = async (tx: BrainEngine, rowNum: number, indexed: NewFact) => {const inserted = await tx.insertFacts([{ ...indexed, row_num: rowNum, source_markdown_slug: row.slug }], { source_id: row.source_id }); // gbrain-allow-direct-insert: coordinator publication of a fence row this request's page file holds, after the fileif (inserted.ids.length === 1) return inserted.ids[0];@@ -105,9 +115,10 @@ export async function prepareFenceFactAppend(engine: BrainEngine, row: WriteRequ}// #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: base });+ const target = snapshot ? await normalizeTargetFences(engine, { sourceId: row.source_id, slug: row.slug, kind: 'facts', page: base })+ : { page: { compiled_truth: '', timeline: '' }, fixes: [] };const fencesNormalized = target.fixes.length ? { fences_normalized: pageFencesNormalized({ sourceId: row.source_id, slug: row.slug, fixes: target.fixes,- writer: row.principal_kind, path: snapshot.page.source_path ?? null, remote: row.authority.remote }) } : {};+ writer: row.principal_kind, path: snapshot?.page.source_path ?? null, remote: row.authority.remote }) } : {};// #6696 C9: a facts row the fence does not hold (extraction, a hand edit) still owns its row_num, so the new row numbers past both.const [indexedMax] = await engine.executeRaw<{ n: number }>('SELECT COALESCE(MAX(row_num),0)::int AS n FROM facts WHERE source_id=$1 AND source_markdown_slug=$2', [row.source_id, row.slug]);// #6686: the fence is edited in the section it lives in (a lone timeline fence stays below the sentinel); the other section is kept byte for byte.@@ -122,12 +133,12 @@ export async function prepareFenceFactAppend(engine: BrainEngine, row: WriteRequconst appended = refuseUnparsedRewrite(target.page, row.slug, row.source_id, () => upsertFactRow(fenced[section], cell));let next = { ...fenced, [section]: appended.body };if (input.supersede) next = strikeFactRowInPage(next, input.supersede.rowNum, rowNum, input.supersede.validUntil ? formatFenceDate(input.supersede.validUntil) : undefined);- const content = serializePageToMarkdown({ ...base, ...next }, snapshot.tags);+ const content = serializePageToMarkdown({ ...base, ...next }, snapshot?.tags ?? []);// The canonical parser/chunker and durable filesystem publication; the CAS binds this render to the snapshot.// #5575 ENG-1: the new row has no facts row yet; its chunks are cut at the append's tier.const prepared = await withPendingFenceRows({ ...page, rowNums: [rowNum], tier: input.pendingTier },- () => preparePageMutation(engine, { ...row, intent: { ...row.intent, content, expected_revision: snapshot.revision, force: false } }, config, undefined, signal, { unprojected: true }));- if (prepared.observedRevision !== snapshot.revision) {+ () => preparePageMutation(engine, { ...row, intent: { ...row.intent, content, ...(snapshot ? { expected_revision: snapshot.revision } : {}), force: false } }, config, undefined, signal, { unprojected: true }));+ if (prepared.observedRevision !== (snapshot?.revision ?? null)) {throw opError('revision_conflict', 'The entity page changed during preparation.',`Another write changed ${row.slug} in source ${row.source_id} while request ${row.request_id} was prepared, so it did not save. Check that request's receipt; once it shows conflict, nothing was saved and submitting it again is safe.`,{ fix: requestReceiptFix(row) });diff --git a/src/core/persistence/coordinator.ts b/src/core/persistence/coordinator.tsindex 1059475c27..80f7ceefa8 100644--- a/src/core/persistence/coordinator.ts+++ b/src/core/persistence/coordinator.ts@@ -19,7 +19,7 @@ import { PREPARATION_BUDGET_KEYS, preparationKind } from './preparation-budget.timport { chargeTransientInterruption, chargedInterruptionDetail, transientInterruption, type TransientInterruption } from './transient-retry.ts';import { readWriteSwitchSnapshot } from './switches.ts';import { isSharedReadFailure } from './bounded-reads.ts';-import { isTerminal, principalKey, requestPrincipal, recoveryFiles, type FileRecoveryRecord, type RecoveryRecord, type WriteRequest } from './model.ts';+import { isBundleRecovery, isTerminal, PAGES_RECOVERY_MAX_FILES, principalKey, requestPrincipal, recoveryFiles, type FileRecoveryRecord, type RecoveryRecord, type WriteRequest } from './model.ts';import { isLockOpenFailure, noteLockOpenFailure, type NativeLockHandle } from './native-lock.ts';import { withCoordinatedWrite } from './context.ts';import { lockCoreSources } from './core-guard.ts';@@ -103,8 +103,22 @@ interface PreparedMutationBase {* `commit` (trusted local preparers only) rides the Git effect into the commit message.*/export type PageMutationFile = MutationFile & { publishMode?: number; commit?: GitCommitNote };+/**+ * GBRA-190 G4 (D2): another page a page publication writes in the same transaction, under the same recovery record and+ * in the same Git commit as the request's own page (a withdrawal's other pages). Its key is locked with the request's,+ * its revision and identity are checked under that lock, its file (when the source has one) is published with the+ * request's, and `apply` runs in the publication transaction after the request's own apply. Only a protocol 2 page+ * request carries companions; the single-page path is unchanged.+ */+export interface CompanionPage {+ slug: string;+ pageId: number | null;+ observedRevision: string | null;+ file?: PageMutationFile;+ apply(tx: BrainEngine, preimage: PageSnapshot | null): Promise<void>;+}export type PreparedMutation = PreparedMutationBase & (- | { target?: 'page'; file?: PageMutationFile; files?: never }+ | { target?: 'page'; file?: PageMutationFile; files?: never; companions?: readonly CompanionPage[] }| { target: 'skill_bundle'; file?: never; files: MutationFile[]; validate(tx: BrainEngine): Promise<void> });export interface PublicationHooks {@@ -461,11 +475,14 @@ export async function publishMutation(engine: BrainEngine, row: WriteRequest, prlet afterCommitDue: WriteRequest | null = null;let createdPage = false;const skill = prepared.target === 'skill_bundle';- const files = skill ? prepared.files ?? [] : prepared.file ? [prepared.file] : [];+ const companions = prepared.target === 'skill_bundle' ? [] : prepared.companions ?? [];+ // GBRA-190 G4 (D2): the request's own page file first, then each companion's, in one recovery record and one commit.+ const files = skill ? prepared.files ?? [] : [...(prepared.file ? [prepared.file] : []), ...companions.flatMap(companion => companion.file ? [companion.file] : [])];const beliefReport = { appended: 0 };try {assertMutationProtocol(row);- if ((row.target_kind ?? 'page') !== (prepared.target ?? 'page') || (skill ? !!prepared.file || !files.length : prepared.files !== undefined)) {+ if ((row.target_kind ?? 'page') !== (prepared.target ?? 'page') || (skill ? !!prepared.file || !files.length : prepared.files !== undefined)+ || (companions.length > 0 && row.protocol_version !== 2)) {throw opError('unsupported_mutation_protocol', 'Prepared mutation does not match its accepted target.',`Request ${row.request_id} in source ${row.source_id} was prepared for a different target than it was accepted for, so nothing was published. This is an internal mismatch, not a caller error: inspect the request and report it to the user; do not resubmit it unchanged.`,{ fix: requestFix(row) });@@ -523,26 +540,41 @@ export async function publishMutation(engine: BrainEngine, row: WriteRequest, pr}}});- } else if (prepared.file && !prepared.noop) {- if (!binding || !lock || !isWriteTargetContained(prepared.file.path, prepared.file.root)) throw opError('storage_error', 'Filesystem publication requires a confined canonical owner.',+ } else if (files.length && !prepared.noop) {+ if (!binding || !lock || files.some(file => !isWriteTargetContained(file.path, file.root))) throw opError('storage_error', 'Filesystem publication requires a confined canonical owner.',`This host does not hold source ${row.source_id}'s canonical worktree, or the file of ${row.slug} resolves outside it, so request ${row.request_id} wrote no file. Inspect the owner; the write publishes only on the host that owns the source.`,{ fix: ownerStatusFix(row.source_id) });- const { record, bytes } = pageRecoveryRecord(row, prepared.file, binding);- if (binding.canonical_git === true) record.door = await doorMarker(binding.local_path!);- // G2: a strict write replayed after its door commit landed finds its own bytes, committed (git-door.ts).- if (prepared.file.expectedBeforeHash !== undefined && record.beforeHash !== prepared.file.expectedBeforeHash && !await replayAfterDoorCommit(record)) {+ const pages = [...(prepared.file ? [{ slug: row.slug, observedRevision: prepared.observedRevision }] : []),+ ...companions.flatMap(companion => companion.file ? [{ slug: companion.slug, observedRevision: companion.observedRevision }] : [])];+ const marker = binding.canonical_git === true ? await doorMarker(binding.local_path!) : undefined;+ const built = files.map((file, index) => {+ const page = pageRecoveryRecord(row, file, binding!);+ if (marker) page.record.door = marker;+ return { ...page, file, page: pages[index]! };+ });+ for (const { record, file, page } of built) {+ // G2: a strict write replayed after its door commit landed finds its own bytes, committed (git-door.ts).+ if (file.expectedBeforeHash === undefined || record.beforeHash === file.expectedBeforeHash || await replayAfterDoorCommit(record)) continue;// A coordinated writer (a withdrawal mirror) also advanced the page:// reprepare against it. Bytes changed at an unchanged revision are an// uncoordinated edit.- const current = await engine.readPageSnapshot(row.slug, { sourceId: row.source_id, includeDeleted: true });- if ((current?.revision ?? null) !== prepared.observedRevision) {+ const current = await engine.readPageSnapshot(page.slug, { sourceId: row.source_id, includeDeleted: true });+ if ((current?.revision ?? null) !== page.observedRevision) {throw new OperationError('revision_conflict', 'The page changed during preparation.', 'Read its current revision and submit the updated intent with a new request_id.');}throw localEditRefusal('The canonical file changed after preparation.', row, skill, 'after the write was prepared, at an unchanged page revision');}- await prepareRecovery(engine, row, record, bytes);+ if (built.length > 1 && (built.length > PAGES_RECOVERY_MAX_FILES || built.some(({ record }) => record.root !== built[0]!.record.root))) {+ throw opError('storage_error', 'A multi-page publication must stay under one canonical root.',+ `Request ${row.request_id} in source ${row.source_id} writes ${built.length} page files that do not share one canonical root (or more than ${PAGES_RECOVERY_MAX_FILES}), so nothing was written. Inspect the request; if it repeats, run gbrain doctor --json and report it to the user.`,+ { fix: requestFix(row) });+ }+ // One file keeps its version 1 record; several page files share one version 3 record (model.ts PagesRecoveryRecord).+ const record: RecoveryRecord = built.length === 1 ? built[0]!.record+ : { version: 3, target: 'pages', root: built[0]!.record.root, ownerEpoch: String(binding.owner_epoch), attempt: row.execution_token!, files: built.map(entry => entry.record) };+ await prepareRecovery(engine, row, record, built.reduce((sum, entry) => sum + entry.bytes, 0));recovery = record;- await stageLargeFiles(engine, row, prepared.file, record);+ for (const entry of built) await stageLargeFiles(engine, row, entry.file, entry.record);await hooks.boundary?.('prepared', row);}const done = await publicationTransaction(engine, async tx => {@@ -565,10 +597,12 @@ export async function publishMutation(engine: BrainEngine, row: WriteRequest, pr`Another worker took over request ${row.request_id} (its execution claim expired or was reassigned) before this attempt published, so this attempt wrote nothing and the current holder decides the outcome. Inspect the request rather than resubmitting it.`,{ fix: requestFix(row) });let snapshot: PageSnapshot | null = null;+ const companionSnapshots = new Map<string, PageSnapshot | null>();if (skill) await assertSharedSkillPersistence(tx, row.source_id);else {await assertKnowledgePublicationAllowed(tx, row, prepared.file);- await tx.lockPageKeys([{ sourceId: row.source_id, slug: row.slug },...(prepared.additionalPageKeys??[])]);+ await tx.lockPageKeys([{ sourceId: row.source_id, slug: row.slug },...(prepared.additionalPageKeys??[]),+ ...companions.map(companion => ({ sourceId: row.source_id, slug: companion.slug }))]);snapshot = await tx.readPageSnapshot(row.slug, { sourceId: row.source_id, includeDeleted: true });// A rename moves an existing page (its old slug is an additional key): not a new page.createdPage = snapshot === null && !prepared.additionalPageKeys?.length;@@ -576,6 +610,12 @@ export async function publishMutation(engine: BrainEngine, row: WriteRequest, prif ((snapshot?.page.id ?? null) !== row.page_id) throw pageIdentityError(snapshot != null || row.page_id === null, 'The accepted page was deleted or recreated.');await assertUnboundPublication(tx, row, snapshot?.page.source_path);if ((snapshot?.revision ?? null) !== prepared.observedRevision) throw new OperationError('revision_conflict', 'The page changed during preparation.', 'Read its current revision and submit the updated intent with a new request_id.');+ for (const companion of companions) {+ const current = await tx.readPageSnapshot(companion.slug, { sourceId: row.source_id, includeDeleted: true });+ if ((current?.page.id ?? null) !== companion.pageId) throw pageIdentityError(current != null || companion.pageId === null, 'A page this write also changes was deleted or recreated.');+ if ((current?.revision ?? null) !== companion.observedRevision) throw new OperationError('revision_conflict', 'A page this write also changes changed during preparation.', 'Read its current revision and submit the updated intent with a new request_id.');+ companionSnapshots.set(companion.slug, current);+ }}await prepared.validate?.(tx);// #5409: a file target prepared before the source became a read-only mirror is never published.@@ -583,9 +623,11 @@ export async function publishMutation(engine: BrainEngine, row: WriteRequest, prthrow new OperationError('source_changed', 'The source became a read-only mirror after this write was prepared; nothing was written to its checkout.','Retry the write with a new request_id; it is now stored database-only.');}- const door = recovery?.version === 1 ? recovery : null;+ // G2: a strict publication's page files (one, or every file of a multi-page publication) carry the door marker.+ const doorFiles = recovery && !isBundleRecovery(recovery) ? recoveryFiles(recovery) : [];+ const door = doorFiles[0]?.door ?? null;// A write prepared strict rechecks its flag under the source lock; one prepared without it publishes as before (only conversion sets the flag).- if (door?.door && !await sourceCanonicalGit(tx, row.source_id, true)) throw strictChanged(row.source_id);+ if (door && !await sourceCanonicalGit(tx, row.source_id, true)) throw strictChanged(row.source_id);// G7a (git-declared.ts): a strict publication never writes or commits a private page's bytes.if (!skill) await assertNoPrivateCommit(tx, row, prepared, snapshot, binding);if (recovery) {@@ -613,9 +655,14 @@ export async function publishMutation(engine: BrainEngine, row: WriteRequest, pr}prepared.postimage = undefined;// W1 finalization contract (docs/designs/BELIEF_LEDGER.md 5.1): the ledger append is the last canonical write before the receipt.- const apply = () => timePublicationStep('apply', row.slug, () => prepared.apply(tx, snapshot));+ const apply = () => timePublicationStep('apply', row.slug, async () => {+ const result = await prepared.apply(tx, snapshot);+ for (const companion of companions) await companion.apply(tx, companionSnapshots.get(companion.slug) ?? null);+ return result;+ });+ const beliefKeys = companions.length ? [...(prepared.additionalPageKeys ?? []), ...companions.map(companion => ({ sourceId: row.source_id, slug: companion.slug }))] : prepared.additionalPageKeys;const outcome = await withCoordinatedWrite(tx, [row.source_id], skill ? apply- : () => withBeliefBatch(tx, publicationBeliefOptions(row, prepared.additionalPageKeys, beliefReport), apply), publicationAttribution(row, prepared.trust));+ : () => withBeliefBatch(tx, publicationBeliefOptions(row, beliefKeys, beliefReport), apply), publicationAttribution(row, prepared.trust));if (!skill) await classifyUnboundPage(tx, row);if (prepared.databaseOnlyReason === 'mirror_read_only') await classifyMirrorPage(tx, row);const final = skill ? null : await publicationPostimage(tx, row, prepared);@@ -624,8 +671,19 @@ export async function publishMutation(engine: BrainEngine, row: WriteRequest, prdecoratePublicationOutcome(row, prepared, outcome, final, files.length, skill);await recordPublicationFenceTrend(tx, row, outcome);// G2: a strict source's file is committed before its row; its Git effect only pushes.- if (door?.door) Object.assign(outcome.persistence as object, { git_state: 'committed', git_commit: await commitThroughDoor(door.door.root, [{ path: door.path, note: prepared.file?.commit }], lock ?? undefined) });- await timePublicationStep('effects', row.slug, () => queuePublicationEffects(tx, row, final, outcome, prepared, { pushOnly: !!door?.door }));+ if (door) Object.assign(outcome.persistence as object, { git_state: 'committed', git_commit: await commitThroughDoor(door.root,+ doorFiles.map((record, index) => ({ path: record.path, note: (files[index] as PageMutationFile | undefined)?.commit })), lock ?? undefined) });+ // D2: a multi-page publication's Git and embedding effects walk every page it wrote (effect-targets.ts targets).+ let pageTargets: { slug: string; page_id: number; revision: string }[] | undefined;+ if (companions.length) {+ pageTargets = [];+ for (const slug of [row.slug, ...companions.map(companion => companion.slug)]) {+ const page = slug === row.slug ? final : await tx.readPageSnapshot(slug, { sourceId: row.source_id, includeDeleted: true });+ if (page && !page.page.deleted_at) pageTargets.push({ slug, page_id: Number(page.page.id), revision: page.revision });+ }+ pageTargets.sort((a, b) => a.slug < b.slug ? -1 : a.slug > b.slug ? 1 : 0);+ }+ await timePublicationStep('effects', row.slug, () => queuePublicationEffects(tx, row, final, outcome, prepared, { pushOnly: !!door, ...(pageTargets ? { pageTargets } : {}) }));if (prepared.afterEffects) await withCoordinatedWrite(tx, [row.source_id], () => prepared.afterEffects!(tx, outcome), publicationAttribution(row, prepared.trust));await hooks.boundary?.('before_commit', row);const committed = await completeWrite(tx, current, 'committed', outcome, undefined, current);@@ -635,9 +693,9 @@ export async function publishMutation(engine: BrainEngine, row: WriteRequest, prawait hooks.boundary?.('after_commit', done);if (beliefReport.appended && done.state === 'committed') await markBeliefCommits(engine, [row.id]).catch(() => undefined);if (recovery) {- // A version 3 record's prior-file copy is removed once the outcome is durable, before its record is cleared.+ // A large prior file's copy (staging.before) is removed once the outcome is durable, before its record is cleared.const staged = recovery;- if (staged.version === 1 && staged.staging?.before) await withFilesystemPublication([staged.root], async () => cleanupRecoveryStaging(staged));+ if (!isBundleRecovery(staged)) for (const file of recoveryFiles(staged)) if (file.staging?.before) await withFilesystemPublication([file.root], async () => cleanupRecoveryStaging(file));await clearResolvedRecovery(engine, row.id, done);}if (done.state === 'committed') afterCommitDue = done;@@ -709,7 +767,7 @@ export async function recoverPublication(engine: BrainEngine, id: string, hostIdif (!current.recovery) return current;const records = recoveryFiles(current.recovery);let landed: string | null = null;- if (current.recovery.version === 2) {+ if (isBundleRecovery(current.recovery)) {const owner = await guardOwnership(tx, current, hostId);if (!owner) throw opError('owner_unavailable', 'Skill recovery requires its canonical owner.',`This host no longer holds source ${current.source_id}'s current owner epoch, so shared-skill request ${current.request_id} stays recovering until its owner finishes it. Inspect the owner; its resident writer finishes the recovery.`,@@ -721,7 +779,7 @@ export async function recoverPublication(engine: BrainEngine, id: string, hostId{ fix: ownerStatusFix(current.source_id) });try {if (!isTerminal(current)) for (const record of records) {- const actual = current.recovery.version === 2 ? bundleFileHash(record) : fileHash(record.path);+ const actual = isBundleRecovery(current.recovery) ? bundleFileHash(record) : fileHash(record.path);if (actual !== record.beforeHash && actual !== record.afterHash) throw unexpectedRecoveryBytes('Canonical recovery bytes changed outside publication.', current, 'was edited outside gbrain and');}// A terminal outcome's prior-file copy is dropped unread when its canonical file still holds the prior bytes.@@ -733,10 +791,10 @@ export async function recoverPublication(engine: BrainEngine, id: string, hostIdif (!isTerminal(current)) for (let index = 0; index < records.length; index++) {const record = records[index];hooks.fileBoundary?.('before_restore', current, index);- const actual = current.recovery.version === 2 ? bundleFileHash(record) : fileHash(record.path);+ const actual = isBundleRecovery(current.recovery) ? bundleFileHash(record) : fileHash(record.path);if (actual !== record.beforeHash && actual !== record.afterHash) throw unexpectedRecoveryBytes('Canonical recovery bytes changed during restoration.', current, 'changed while recovery was restoring it and');// G2: a strict publication whose commit landed keeps the committed file; Git holds it.- if (current.recovery.version === 1 && await doorCommitLanded(record)) {+ if (!isBundleRecovery(current.recovery) && await doorCommitLanded(record)) {landed = await landedCommit(record.door!.root, record.door!.head, record.path);if (record.staging?.before) await withFilesystemPublication([record.root], async () => cleanupRecoveryStaging(record, { priorIntact: true }));} else if (record.staging?.before) {@@ -747,7 +805,7 @@ export async function recoverPublication(engine: BrainEngine, id: string, hostId} else if (actual === record.afterHash && actual !== record.beforeHash) {await withFilesystemPublication([record.root], async () => {const file = { path: record.path, root: record.root, content: record.before === null ? null : Buffer.from(record.before, 'base64') };- if (current.recovery!.version === 2) {+ if (isBundleRecovery(current.recovery!)) {const restored = { ...record, beforeHash: record.afterHash, afterHash: record.beforeHash,mode: record.afterHash === null ? null : record.afterMode ?? record.mode, afterMode: record.mode ?? undefined,staging: { publication: record.staging?.restoration } };diff --git a/src/core/persistence/effect-journal.ts b/src/core/persistence/effect-journal.tsindex a0f0eae5a7..af991b64d9 100644--- a/src/core/persistence/effect-journal.ts+++ b/src/core/persistence/effect-journal.ts@@ -26,7 +26,9 @@ import { EFFECT_FAULT_POINTS, faultPoint } from './fault-points.ts';export async function queuePublicationEffects(tx: BrainEngine, row: EffectRequest & Partial<Pick<WriteRequest, 'operation' | 'intent' | 'authority' | 'principal_kind' | 'principal_id'>>, snapshot: PageSnapshot | null,outcome: Record<string, unknown>, prepared?: PreparedMutation,/** A grouped publication completes its members after queueing all of them, then calls `reconcileFinishedBatch` itself. */- opts: { deferBatchReconcile?: boolean; /** G2 (git-door.ts): the file is already committed; its Git effect only pushes. */ pushOnly?: boolean } = {}): Promise<void> {+ opts: { deferBatchReconcile?: boolean; /** G2 (git-door.ts): the file is already committed; its Git effect only pushes. */ pushOnly?: boolean;+ /** GBRA-190 G4 (D2): every page a multi-page publication wrote, sorted by slug; its Git and embedding effects walk them (effect-targets.ts). */+ pageTargets?: readonly { slug: string; page_id: number; revision: string }[] } = {}): Promise<void> {if (prepared?.noop || prepared?.target === 'skill_bundle') return;await declarePersistenceProtocol(tx);const revision = snapshot?.revision;@@ -34,7 +36,11 @@ export async function queuePublicationEffects(tx: BrainEngine, row: EffectReques// #6007: the effects are inserted together, in queue order, by one statement at the end.const queued: { kind: EffectKind; data: Record<string, unknown>; gated?: boolean }[] = [];const queue = (kind: EffectKind, extra: Record<string, unknown> = {}) => { queued.push({ kind, data: { ...data, ...extra } }); };- if (prepared?.file && row.worktree_id) {+ const companionFiles = (prepared?.companions ?? []).some(companion => companion.file);+ if (opts.pageTargets && (prepared?.file || companionFiles) && row.worktree_id) {+ queue('git', { version: 2, targets: opts.pageTargets, ...(opts.pushOnly ? { push_only: true } : {}) });+ if (!opts.pushOnly && outcome.persistence && typeof outcome.persistence === 'object') Object.assign(outcome.persistence, { git_state: 'queued' });+ } else if (prepared?.file && row.worktree_id) {const [binding] = await tx.executeRaw<{ local_path: string }>(`SELECT h.local_path FROM persistence_host_bindings hJOIN persistence_worktrees w ON w.id=h.worktree_id AND w.owner_host_id=h.host_id WHERE w.id=$1::uuid`, [row.worktree_id]);if (!binding?.local_path) throw opError('owner_unavailable', 'Cannot record the canonical Git target without its owner binding.',@@ -47,7 +53,7 @@ export async function queuePublicationEffects(tx: BrainEngine, row: EffectRequesif (!opts.pushOnly && outcome.persistence && typeof outcome.persistence === 'object') Object.assign(outcome.persistence, { git_state: 'queued' });}if (snapshot && !snapshot.page.deleted_at) {- if (!prepared?.deferEmbedding) queue('embedding');+ if (!prepared?.deferEmbedding) queue('embedding', opts.pageTargets ? { version: 2, targets: opts.pageTargets } : {});outcome.embedding_state = await embeddingDisabled(tx) ? 'disabled' : prepared?.deferEmbedding ? 'deferred' : 'queued';if ((outcome.facts_backstop as { queued?: boolean } | undefined)?.queued) {if (!(await isFactsExtractionEnabled(tx))) outcome.facts_backstop = { skipped: 'extraction_disabled' };@@ -57,7 +63,7 @@ export async function queuePublicationEffects(tx: BrainEngine, row: EffectRequesif (queuesMentionLinks(row, prepared)) queued.push({ kind: 'links', data: { ...data, ...(prepared?.mentionRange ? { range: prepared.mentionRange } : {}) }, gated: true });// #5876: the Life Chronicle decision is a ledger row, not an effect; the `chronicle` cycle phase executes it.await recordChronicleDecision(tx, row, snapshot, outcome);- }+ } else if (opts.pageTargets?.length && !prepared?.deferEmbedding) queue('embedding', { version: 2, targets: opts.pageTargets });const inserted = queued.length ? await tx.executeRaw<{ kind: string }>(`INSERT INTO persistence_effects (request_id,kind,revision,data,source_id,source_incarnation,worktree_id)SELECT $1::uuid,t.e->>'kind',$2::uuid,t.e->'data',$3,$4::uuid,$5::uuid FROM jsonb_array_elements($6::text::jsonb) WITH ORDINALITY AS t(e,n)WHERE NOT (COALESCE((t.e->>'gated')::boolean,false) AND EXISTS (SELECT 1 FROM configdiff --git a/src/core/persistence/group-publish.ts b/src/core/persistence/group-publish.tsindex 181d96a100..fc37cebf9b 100644--- a/src/core/persistence/group-publish.ts+++ b/src/core/persistence/group-publish.ts@@ -97,7 +97,8 @@ export function singleWrite(row: Pick<WriteRequest, 'operation' | 'intent'>): bo/** Whether a prepared member can share a group transaction. */export function groupable(row: WriteRequest, prepared: PreparedMutation): boolean {- if ((row.target_kind ?? 'page') !== 'page' || prepared.target === 'skill_bundle' || prepared.sourceExclusive || prepared.exclusiveSources?.length || prepared.afterEffects) return false;+ if ((row.target_kind ?? 'page') !== 'page' || prepared.target === 'skill_bundle' || prepared.sourceExclusive || prepared.exclusiveSources?.length || prepared.afterEffects+ || prepared.companions?.length || (row.protocol_version ?? 1) !== 1) return false;if (syncMember(row)) return !prepared.file && typeof prepared.validate === 'function';// A streamed file (large-file.ts) is staged before its publication transaction, which only publishMutation does.if (isStreamedContent(prepared.file?.content)) return false;diff --git a/src/core/persistence/memory-mutations.ts b/src/core/persistence/memory-mutations.tsindex 6aa956c3f3..bfb3c1a935 100644--- a/src/core/persistence/memory-mutations.ts+++ b/src/core/persistence/memory-mutations.ts@@ -99,8 +99,10 @@ async function planRememberTarget(ctx: OperationContext, sourceId: string, sourcif (inferred && (await isFactWithdrawn(ctx.engine, sourceId, inferred.visibility, inferred.fact, slug)|| parseFactsFence(whole!.compiled_truth).warnings.length)) throw new InferredTargetRejected('ENTITY_LINK_FAILED');// Preserve the stub guard: a fallback name remains DB-only until a real- // entity page exists. No placeholder page is created by remember.- const fence = entitySlug !== null && snapshot !== null;+ // entity page exists. No placeholder entity page is created by remember; a+ // fact without an entity is a row of memory/unattributed, created on first use (GBRA-190 G4).+ const unattributed = entitySlug === null;+ let fence = unattributed || snapshot !== null;const sandbox = ctx.viaSubagent === true && !(ctx.allowedSlugPrefixes?.length);const configuredWriteThrough = !/^(false|0|off|no)$/i.test(await ctx.engine.getConfig('sync.write_through') ?? 'true');const writeThrough = configuredWriteThrough && !sandbox;@@ -108,10 +110,13 @@ async function planRememberTarget(ctx: OperationContext, sourceId: string, sourcelse if (!configuredWriteThrough) authority.databaseOnlyReason = 'disabled_by_config';// An inferred link never designates an owner or reports a missing one.const target = fence ? await resolveFactWriteTarget(ctx.engine, sourceId, source,- { sandbox, fileBacked: Boolean(snapshot!.page.source_path), remote: ctx.remote !== false }).catch((error: unknown) => {+ { sandbox, fileBacked: snapshot ? Boolean(snapshot.page.source_path) : true, remote: ctx.remote !== false }).catch((error: unknown) => {if (inferred && error instanceof OperationError) throw new InferredTargetRejected('ENTITY_LINK_FAILED');+ // A source that refuses a new canonical file keeps the subjectless fact database-only, as before memory/unattributed had a page.+ if (unattributed && !snapshot && error instanceof OperationError) return null;throw error;}) : null;+ if (unattributed && !snapshot && !target) fence = false;let binding = target?.kind === 'publish' ? target.binding : null;if (target?.kind === 'publish' && target.databaseOnlyReason) authority.databaseOnlyReason = target.databaseOnlyReason;if (target?.kind === 'unbound') {diff --git a/src/core/persistence/memory-prepare.ts b/src/core/persistence/memory-prepare.tsindex 82809d7579..c20f0bc27f 100644--- a/src/core/persistence/memory-prepare.ts+++ b/src/core/persistence/memory-prepare.ts@@ -21,6 +21,7 @@ import { fenceAppendPendingTier } from '../eligibility/fence-overlay.ts';import { prepareFenceFactAppend, requestReceiptFix, type FenceFactAppend } from '../facts/fence-fact-append.ts';import { privateProvenanceFilterFragment, resolveExcludePrivatePages } from '../search/private-visibility.ts';import { tightenToPage } from '../facts/visibility.ts';+import { UNATTRIBUTED_MEMORY_SLUG } from '../facts/extract-from-fence.ts';import { noteBelief } from '../belief/ledger.ts';function conflict(row: WriteRequest): never {@@ -135,7 +136,7 @@ export async function prepareMemoryMutation(engine: BrainEngine, row: WriteRequeconst retiredUntil = status === 'superseded' ? supersededValidUntil(decision.candidate!, validFrom) : null;// The fact is published as a row of its entity page's facts fence, file before facts row (facts/fence-fact-append.ts).let fence: FenceFactAppend | undefined;- if (p.fence === true && snapshot) {+ if (p.fence === true && (snapshot || row.slug === UNATTRIBUTED_MEMORY_SLUG)) {const old = decision.candidate;fence = await prepareFenceFactAppend(engine, row, config, snapshot, { fact, pendingTier: fenceAppendPendingTier(writerTier),supersede: status === 'superseded' && old?.source_markdown_slug === row.slug && old.row_num != null ? { rowNum: Number(old.row_num), validUntil: retiredUntil } : undefined }, signal);diff --git a/src/core/persistence/model.ts b/src/core/persistence/model.tsindex dc1a890fcd..25549e3262 100644--- a/src/core/persistence/model.ts+++ b/src/core/persistence/model.ts@@ -59,14 +59,37 @@ export interface BundleRecoveryRecord {staging?: never;beforeHash?: never;}-export type RecoveryRecord = FileRecoveryRecord | BundleRecoveryRecord;+/**+ * GBRA-190 G4 (D2): the page files one publication writes together (a withdrawal's pages), restored together and+ * committed in one Git commit. Each file is a page file record (version 1 fields, door included on a strict source);+ * `files[0]` is the request's own page when it has a file. Binaries that predate it refuse version 3 unread.+ */+export interface PagesRecoveryRecord {+ version: 3;+ target: 'pages';+ root: string;+ ownerEpoch: string;+ attempt: string;+ files: FileRecoveryRecord[];+ staging?: never;+ beforeHash?: never;+}+export type RecoveryRecord = FileRecoveryRecord | BundleRecoveryRecord | PagesRecoveryRecord;+/** The most page files one publication writes together (a withdrawal's bound, withdrawal-discovery.ts). */+export const PAGES_RECOVERY_MAX_FILES = 256;export function recoveryFiles(record: RecoveryRecord): FileRecoveryRecord[] {assertRecoveryVersion('persistence_requests', record, null);if (record.version === 1) return [record];if (record.version === 2 && record.target === 'skill_bundle' && Array.isArray(record.files)&& record.files.length > 0 && record.files.length <= 128 && record.files.every(file => file.version === 1)) return record.files;+ if (record.version === 3 && record.target === 'pages' && Array.isArray(record.files)+ && record.files.length > 0 && record.files.length <= PAGES_RECOVERY_MAX_FILES && record.files.every(file => file.version === 1)) return record.files;throw new Error('unsupported_mutation_protocol');}+/** A shared-skill bundle's record, whose files are bundle files (bundle-files.ts), not page files. */+export function isBundleRecovery(record: RecoveryRecord): record is BundleRecoveryRecord {+ return record.version === 2;+}export interface WriteRequest {id: string;principal_kind: Principal['kind'];diff --git a/src/core/persistence/protocol.ts b/src/core/persistence/protocol.tsindex 61e857aad2..184a38b331 100644--- a/src/core/persistence/protocol.ts+++ b/src/core/persistence/protocol.ts@@ -61,7 +61,8 @@ export function isPersistenceDeclaration(statement: string): boolean {export const PERSISTENCE_PROTOCOL_PREDICATE = "set_config('gbrain.persistence_protocol','2',true)='2'";export function assertMutationProtocol(row: Pick<WriteRequest, 'target_kind' | 'protocol_version'>): void {- if (((row.target_kind ?? 'page') === 'page' && (row.protocol_version ?? 1) === 1)+ // GBRA-190 G4 (D2): a page request at protocol 2 may publish several pages together (a withdrawal).+ if (((row.target_kind ?? 'page') === 'page' && [1, 2].includes(row.protocol_version ?? 1))|| (row.target_kind === 'skill_bundle' && row.protocol_version === 2)) return;throw opError('unsupported_mutation_protocol', 'This consumer does not support the request target and protocol version.',`This gbrain process cannot apply ${row.target_kind ?? 'page'} requests at protocol ${row.protocol_version ?? 1}, so it left the request untouched. A newer gbrain wrote it: upgrading gbrain on this host (the user's call) lets it be applied.`);diff --git a/src/core/persistence/recovery-version.ts b/src/core/persistence/recovery-version.tsindex 49affab07e..bb8680d4cd 100644--- a/src/core/persistence/recovery-version.ts+++ b/src/core/persistence/recovery-version.ts@@ -11,8 +11,8 @@ import type { Action } from '../agent-output.ts';/** `persistence_effects.recovery` (effect-model.ts `EffectRecovery`): 1 embeds the file, 2 names a streamed stage. */export const EFFECT_RECOVERY_VERSIONS: readonly number[] = [1, 2];-/** `persistence_requests.recovery` (model.ts `RecoveryRecord`): 1 one file, 2 a shared-skill bundle. */-export const REQUEST_RECOVERY_VERSIONS: readonly number[] = [1, 2];+/** `persistence_requests.recovery` (model.ts `RecoveryRecord`): 1 one file, 2 a shared-skill bundle, 3 several page files (GBRA-190). */+export const REQUEST_RECOVERY_VERSIONS: readonly number[] = [1, 2, 3];export type RecoveryTable = 'persistence_requests' | 'persistence_effects';const KNOWN: Record<RecoveryTable, readonly number[]> = { persistence_requests: REQUEST_RECOVERY_VERSIONS, persistence_effects: EFFECT_RECOVERY_VERSIONS };diff --git a/src/core/pglite-schema.generated.ts b/src/core/pglite-schema.generated.tsindex ba667bf4dd..afb9251e6b 100644--- a/src/core/pglite-schema.generated.ts+++ b/src/core/pglite-schema.generated.ts@@ -2039,7 +2039,7 @@ CREATE OR REPLACE FUNCTION gbrain_require_persistence_protocol(required integer)RAISE EXCEPTION 'writer_upgrade_required: this mutation requires persistence protocol 2' USING ERRCODE='42501';END IF;END \$\$;-CREATE OR REPLACE FUNCTION gbrain_guard_request_protocol() RETURNS trigger LANGUAGE plpgsql SET search_path = pg_catalog, public AS \$\$+CREATE OR REPLACE FUNCTION gbrain_guard_request_protocol() RETURNS trigger LANGUAGE plpgsql SET search_path = pg_catalog, public AS \$DECLARE target text; version integer; floor integer; active boolean; record jsonb;BEGINIF TG_OP='DELETE' THEN target:=OLD.target_kind; version:=OLD.protocol_version;@@ -2065,17 +2065,18 @@ CREATE OR REPLACE FUNCTION gbrain_guard_request_protocol() RETURNS trigger LANGUWHERE w.id=NEW.worktree_id AND w.state='active') THENRAISE EXCEPTION 'writer_not_quiesced: canonical owner capability must be revalidated' USING ERRCODE='42501';END IF;- ELSIF version<>1 THEN+ ELSIF version NOT IN (1,2) THENRAISE EXCEPTION 'unsupported_mutation_protocol: invalid page target' USING ERRCODE='42501';END IF;record:=NEW.recovery;- IF record IS NOT NULL AND ((target='page' AND record->>'version' IS DISTINCT FROM '1')+ IF record IS NOT NULL AND ((target='page' AND record->>'version' IS DISTINCT FROM '1'+ AND NOT (record->>'version'='3' AND record->>'target'='pages' AND jsonb_typeof(record->'files')='array'))OR (target='skill_bundle' AND (record->>'version' IS DISTINCT FROM '2' OR record->>'target' IS DISTINCT FROM 'skill_bundle'OR jsonb_typeof(record->'files') IS DISTINCT FROM 'array'))) THENRAISE EXCEPTION 'unsupported_mutation_protocol: recovery target mismatch' USING ERRCODE='42501';END IF;RETURN NEW;- END \$\$;+ END \$;DROP TRIGGER IF EXISTS gbrain_request_protocol ON persistence_requests;CREATE TRIGGER gbrain_request_protocol BEFORE INSERT OR UPDATE OR DELETE ON persistence_requestsFOR EACH ROW EXECUTE FUNCTION gbrain_guard_request_protocol();diff --git a/src/core/schema-embedded.generated.ts b/src/core/schema-embedded.generated.tsindex 6863a511d6..6b6aa49b1b 100644--- a/src/core/schema-embedded.generated.ts+++ b/src/core/schema-embedded.generated.ts@@ -2798,7 +2798,7 @@ CREATE OR REPLACE FUNCTION gbrain_require_persistence_protocol(required integer)RAISE EXCEPTION 'writer_upgrade_required: this mutation requires persistence protocol 2' USING ERRCODE='42501';END IF;END \$\$;-CREATE OR REPLACE FUNCTION gbrain_guard_request_protocol() RETURNS trigger LANGUAGE plpgsql SET search_path = pg_catalog, public AS \$\$+CREATE OR REPLACE FUNCTION gbrain_guard_request_protocol() RETURNS trigger LANGUAGE plpgsql SET search_path = pg_catalog, public AS \$DECLARE target text; version integer; floor integer; active boolean; record jsonb;BEGINIF TG_OP='DELETE' THEN target:=OLD.target_kind; version:=OLD.protocol_version;@@ -2824,17 +2824,18 @@ CREATE OR REPLACE FUNCTION gbrain_guard_request_protocol() RETURNS trigger LANGUWHERE w.id=NEW.worktree_id AND w.state='active') THENRAISE EXCEPTION 'writer_not_quiesced: canonical owner capability must be revalidated' USING ERRCODE='42501';END IF;- ELSIF version<>1 THEN+ ELSIF version NOT IN (1,2) THENRAISE EXCEPTION 'unsupported_mutation_protocol: invalid page target' USING ERRCODE='42501';END IF;record:=NEW.recovery;- IF record IS NOT NULL AND ((target='page' AND record->>'version' IS DISTINCT FROM '1')+ IF record IS NOT NULL AND ((target='page' AND record->>'version' IS DISTINCT FROM '1'+ AND NOT (record->>'version'='3' AND record->>'target'='pages' AND jsonb_typeof(record->'files')='array'))OR (target='skill_bundle' AND (record->>'version' IS DISTINCT FROM '2' OR record->>'target' IS DISTINCT FROM 'skill_bundle'OR jsonb_typeof(record->'files') IS DISTINCT FROM 'array'))) THENRAISE EXCEPTION 'unsupported_mutation_protocol: recovery target mismatch' USING ERRCODE='42501';END IF;RETURN NEW;- END \$\$;+ END \$;DROP TRIGGER IF EXISTS gbrain_request_protocol ON persistence_requests;CREATE TRIGGER gbrain_request_protocol BEFORE INSERT OR UPDATE OR DELETE ON persistence_requestsFOR EACH ROW EXECUTE FUNCTION gbrain_guard_request_protocol();diff --git a/src/core/schema-migrations/latest.generated.ts b/src/core/schema-migrations/latest.generated.tsindex 6d1e21ecc7..4f1b5b8a21 100644--- a/src/core/schema-migrations/latest.generated.ts+++ b/src/core/schema-migrations/latest.generated.ts@@ -4,4 +4,4 @@// The highest schema migration version (migrate.ts LATEST_VERSION), importable without// loading the migrations themselves.-export const LATEST_SCHEMA_VERSION = 274;+export const LATEST_SCHEMA_VERSION = 275;diff --git a/src/core/schema-migrations/registry.generated.ts b/src/core/schema-migrations/registry.generated.tsindex 91b70f5a9d..c0729630d1 100644--- a/src/core/schema-migrations/registry.generated.ts+++ b/src/core/schema-migrations/registry.generated.ts@@ -275,6 +275,7 @@ import { v271 } from './v271-facts-superseded-by-index.ts';import { v272 } from './v272-git-canonical-declared.ts';import { v273 } from './v273-segment-derivations.ts';import { v274 } from './v274-pages-withheld-source-path.ts';+import { v275 } from './v275-multi-page-publication-protocol.ts';// Array order is historical (see HISTORICAL_ARRAY_ORDER in the generator); the// runner sorts by version before applying.@@ -548,4 +549,5 @@ export const MIGRATIONS: Migration[] = [v272,v273,v274,+ v275,];diff --git a/src/core/schema-migrations/v275-multi-page-publication-protocol.ts b/src/core/schema-migrations/v275-multi-page-publication-protocol.tsnew file mode 100644index 0000000000..03af5b53f2--- /dev/null+++ b/src/core/schema-migrations/v275-multi-page-publication-protocol.ts@@ -0,0 +1,13 @@+import type { Migration } from './types.ts';+import { REQUEST_PROTOCOL_GUARD_SQL } from '../shared-skills/persistence-schema.ts';++export const v275: Migration = {+ // GBRA-190 G4 (D2): one publication may write several pages (a withdrawal strikes its claim on every page that+ // carries it) and commit them in one Git commit. Such a request is a page target at protocol 2, so a binary that+ // predates it leaves it untouched, and its recovery record is version 3 (several page files), which those binaries+ // refuse unread (recovery-version.ts). Only the trigger function is replaced: no table, column or row changes.+ version: 275,+ name: 'multi_page_publication_protocol',+ idempotent: true,+ sql: REQUEST_PROTOCOL_GUARD_SQL + ';',+};diff --git a/src/core/shared-skills/persistence-schema.ts b/src/core/shared-skills/persistence-schema.tsindex e4d4e2b86b..09c0a55197 100644--- a/src/core/shared-skills/persistence-schema.ts+++ b/src/core/shared-skills/persistence-schema.ts@@ -1,23 +1,9 @@-export const SHARED_SKILLS_PERSISTENCE_SCHEMA_STATEMENTS: readonly string[] = [- `ALTER TABLE persistence_brain ADD COLUMN IF NOT EXISTS writer_protocol_floor integer NOT NULL DEFAULT 1 CHECK (writer_protocol_floor IN (1,2))`,- `ALTER TABLE persistence_brain ADD COLUMN IF NOT EXISTS skill_bundles_enabled boolean NOT NULL DEFAULT false`,- `ALTER TABLE persistence_requests ADD COLUMN IF NOT EXISTS target_kind text NOT NULL DEFAULT 'page' CHECK (target_kind IN ('page','skill_bundle'))`,- `ALTER TABLE persistence_requests ADD COLUMN IF NOT EXISTS protocol_version integer NOT NULL DEFAULT 1 CHECK (protocol_version IN (1,2))`,- `CREATE TABLE IF NOT EXISTS persistence_writer_protocols (- worktree_id uuid NOT NULL REFERENCES persistence_worktrees(id),- host_id uuid NOT NULL,- owner_epoch bigint NOT NULL,- protocol_version integer NOT NULL CHECK (protocol_version=2),- registered_at timestamptz NOT NULL DEFAULT now(),- PRIMARY KEY(worktree_id,host_id)- )`,- `CREATE OR REPLACE FUNCTION gbrain_require_persistence_protocol(required integer) RETURNS void LANGUAGE plpgsql SET search_path = pg_catalog, public AS $$- BEGIN- IF required >= 2 AND COALESCE(current_setting('gbrain.persistence_protocol',true),'') <> '2' THEN- RAISE EXCEPTION 'writer_upgrade_required: this mutation requires persistence protocol 2' USING ERRCODE='42501';- END IF;- END $$`,- `CREATE OR REPLACE FUNCTION gbrain_guard_request_protocol() RETURNS trigger LANGUAGE plpgsql SET search_path = pg_catalog, public AS $$+/**+ * The request protocol guard. GBRA-190 G4 (D2): a page target is protocol 1, or 2 for a request whose publication+ * writes several pages (a withdrawal), and its recovery record is version 1 (one file) or version 3 (several page+ * files, model.ts PagesRecoveryRecord); a binary that predates protocol 2 page requests leaves them untouched.+ */+export const REQUEST_PROTOCOL_GUARD_SQL = `CREATE OR REPLACE FUNCTION gbrain_guard_request_protocol() RETURNS trigger LANGUAGE plpgsql SET search_path = pg_catalog, public AS $DECLARE target text; version integer; floor integer; active boolean; record jsonb;BEGINIF TG_OP='DELETE' THEN target:=OLD.target_kind; version:=OLD.protocol_version;@@ -43,17 +29,39 @@ export const SHARED_SKILLS_PERSISTENCE_SCHEMA_STATEMENTS: readonly string[] = [WHERE w.id=NEW.worktree_id AND w.state='active') THENRAISE EXCEPTION 'writer_not_quiesced: canonical owner capability must be revalidated' USING ERRCODE='42501';END IF;- ELSIF version<>1 THEN+ ELSIF version NOT IN (1,2) THENRAISE EXCEPTION 'unsupported_mutation_protocol: invalid page target' USING ERRCODE='42501';END IF;record:=NEW.recovery;- IF record IS NOT NULL AND ((target='page' AND record->>'version' IS DISTINCT FROM '1')+ IF record IS NOT NULL AND ((target='page' AND record->>'version' IS DISTINCT FROM '1'+ AND NOT (record->>'version'='3' AND record->>'target'='pages' AND jsonb_typeof(record->'files')='array'))OR (target='skill_bundle' AND (record->>'version' IS DISTINCT FROM '2' OR record->>'target' IS DISTINCT FROM 'skill_bundle'OR jsonb_typeof(record->'files') IS DISTINCT FROM 'array'))) THENRAISE EXCEPTION 'unsupported_mutation_protocol: recovery target mismatch' USING ERRCODE='42501';END IF;RETURN NEW;+ END $`;++export const SHARED_SKILLS_PERSISTENCE_SCHEMA_STATEMENTS: readonly string[] = [+ `ALTER TABLE persistence_brain ADD COLUMN IF NOT EXISTS writer_protocol_floor integer NOT NULL DEFAULT 1 CHECK (writer_protocol_floor IN (1,2))`,+ `ALTER TABLE persistence_brain ADD COLUMN IF NOT EXISTS skill_bundles_enabled boolean NOT NULL DEFAULT false`,+ `ALTER TABLE persistence_requests ADD COLUMN IF NOT EXISTS target_kind text NOT NULL DEFAULT 'page' CHECK (target_kind IN ('page','skill_bundle'))`,+ `ALTER TABLE persistence_requests ADD COLUMN IF NOT EXISTS protocol_version integer NOT NULL DEFAULT 1 CHECK (protocol_version IN (1,2))`,+ `CREATE TABLE IF NOT EXISTS persistence_writer_protocols (+ worktree_id uuid NOT NULL REFERENCES persistence_worktrees(id),+ host_id uuid NOT NULL,+ owner_epoch bigint NOT NULL,+ protocol_version integer NOT NULL CHECK (protocol_version=2),+ registered_at timestamptz NOT NULL DEFAULT now(),+ PRIMARY KEY(worktree_id,host_id)+ )`,+ `CREATE OR REPLACE FUNCTION gbrain_require_persistence_protocol(required integer) RETURNS void LANGUAGE plpgsql SET search_path = pg_catalog, public AS $$+ BEGIN+ IF required >= 2 AND COALESCE(current_setting('gbrain.persistence_protocol',true),'') <> '2' THEN+ RAISE EXCEPTION 'writer_upgrade_required: this mutation requires persistence protocol 2' USING ERRCODE='42501';+ END IF;END $$`,+ REQUEST_PROTOCOL_GUARD_SQL,`DROP TRIGGER IF EXISTS gbrain_request_protocol ON persistence_requests`,`CREATE TRIGGER gbrain_request_protocol BEFORE INSERT OR UPDATE OR DELETE ON persistence_requestsFOR EACH ROW EXECUTE FUNCTION gbrain_guard_request_protocol()`,diff --git a/src/schema.sql b/src/schema.sqlindex 7cd85b5ea2..93d142cb34 100644--- a/src/schema.sql+++ b/src/schema.sql@@ -2794,7 +2794,7 @@ CREATE OR REPLACE FUNCTION gbrain_require_persistence_protocol(required integer)RAISE EXCEPTION 'writer_upgrade_required: this mutation requires persistence protocol 2' USING ERRCODE='42501';END IF;END $$;-CREATE OR REPLACE FUNCTION gbrain_guard_request_protocol() RETURNS trigger LANGUAGE plpgsql SET search_path = pg_catalog, public AS $$+CREATE OR REPLACE FUNCTION gbrain_guard_request_protocol() RETURNS trigger LANGUAGE plpgsql SET search_path = pg_catalog, public AS $DECLARE target text; version integer; floor integer; active boolean; record jsonb;BEGINIF TG_OP='DELETE' THEN target:=OLD.target_kind; version:=OLD.protocol_version;@@ -2820,17 +2820,18 @@ CREATE OR REPLACE FUNCTION gbrain_guard_request_protocol() RETURNS trigger LANGUWHERE w.id=NEW.worktree_id AND w.state='active') THENRAISE EXCEPTION 'writer_not_quiesced: canonical owner capability must be revalidated' USING ERRCODE='42501';END IF;- ELSIF version<>1 THEN+ ELSIF version NOT IN (1,2) THENRAISE EXCEPTION 'unsupported_mutation_protocol: invalid page target' USING ERRCODE='42501';END IF;record:=NEW.recovery;- IF record IS NOT NULL AND ((target='page' AND record->>'version' IS DISTINCT FROM '1')+ IF record IS NOT NULL AND ((target='page' AND record->>'version' IS DISTINCT FROM '1'+ AND NOT (record->>'version'='3' AND record->>'target'='pages' AND jsonb_typeof(record->'files')='array'))OR (target='skill_bundle' AND (record->>'version' IS DISTINCT FROM '2' OR record->>'target' IS DISTINCT FROM 'skill_bundle'OR jsonb_typeof(record->'files') IS DISTINCT FROM 'array'))) THENRAISE EXCEPTION 'unsupported_mutation_protocol: recovery target mismatch' USING ERRCODE='42501';END IF;RETURN NEW;- END $$;+ END $;DROP TRIGGER IF EXISTS gbrain_request_protocol ON persistence_requests;CREATE TRIGGER gbrain_request_protocol BEFORE INSERT OR UPDATE OR DELETE ON persistence_requestsFOR EACH ROW EXECUTE FUNCTION gbrain_guard_request_protocol();diff --git a/test/doctor-fence-integrity.test.ts b/test/doctor-fence-integrity.test.tsindex cdafd31e2e..caf222047c 100644--- a/test/doctor-fence-integrity.test.ts+++ b/test/doctor-fence-integrity.test.ts@@ -233,6 +233,32 @@ describe('fence_integrity doctor check', () => {expect((await result()).status).toBe('ok');});+ test('a legacy row that copies a fenced claim of its page (duplicate_claim) points at the duplicate-facts preview, never the claim (GBRA-190)', async () => {+ const s = await source({ 'people/alice-example.md': md('Alice Example', CLEAN) });+ const page = await stored(s.id, 'people/alice-example', CLEAN);+ await engine.executeRaw('UPDATE pages SET source_path = $1 WHERE id = $2', ['people/alice-example.md', page.id]);+ const insert = (rowNum: number | null) => engine.executeRaw<{ id: number }>(+ `INSERT INTO facts (source_id, entity_slug, fact, kind, visibility, notability, valid_from, source, confidence, row_num, source_markdown_slug)+ VALUES ($1, 'people/alice-example', 'Clean synthetic fact', 'fact', 'private', 'medium', '2026-01-01', 'call', 1, $2, $3) RETURNING id`,+ [s.id, rowNum, rowNum === null ? null : 'people/alice-example']);+ await insert(1);+ const [legacy] = await insert(null);+ const check = await result();+ expect(check.status).toBe('warn');+ expect((check.details as any).unrenderable_legacy_facts).toEqual({ total: 1, complete: true, pages: [{ source_id: s.id, slug: 'people/alice-example',+ rows: [{ fact_id: Number(legacy.id), reason: 'duplicate_claim', class: 'duplicate_claim' }] }] });+ expect(check.message).toContain(`1 of them copy a claim their page's facts table already carries (duplicate_claim): gbrain repair duplicate-facts --source ${s.id} previews`);+ expect(check.message).not.toContain('For the other rows there is no safe automatic fix');+ expect(check.message).not.toContain('forget_fact');+ const rendered = renderAction(check.fix!, cliRenderContext());+ expect(rendered.next).toBe('run');+ expect(rendered.command).toBe(`gbrain repair duplicate-facts --source ${s.id} --json`);+ expect(rendered.docs).toContain('repair.md#duplicate-facts');+ expect(JSON.stringify(check)).not.toContain('Clean synthetic fact');+ await engine.executeRaw('DELETE FROM facts WHERE source_id = $1', [s.id]);+ expect((await result()).status).toBe('ok');+ });+test('a census the scan did not finish is partial and never ok, even with nothing found so far', async () => {const s = await source({ 'notes/clean.md': md('Clean', CLEAN) });await stored(s.id, 'notes/clean', CLEAN);diff --git a/test/extract-rollup-halt-reasons-5495.test.ts b/test/extract-rollup-halt-reasons-5495.test.tsindex 920010e172..dd2239822a 100644--- a/test/extract-rollup-halt-reasons-5495.test.ts+++ b/test/extract-rollup-halt-reasons-5495.test.ts@@ -12,8 +12,9 @@* with old and new writers on one day; doctor names the top reason; a brain* whose schema is behind keeps extracting and loses rollup rows with one* stderr line naming the migration fix, never a throw; extract_atoms records- * a credentials abort as provider_auth and extract_facts' fence guard as- * integrity_guard.+ * a credentials abort as provider_auth, and an extract_facts run whose fence+ * guard holds a page books a completed round, never a halt (GBRA-190 G4: the+ * guard holds that page only and every other page reconciles).* Fails when: the migration backfills, a cap becomes a halt reason, reasons* are JSON-stringified into the jsonb, unknown is stored instead of* computed, or the doctor ignores the column.@@ -174,7 +175,7 @@ test('a brain whose schema is behind v239 keeps extracting: the rollup write ret}}, 120_000);-test('extract_atoms records a credentials abort as provider_auth; extract_facts records its fence guard as integrity_guard', async () => {+test('extract_atoms records a credentials abort as provider_auth; an extract_facts run with a guard-held page is a completed round', async () => {const engine = engines.find(e => e.kind === 'pglite');if (!engine) return;for (const slug of ['note/auth-1', 'note/auth-2']) await engine.putPage(slug, { title: slug, type: 'note', compiled_truth: 'seed body prose' } as never, { sourceId: 'default' });@@ -200,7 +201,8 @@ test('extract_atoms records a credentials abort as provider_auth; extract_factsexpect((await runExtractFacts(stub, { slugs: [], sourceId: 'default' })).guardTriggered).toBe(true);const rollups = calls.filter(c => c.sql.includes('INSERT INTO extract_rollup_7d'));expect(rollups).toHaveLength(1);- expect(rollups[0]!.params[4]).toBe(1);- expect(rollups[0]!.params[10]).toBe('integrity_guard');+ expect(rollups[0]!.params[4]).toBe(0);+ expect(rollups[0]!.params[7]).toBe(1);+ expect(rollups[0]!.params[10]).toBeNull();expect(rollups[0]!.sql).not.toContain('JSON.stringify');}, 120_000);