Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
Fix delegated sync to a recovered PGLite serve and owner-bound remember on segmented pages
garrytan3d874b1113e1
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 927b2836bc..f3768f34d9 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -10,6 +10,19 @@ credits are retained; no result has been reassigned to another provider. Originaidentifiers and attribution are available in the pre-removal Git revision`6040075c6cb95be5881cc2e1b76ef7d71f4e5d29` (retained on 2026-09-23).+## [Unreleased]++### A recovered `gbrain serve` syncs again, and the brain owner's `remember` works on a large page++**Syncs no longer fail after a `gbrain serve` recovers from status-only mode (#9224).** When `gbrain serve` starts while another gbrain process holds a PGLite brain (a second agent session, or a cron job), it answers with only `gbrain_status` until the brain opens, then takes over as the brain's owner. From then on, every `gbrain sync` handed to that owner that had pages to write failed with `storage_error` "The persistence owner could not complete this request", and the owner's own `sync_brain` failed with "Unknown engine kind for db-lock: pglite". This lasted until the agent session restarted. An ordinary install, where serve opens the brain when it starts, was not affected.+- The cause was in the stand-in engine that status-only serve runs on. On recovery it passed the live engine's methods through, but not its getters and fields, so PGLite's `db` handle was missing and the sync lock could not be taken. It also wrapped every method as `async`, so a synchronous method such as `registerBeforeDisconnect` returned a promise instead of its value, which broke a sync that got past the lock. After recovery the stand-in now exposes exactly the live engine's properties, read through to it, and a synchronous method returns its own value. A Postgres `gbrain serve` that started while its database was unreachable runs on the same stand-in and gets the same fix; its sync lock was never affected.+- An unexpected fault inside the owner now reaches the caller as `internal_error` (detail `owner_internal`) with an incident ID. The error says the request was not at fault and how to recover: restart that owner and rerun the command; with no owner running, the CLI opens the brain itself. A write also names its request ID to inspect first. The fix, `gbrain sources writer status --json`, is read-only and names the owner process. The cause itself goes only to the owner's own stderr, under the same incident ID and with connection strings redacted, and never crosses the local socket. Before, the caller got `storage_error` and a `gbrain doctor` fix that could not see the fault, and the owner logged nothing.++**The brain owner's `remember` works on an entity page stored in segments (#9213).** With a token bound to the brain owner, `remember` onto a large entity page (one stored in segments) was refused with `page_body_segmented` before it was admitted, while the same call from an unbound token committed. The owner's visibility checks copied the whole page object, and reading a segmented page's body as one string throws on purpose. Those checks now read only the page's labels, readers and identity. The same mistake is fixed in the member scope-page check, at admission and at preparation, and in the shared-origin retention purge of a page over 24 MiB. The guard that refuses whole-body reads of a segmented page is exactly as strict as before.+- A write refused with `page_body_segmented` no longer suggests `get_page body: "auto"`, which reads the page and doesn't help a write. A `remember` gets the fix that works: save the claim without an entity, and it is filed under `memory/unattributed`. Any other write over MCP gets a fix with no step to run that names the edits that do work on such a page: `edit_page`, `append_page`, `add_tag` and `remove_tag`. Reads keep the `get_page` fix.++Reported by @thiagodalvarenga (#9224) and @andreineacsu (#9213). First fixed by @Masashi-Ono0611 (#9231, #9215).+## [0.60.699.0] - 2026-11-12### The Ubicloud gate VMs run a current gitdiff --git a/src/core/degraded-engine.ts b/src/core/degraded-engine.tsindex 21d4636174..fe973107b6 100644--- a/src/core/degraded-engine.ts+++ b/src/core/degraded-engine.ts@@ -96,9 +96,9 @@ function enginePrototypeMethodNames(): string[] {/** Prototype GETTERS (e.g. `get sql()`), delegated too — serve holds this* wrapper forever, so a post-recovery property read must reach the live- * engine, not silently return undefined. Instance properties set in the- * constructor are NOT enumerable from the prototype and stay out of the- * BrainEngine contract (methods + kind + prototype getters only). */+ * engine, not silently return undefined. Instance fields are not on the+ * prototype: while dead they are absent, and recovery (`alignWith`)+ * delegates them along with the live engine's own methods and getters. */function enginePrototypeGetterNames(): string[] {const names = new Set<string>();let proto: object | null = PostgresEngine.prototype;@@ -138,7 +138,7 @@ export function createDegradedEngine(opts: DegradedEngineOptions): BrainEngine {.reconnect().then((engine) => {live = engine;- alignMethodsWith(engine);+ alignWith(engine);for (const cb of recoveryCallbacks.splice(0)) {try { cb(); } catch { /* recovery callbacks are best-effort */ }}@@ -169,29 +169,44 @@ export function createDegradedEngine(opts: DegradedEngineOptions): BrainEngine {}const target: Record<string | symbol, unknown> = {};+ /** Names the stand-in mirrored from PostgresEngine; recovery drops the ones the live engine lacks. */+ const mirrored = new Set<string>();/**- * The method set was enumerated from PostgresEngine; a live engine of- * another kind (status-only serve over PGLite) gets exactly its own- * methods, so `typeof engine.x === 'function'` capability probes stay true.+ * #9224: the surface was enumerated from PostgresEngine; a live engine of+ * another kind (status-only serve over PGLite) gets exactly its own surface:+ * every property reachable on it (prototype methods and getters, instance+ * fields, symbol keys), delegated to it, and none it lacks. Before, only+ * methods were aligned, so PGLite's `db` getter stayed missing and+ * tryAcquireDbLock refused every delegated sync that had pages to write.*/- const alignMethodsWith = (engine: BrainEngine) => {- const own = engine as unknown as Record<string, unknown>;- for (const name of Object.keys(target)) {- if (typeof target[name] === 'function' && name !== 'disconnect' && typeof own[name] !== 'function') delete target[name];+ const alignWith = (engine: BrainEngine) => {+ const own = engine as unknown as Record<string | symbol, unknown>;+ for (const name of mirrored) {+ if (name !== 'disconnect' && !(name in engine)) delete target[name];}- let proto: object | null = Object.getPrototypeOf(engine);- while (proto && proto !== Object.prototype) {- for (const name of Object.getOwnPropertyNames(proto)) {- if (name === 'constructor' || name in target) continue;- const desc = Object.getOwnPropertyDescriptor(proto, name);- if (desc && typeof desc.value === 'function') target[name] = (...args: unknown[]) => (own[name] as (...a: unknown[]) => unknown).apply(engine, args);+ for (let holder: object | null = engine; holder && holder !== Object.prototype; holder = Object.getPrototypeOf(holder)) {+ for (const key of Reflect.ownKeys(holder)) {+ if (key === 'constructor' || key in target) continue;+ const desc = Object.getOwnPropertyDescriptor(holder, key)!;+ if (holder !== engine && typeof desc.value === 'function') {+ target[key] = (...args: unknown[]) => (own[key] as (...a: unknown[]) => unknown).apply(engine, args);+ continue;+ }+ Object.defineProperty(target, key, {+ get: () => own[key],+ set: (value: unknown) => { own[key] = value; },+ enumerable: desc.enumerable ?? false,+ configurable: true,+ });}- proto = Object.getPrototypeOf(proto);}};for (const name of enginePrototypeMethodNames()) {if (name === 'disconnect') continue; // special-cased below- target[name] = async (...args: unknown[]) => {+ mirrored.add(name);+ // Not async: once live, a synchronous method (registerBeforeDisconnect returns its unregister function) must+ // return its own value, not a promise of it (#9224). While dead every call is a rejected promise, as before.+ target[name] = (...args: unknown[]) => {if (live) {return (live as unknown as Record<string, (...a: unknown[]) => unknown>)[name](...args);}@@ -203,6 +218,7 @@ export function createDegradedEngine(opts: DegradedEngineOptions): BrainEngine {if (live) await live.disconnect();};for (const name of enginePrototypeGetterNames()) {+ mirrored.add(name);Object.defineProperty(target, name, {// Sync surface: a property read never triggers a reconnect — while// dead it throws the stored (honest) error rather than silently@@ -212,6 +228,7 @@ export function createDegradedEngine(opts: DegradedEngineOptions): BrainEngine {throw lastError;},enumerable: true,+ configurable: true,});}Object.defineProperty(target, 'kind', {diff --git a/src/core/page-body/page-shape.ts b/src/core/page-body/page-shape.tsindex d892a457d6..5bc0b12a6d 100644--- a/src/core/page-body/page-shape.ts+++ b/src/core/page-body/page-shape.ts@@ -12,7 +12,7 @@* sites): the runtime getters and `scripts/check-page-body-readers.ts` are the* enforcement, not the type checker.*/-import { opError } from '../ops/contract.ts';+import { OperationError, opError } from '../ops/contract.ts';import { PAGE_MAX_BYTES } from '../page-size-policy.ts';import type { Page } from '../types.ts';import type { BodyStorage } from './types.ts';@@ -79,6 +79,26 @@ export function pageBodyOverCeilingError(page: { slug?: string; source_id?: striconsent: [], actor: 'agent', requires_exclusive: false, why: "Returns the page's outline and its first window, with next_cursor to read on." } });}+/** True when `fix` is the read step pageBodySegmentedError and pageBodyOverCeilingError give: get_page reading the page in pieces. */+export function readsPageInPieces(fix: { mcp?: { tool?: string } } | undefined): boolean {+ return fix?.mcp?.tool === 'get_page';+}++/**+ * A write refused `page_body_segmented` whose next step reads the page in pieces (its own or, with no fix, the code's+ * registry default), which changes nothing for a writer: the same refusal with no step to run (next: report), and a+ * writer's suggestion unless it carries one of its own. A refusal with a write fix of its own (remember's unattributed+ * save) is left as it is.+ */+export function asSegmentedWriteRefusal(error: unknown): void {+ if (!(error instanceof OperationError) || error.canonicalCode !== 'page_body_segmented') return;+ if (error.fix && !readsPageInPieces(error.fix)) return;+ if (error.fix || !error.suggestion) error.suggestion = 'This write needs the page\'s whole body as one string, which it cannot get from a page stored in segments, so retrying refuses the same way and nothing was changed. '+ + 'On such a page edit_page and append_page change its text, and add_tag and remove_tag its tags.';+ error.fix = { consent: [], actor: 'agent', requires_exclusive: false,+ why: 'No retry of this write can change this page; tell the user which change could not be made, or make it with edit_page, append_page, add_tag or remove_tag.' };+}+/** Throws `page_body_segmented` for a segmented page; `site` names the caller. Inline pages pass. */export function assertInlineBody(page: BodyShape & { slug?: string; source_id?: string }, site: string): void {if (isSegmentedPage(page)) throw pageBodySegmentedError(page, site);diff --git a/src/core/persistence/ipc.ts b/src/core/persistence/ipc.tsindex d0dbeef8cf..f9473b53a4 100644--- a/src/core/persistence/ipc.ts+++ b/src/core/persistence/ipc.ts@@ -1,9 +1,11 @@/** Dedicated, bounded local persistence transport. Hook IPC keeps its own small frame budget. */import net, { type Server, type Socket } from 'node:net';+import { randomUUID } from 'node:crypto';import { chmodSync, lstatSync, unlinkSync } from 'node:fs';import { isAbsolute } from 'node:path';import { OperationError, opError } from '../ops/contract.ts';import { readFix } from '../ops/op-fix.ts';+import { redactConnectionInfo } from '../audit/redact-connection-info.ts';import type { Action } from '../agent-output.ts';import type { ProjectionBacklog } from '../page-state/projections.ts';import { resolveSocketPathForConfig, socketHasLiveListener } from '../context/resolve-ipc.ts';@@ -167,10 +169,23 @@ const clientBug = (message: string): OperationError => opError('invalid_params','This gbrain build produced a malformed local persistence request, so nothing was sent to the owner. It is a client fault, not a caller mistake: run gbrain doctor --json on this host and report it to the user with the command that failed.',{ fix: readFix('Checks this installation and its persistence owner without changing anything.', { argv: ['gbrain', 'doctor', '--json'] }) });-function publicError(error: unknown): Record<string, unknown> {+/**+ * #9224: an owner fault that is not an OperationError crosses the socket as `internal_error` with an incident ID,+ * how to recover and a read-only fix naming the owner; the cause itself goes only to the owner's own stderr.+ */+function publicError(error: unknown, requestId?: string): Record<string, unknown> {if (error instanceof OperationError) return error.toJSON();- // Never reflect driver errors, SQL, credentials, or private payloads.- return { error: 'storage_error', message: 'The persistence owner could not complete this request.' };+ const incident = randomUUID();+ // Never reflect driver errors, SQL, credentials, or private payloads: the cause stays on this host's owner log.+ try {+ const cause = error instanceof Error ? error.stack ?? `${error.name}: ${error.message}` : String(error);+ process.stderr.write(`[gbrain persistence] request failed in this owner (incident ${incident}): ${redactConnectionInfo(cause)}\n`);+ } catch { /* stderr gone */ }+ return opError('internal_error', `The persistence owner failed while running this request (incident ${incident}); the request itself was not at fault.`,+ `The process that holds this brain (the command in fix names it) hit an internal fault and wrote the cause to its own stderr under incident ${incident}; nothing about it crosses the local socket. ${requestId+ ? `The write may have partly run: inspect request ${requestId} with gbrain write-request ${requestId} before resubmitting it. `+ : ''}Restart that owner (for a gbrain serve an agent app launched, restart its MCP server or the agent session), then run the same command again; with no owner running, the CLI opens the brain itself. If it fails again after a restart, tell the user and give them the incident ID.`,+ { detail: 'owner_internal', fix: writerStatusFix('Names the process that owns this brain (its PID, lane and gbrain version), read-only, so it can be restarted.') }).toJSON();}function responseFrame(value: unknown): string {@@ -279,7 +294,7 @@ export async function startPersistenceIpcServer(error.requestId = mutation.requestId;if (mutation.receipt) error.writeRequest = publicWriteReceipt(mutation.receipt);}- if (!socket.destroyed) socket.end(responseFrame({ version: 1, ok: false, error: publicError(error) }));+ if (!socket.destroyed) socket.end(responseFrame({ version: 1, ok: false, error: publicError(error, mutation?.requestId) }));} finally {if (admitted) active--;}@@ -351,7 +366,7 @@ export function restoreRecoveryContract(error: OperationError, body: Record<striif (typeof body.code === 'string' && body.code !== error.code) error.canonical = body.code as OperationError['canonical'];if (typeof body.detail === 'string') error.detail = body.detail;if (typeof body.retryable === 'boolean') error.retryable = body.retryable;- if (record(body.fix) && body.code === 'worktree_refreshing') { const { next: _next, command: _command, ...fix } = body.fix; error.fix = fix as unknown as Action; }+ if (record(body.fix) && (body.code === 'worktree_refreshing' || body.code === 'internal_error' && body.detail === 'owner_internal')) { const { next: _next, command: _command, ...fix } = body.fix; error.fix = fix as unknown as Action; }}function remoteOperationError(value: unknown): OperationError {diff --git a/src/core/persistence/memory-mutations.ts b/src/core/persistence/memory-mutations.tsindex 3f279ed5d0..824a42687f 100644--- a/src/core/persistence/memory-mutations.ts+++ b/src/core/persistence/memory-mutations.ts@@ -11,7 +11,7 @@ import { isNullLikeEntity } from '../facts/write-single.ts';import { isFactWithdrawn, planFactWithdrawal } from '../facts/withdrawal.ts';import { inferFactSubject, isEntityInferenceEnabled, type InferredVia } from '../facts/subject-infer.ts';import { parseFactsFence } from '../facts-fence.ts';-import { isSegmentedPage } from '../page-body/page-shape.ts';+import { isSegmentedPage, withoutBody } from '../page-body/page-shape.ts';import { segmentedRememberRefusal, type RememberCarry } from './verb-errors.ts';import { materializedPage, segmentedOverCeiling } from './segmented-apply.ts';import { excludesPrivateWrites, storedOwnerSpeaksForItself } from './page-visibility.ts';@@ -99,7 +99,7 @@ async function planRememberTarget(ctx: OperationContext, sourceId: string, sourcthrow opError('page_not_found', 'The target entity is not writable by this caller.',`Entity page ${slug} in source ${sourceId} is deleted or not visible to this caller, so nothing was saved. Remember the fact against a visible entity, or without an entity (it is then filed under memory/unattributed).`);}- if (memberPage === SCOPE_PAGE_SLUG) { if (snapshot && !await scopePageIsShared(ctx.engine, { ...snapshot.page, source_id: sourceId, slug })) throw scopePageNotShared(sourceId); }+ if (memberPage === SCOPE_PAGE_SLUG) { if (snapshot && !await scopePageIsShared(ctx.engine, { ...withoutBody(snapshot.page), source_id: sourceId, slug })) throw scopePageNotShared(sourceId); }else if (memberPage && snapshot && !memberPageIsOwn(memberPage, snapshot.page.frontmatter)) throw memberPageNotOwned(memberPage);if (inferred && !snapshot) throw new InferredTargetRejected('NO_ENTITY');// Wave B: a segmented entity page over the single-string ceiling cannot take a fence row; named or inferred, the save refuses@@ -187,7 +187,7 @@ async function ownerDefaultKeptPrivate(ctx: OperationContext, sourceId: string,const id = Number(replaces);if (replaces !== undefined && replaces !== null && Number.isSafeInteger(id) && (await ownMemberFactIds(ctx.engine, sourceId, [id])).has(id)) return true;const snapshot = slug ? await ctx.engine.readPageSnapshot(slug, { sourceId }) : null;- return await rememberVisibility(ctx, { p: {}, visibilityDefaulted: true }, snapshot && { ...snapshot.page, source_id: sourceId, slug: slug! }) === 'private';+ return await rememberVisibility(ctx, { p: {}, visibilityDefaulted: true }, snapshot && { ...withoutBody(snapshot.page), source_id: sourceId, slug: slug! }) === 'private';}async function rememberCarry(ctx: OperationContext, call: RememberCall, page: PageLabel): Promise<RememberCarry> {@@ -264,7 +264,7 @@ export async function submitRememberMutation(ctx: OperationContext, params: Reco({ slug, authority, snapshot, fence, binding, writeThrough } = await planRememberTarget(ctx, sourceId, source, entitySlug, null, call, memberPage));}// D1: the owner's explicit visibility "world" onto a page whose facts are kept private is refused like share: true.- const ownerWorldRestricted = ownerShares && !call.visibilityDefaulted && snapshot !== null && isDerivationPrivate(await withFolderRestricted(ctx.engine, { ...snapshot.page, source_id: sourceId, slug }));+ const ownerWorldRestricted = ownerShares && !call.visibilityDefaulted && snapshot !== null && isDerivationPrivate(await withFolderRestricted(ctx.engine, { ...withoutBody(snapshot.page), source_id: sourceId, slug }));if (p.share === true && visibility !== 'world' || ownerWorldRestricted) {throw Object.assign(verbError('invalid_params', `remember: ${p.share === true ? 'share: true' : 'visibility "world"'} cannot share a fact on ${slug}, whose facts are kept private (restricted page or the brain's private fact default); nothing was saved.`,p.share === true ? 'Share it on a page every reader of this source can read, or drop share to keep the fact on your own page.'diff --git a/src/core/persistence/memory-prepare.ts b/src/core/persistence/memory-prepare.tsindex 391ac75ff5..8cf2bc0624 100644--- a/src/core/persistence/memory-prepare.ts+++ b/src/core/persistence/memory-prepare.ts@@ -27,6 +27,7 @@ import { noteBelief } from '../belief/ledger.ts';import { attestedShareRefused, MEMBER_PAGE_PREFIX, memberPageFrontmatter, memberPageIsOwn, memberPageNotOwned, onOwnedMemoryPageSql, scopePageFrontmatter, scopePageIsShared, scopePageNotShared } from '../access/member-facts.ts';import { claimColumns, storedClaim } from '../facts/typed-claim.ts';import { parseStoredActor } from '../access/actor-model.ts';+import { withoutBody } from '../page-body/page-shape.ts';function conflict(row: WriteRequest): never {throw opError('revision_conflict', 'The memory changed during semantic preparation.',@@ -85,7 +86,7 @@ export async function prepareMemoryMutation(engine: BrainEngine, row: WriteRequeconst snapshot = await engine.readPageSnapshot(row.slug, { sourceId: row.source_id, includeDeleted: true });if ((snapshot?.page.id ?? null) !== row.page_id && !rememberAcceptsPageCreatedSince(row, snapshot)) throw pageIdentityError(snapshot != null || row.page_id === null, 'The accepted entity was deleted or recreated.');if (p.member_page === true && snapshot && !memberPageIsOwn(row.slug, snapshot.page.frontmatter)) throw memberPageNotOwned(row.slug);- if (p.scope_page === true && snapshot && !await scopePageIsShared(engine, { ...snapshot.page, source_id: row.source_id, slug: row.slug })) throw scopePageNotShared(row.source_id);+ if (p.scope_page === true && snapshot && !await scopePageIsShared(engine, { ...withoutBody(snapshot.page), source_id: row.source_id, slug: row.slug })) throw scopePageNotShared(row.source_id);// A defaulted visibility never lands broader than the target page as it stands at publication.if (p.visibility_defaulted === true && snapshot) input.visibility = tightenToPage(input.visibility, await withFolderRestricted(engine, snapshot.page));// GST-2243: a shared fact whose page turned restricted after admission is refused, never saved private under a world receipt.diff --git a/src/core/persistence/page-prepare.ts b/src/core/persistence/page-prepare.tsindex 2a6883775f..3dfc6a9377 100644--- a/src/core/persistence/page-prepare.ts+++ b/src/core/persistence/page-prepare.ts@@ -752,7 +752,7 @@ async function prepareDeletePageMutation(engine: BrainEngine, row: WriteRequest,apply: async tx => {if (purge && excludedPath !== null) await assertStillSyncExcluded(tx, row, excludedPath);// #7311: the tombstone forgets the survivor's file, as an origin_twin page has, so its purge writes no deletion marker for it.- if (preparedPurge && sharedRetention) return purgePageInTransaction(tx, row, { ...snapshot, page: { ...snapshot.page, source_path: null, source_uri: null } }, preparedPurge);+ if (preparedPurge && sharedRetention) return purgePageInTransaction(tx, row, { ...snapshot, page: { ...(bodyUnread(snapshot.page) ? withoutBody(snapshot.page) : snapshot.page), source_path: null, source_uri: null } as Page }, preparedPurge);if (preparedPurge) return purgePageInTransaction(tx, row, snapshot, preparedPurge);// GST-2518: a soft delete authors no content, so the tombstone keeps its tier (and a write over it the page's label guard).if (!noop) { await tx.createVersion(row.slug, source); await withTrustKeep(tx, ['pages'], () => tx.softDeletePage(row.slug, source)); }diff --git a/src/core/persistence/verb-errors.ts b/src/core/persistence/verb-errors.tsindex 58d1134643..9b524019f4 100644--- a/src/core/persistence/verb-errors.ts+++ b/src/core/persistence/verb-errors.ts@@ -9,6 +9,7 @@ import { FACT_WITHDRAWN_SUGGESTION } from '../facts/withdrawal.ts';import { CHECKPOINT_MOVED_MESSAGE } from './sync-slug-mode.ts';import { PAGE_CHANGED_AFTER_READ_MESSAGE, PAGE_CHANGED_DURING_PREPARATION_MESSAGE } from '../page-state/types.ts';import { readFix } from '../ops/op-fix.ts';+import { readsPageInPieces } from '../page-body/page-shape.ts';import { codeEntry, ERROR_CATALOGUE } from '../error-catalogue.ts';import { SOURCE_CHECKOUT_MISSING, type CheckoutRefusalOrigin } from './publication-failure.ts';import { ownershipRecordNotPrivateError, physicalRootDirectoryChangedError } from './physical-root-record.ts';@@ -196,7 +197,7 @@ export function writeFailureDiagnostic(code: string, message?: string | null): {if (code === 'source_writeback_required' && message?.startsWith('Canonical preparation would normalize a facts or takes fence (')) return { reason: code, message,suggestion: 'A company-brain source never rewrites repository files: fix the named fence in the repository, commit it, and resume the sync.' };// Wave B: a page whose body is stored in segments refuses a whole-body write; a deliberate per-page verdict, never a server fault.- if (code === 'page_body_segmented') return { reason: code, message: message ?? SEGMENTED_WRITE_MESSAGE, suggestion: SEGMENTED_WRITE_SUGGESTION };+ if (code === 'page_body_segmented') return { reason: code, message: message ?? SEGMENTED_WRITE_MESSAGE, suggestion: message?.includes('24 MiB') ? SEGMENTED_WRITE_SUGGESTION : SEGMENTED_PATH_SUGGESTION };// #8522: a page whose segment rows readable here do not cover its body refuses every whole-body write the same way; the message names the page.if (code === 'page_body_rows_unreadable') return { reason: code, message: message ?? codeEntry(code)!.summary, suggestion: codeEntry(code)!.suggestion };// #5575: a purged claim or page content is refused for good; the owner alone can clear its tombstone.@@ -216,6 +217,9 @@ const SEGMENTED_WRITE_MESSAGE = 'The target page stores its body in segments, anconst SEGMENTED_WRITE_SUGGESTION = 'The target page stores its body in segments over the 24 MiB limit up to which this write reads the body whole, so retrying refuses the same way. '+ 'For remember: save the claim without an entity (omit entity, infer_entity: false); it is filed under memory/unattributed, and remembering it with entity once that page accepts fact rows replaces that copy. '+ "Read the page with get_page body: 'auto' or a window.";+/** A segmented target refused by a write path that reads the body whole (pageBodySegmentedError), below the ceiling too. */+const SEGMENTED_PATH_SUGGESTION = 'The target page stores its body in segments, and this write reads the body whole on a path that cannot read a page stored in segments yet, so retrying refuses the same way. '+ + 'For remember: save the claim without an entity (omit entity, infer_entity: false); it is filed under memory/unattributed, and remembering it with entity once that page accepts fact rows replaces that copy.';/** What the unattributed retry must keep from the refused call, so the retry is never broader than the original. */export interface RememberCarry { visibility: 'world' | 'private'; kind?: string; ttl?: string; valid_from?: string }@@ -281,8 +285,9 @@ export async function runMemoryWrite<T>(run: () => Promise<T>): Promise<T> {}// Wave B: a segmented target is a caller-class refusal; the frozen wire code is invalid_params and the canonical code says why.if (error.canonicalCode === 'page_body_segmented') {- const segmented = verbError('invalid_params', error.message, error.suggestion ?? SEGMENTED_WRITE_SUGGESTION);- Object.assign(segmented, { canonical: 'page_body_segmented', writeError: 'page_body_segmented', fix: error.fix ?? segmentedRememberFix() });+ const readStep = readsPageInPieces(error.fix);+ const segmented = verbError('invalid_params', error.message, !readStep && error.suggestion ? error.suggestion : writeFailureDiagnostic('page_body_segmented', error.message).suggestion);+ Object.assign(segmented, { canonical: 'page_body_segmented', writeError: 'page_body_segmented', fix: !readStep && error.fix ? error.fix : segmentedRememberFix() });throw segmented;}// GST-1387: a refresh fence is a retryable wait, not an outage: the frozen code stays unavailable, and the canonical code,diff --git a/src/mcp/dispatch.ts b/src/mcp/dispatch.tsindex 4b8fea3137..74a6099667 100644--- a/src/mcp/dispatch.ts+++ b/src/mcp/dispatch.ts@@ -11,6 +11,7 @@ import { affectsRecall } from '../core/types.ts';import type { BrainEngine } from '../core/engine.ts';import { operations, OperationError, enforceBoundClientOpAllowList, opError } from '../core/operations.ts';import type { OperationContext, AuthInfo } from '../core/operations.ts';+import { asSegmentedWriteRefusal } from '../core/page-body/page-shape.ts';import type { Operation, OperationMeta } from '../core/ops/contract.ts';import { loadConfig } from '../core/config.ts';import { withRequestConfigSnapshot, withoutRequestConfigSnapshot } from '../core/config-snapshot.ts';@@ -1403,6 +1404,7 @@ async function dispatchResolvedCall(notices.push(...await sessionSafetyNotices(engine, opts, ctx.config));notices.push(...await grantBlockedNotices(engine, opts, refusedByGrant(e)));attachRetryCall(op, name, safeParams, e);+ if (op.mutating) asSegmentedWriteRefusal(e);return deferredWriteResult(e, notices, opts) ?? errorResult(e, opts, { op: name, mutating: op.mutating === true, idempotent: op.idempotent === true, notices: admitNotices(notices, opts) });}}diff --git a/test/degraded-engine-recovered-surface-9224.test.ts b/test/degraded-engine-recovered-surface-9224.test.tsnew file mode 100644index 0000000000..2838d210da--- /dev/null+++ b/test/degraded-engine-recovered-surface-9224.test.ts@@ -0,0 +1,107 @@+/**+ * #9224: a status-only `gbrain serve` over PGLite runs on the degraded stand-in, and once the brain opens it+ * becomes the persistence owner. Every delegated sync that had pages to write then failed with+ * "Unknown engine kind for db-lock: pglite": recovery re-aligned the stand-in's methods with the live engine+ * but not its getters or fields, so `engine.db` stayed missing and tryAcquireDbLock fell through.+ *+ * 1. Protects: after recovery the stand-in exposes exactly the live engine's surface (every key reachable on it,+ * read through to it), enumerated from the real engine so a getter or field added later is covered, and the+ * sync writer lock is taken on it as on the engine itself.+ * 2. Fails when: recovery leaves any property of the live engine missing, stale or different, or keeps one the+ * live engine does not have.+ * 3. Real seams: a real PGLite engine (and a real Postgres engine when DATABASE_URL is set), the real stand-in+ * and the real db lock.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { createDegradedEngine, DegradedRecoveredRetryError } from '../src/core/degraded-engine.ts';+import { DEGRADED_LAST_ERROR, DEGRADED_ON_RECOVER, DEGRADED_STATE } from '../src/core/degraded-marker.ts';+import { tryAcquireDbLock } from '../src/core/db-lock.ts';+import type { BrainEngine } from '../src/core/engine.ts';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { testBackends } from './helpers/test-backends.ts';+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';++const STAND_IN_KEYS = new Set<PropertyKey>([DEGRADED_STATE, DEGRADED_ON_RECOVER, DEGRADED_LAST_ERROR]);+const LOCK_ID = 'gbrain-sync';++function reachableKeys(engine: object): PropertyKey[] {+ const keys = new Set<PropertyKey>();+ for (let holder: object | null = engine; holder && holder !== Object.prototype; holder = Object.getPrototypeOf(holder)) {+ for (const key of Reflect.ownKeys(holder)) if (key !== 'constructor') keys.add(key);+ }+ return [...keys];+}++function read(engine: object, key: PropertyKey): { value?: unknown; error?: string } {+ try { return { value: (engine as Record<PropertyKey, unknown>)[key] }; } catch (e) { return { error: (e as Error).message }; }+}++for (const kind of testBackends()) {+ describe(`degraded stand-in recovered onto a live ${kind} engine (#9224)`, () => {+ let live: BrainEngine;+ let close: () => Promise<void>;+ let engine: BrainEngine;++ beforeAll(async () => {+ if (kind === 'postgres') ({ engine: live, close } = await isolatedPersistencePostgres(process.env.DATABASE_URL!));+ else { live = new PGLiteEngine(); await live.connect({ engine: 'pglite' } as never); await live.initSchema(); close = () => live.disconnect(); }+ engine = createDegradedEngine({+ initialError: new Error('This brain is open in another gbrain serve.'),+ reconnect: async () => live,+ minIntervalMs: 0,+ kind,+ });+ await expect(engine.getStats()).rejects.toBeInstanceOf(DegradedRecoveredRetryError);+ }, 120_000);++ afterAll(async () => { await close?.(); });++ test('every property reachable on the live engine reads the same through the recovered stand-in', () => {+ const keys = reachableKeys(live);+ expect(keys.length).toBeGreaterThan(50);+ const differ: string[] = [];+ for (const key of keys) {+ if (!(key in engine)) { differ.push(`${String(key)}: missing`); continue; }+ const want = read(live, key), got = read(engine, key);+ if (want.error !== undefined || got.error !== undefined) {+ if (want.error !== got.error) differ.push(`${String(key)}: threw ${got.error ?? 'nothing'}, live threw ${want.error ?? 'nothing'}`);+ continue;+ }+ if (typeof got.value !== typeof want.value) { differ.push(`${String(key)}: ${typeof got.value}, live ${typeof want.value}`); continue; }+ if (typeof want.value !== 'function' && Object.is(want.value, read(live, key).value) && !Object.is(got.value, want.value)) differ.push(`${String(key)}: a different value`);+ }+ expect(differ).toEqual([]);+ });++ test('a synchronous engine method stays synchronous through the recovered stand-in', () => {+ const asyncWrapped = reachableKeys(live).filter(key => {+ const method = read(live, key).value;+ if (typeof method !== 'function' || method.constructor.name === 'AsyncFunction') return false;+ return (read(engine, key).value as { constructor: { name: string } }).constructor.name === 'AsyncFunction';+ }).map(String);+ expect(asyncWrapped).toEqual([]);+ const unregister = engine.registerBeforeDisconnect(async () => {});+ expect(typeof unregister).toBe('function');+ unregister();+ });++ test('the stand-in keeps no property the live engine does not have', () => {+ const extra = Reflect.ownKeys(engine).filter(key => !STAND_IN_KEYS.has(key) && !(key in live)).map(String);+ expect(extra).toEqual([]);+ expect(engine.kind).toBe(kind);+ });++ test('the sync writer lock is taken, refreshed and released on the recovered engine', async () => {+ const lock = await tryAcquireDbLock(engine, LOCK_ID);+ expect(lock).not.toBeNull();+ try {+ const held = await live.executeRaw<{ holder_pid: number }>('SELECT holder_pid FROM gbrain_cycle_locks WHERE id = $1', [LOCK_ID]);+ expect(held.map(row => Number(row.holder_pid))).toEqual([process.pid]);+ expect(await lock!.refresh()).toBe(true);+ } finally {+ await lock?.release();+ }+ expect(await live.executeRaw('SELECT 1 FROM gbrain_cycle_locks WHERE id = $1', [LOCK_ID])).toEqual([]);+ });+ });+}diff --git a/test/helpers/segmented-write-sweep.ts b/test/helpers/segmented-write-sweep.tsnew file mode 100644index 0000000000..e2908db554--- /dev/null+++ b/test/helpers/segmented-write-sweep.ts@@ -0,0 +1,257 @@+/**+ * #9213 sweep fixture: every mutating op of the registry, classified as one that loads the page it targets (PAGE_OPS,+ * with the call that drives it) or one that loads none (NO_PAGE_TARGET, with the reason), and a repo-less brain with a+ * credential per binding (local CLI, unbound token, member-bound, owner-bound, attested actor) to run them under.+ * Used by test/large-pages/segmented-write-sweep.test.ts (below the 24 MiB ceiling) and+ * test/large-pages/segmented-write-sweep-over-ceiling.slow.test.ts.+ */+import { expect } from 'bun:test';+import { createHash, randomUUID } from 'node:crypto';+import type { BrainEngine } from '../../src/core/engine.ts';+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';+import { importFromContent } from '../../src/core/import-file.ts';+import { PAGE_MAX_BYTES } from '../../src/core/page-size-policy.ts';+import { configureGateway, resetGateway, __setEmbedTransportForTests } from '../../src/core/ai/gateway.ts';+import { GBrainOAuthProvider } from '../../src/core/oauth-provider.ts';+import { sqlQueryForEngine } from '../../src/core/sql-query.ts';+import { dispatchToolCall } from '../../src/mcp/dispatch.ts';+import { operationsByName } from '../../src/core/operations.ts';+import { OperationError, type AuthInfo, type OperationContext } from '../../src/core/ops/contract.ts';+import { __resetPrivateVisibilityCacheForTests } from '../../src/core/search/private-visibility.ts';+import { addMember, bindCredential } from '../../src/core/access/members.ts';+import { setOwner } from '../../src/core/access/owner.ts';+import { linkMember } from '../../src/core/access/actor.ts';+import { disposePersistenceConsumer } from '../../src/core/persistence/service.ts';+import type { TestBackend } from './test-backends.ts';+import { isolatedPersistencePostgres } from './persistence-postgres.ts';++export const SRC = 'source-a';+export const OWNER = 'carol-example';+export const OTHER = 'companies/globex-example';+const QM_ALICE = 'U0ALICE';+const MEMORY_OPS = ['forget', 'forget_fact', 'get_write_request', 'memory_propose', 'memory_recall', 'memory_write', 'remember'];+const DIMS = 1536;+const WRITE_WAIT_MS = 60_000;+/** An upload part under the remote HTTP frame cap. */+const UPLOAD_PART_CHARS = 256 * 1024;+/** Lines of a body just over the 1 MiB inline bound: stored in segments, read back whole by a write that needs it. */+export const SEGMENTED_LINES = 16_000;++export type Who = 'local' | 'plain' | 'alice' | 'owner' | 'qm';+export type Call = { isError: boolean; text: string; json: Record<string, any>; dispatched: boolean };+export type Fixture = {+ call: (who: Who, op: string, params: Record<string, unknown>) => Promise<Call>;+ revision: (slug: string) => Promise<string>;+ localFact: (slug: string) => Promise<number>;+ localTake: (slug: string) => Promise<number>;+ versionId: (slug: string) => Promise<number>;+};+export interface Case {+ /** Bindings this op runs under; remote ones go through MCP dispatch with remote = true. */+ who: readonly Who[];+ /** The op's own call on page slug; setup reads and writes run locally. */+ run: (f: Fixture, slug: string, who: Who) => Promise<Call>;+ /** Replaces, deletes or restores the page: the over-ceiling pass gives it a page of its own. */+ replaces?: true;+ /** Why the over-ceiling pass does not run this op. */+ skipOver?: string;+}++const REMOTE: readonly Who[] = ['local', 'plain', 'alice', 'owner'];+const LOCAL: readonly Who[] = ['local'];+const MEMORY: readonly Who[] = ['local', 'plain', 'alice', 'owner', 'qm'];+const NO_FENCE_ROW = 'an over-ceiling page holds no facts or takes fence (its streamed import refuses one), so there is no row to target';+const op = (name: string, params: (f: Fixture, slug: string, who: Who) => Promise<Record<string, unknown>> | Record<string, unknown>) =>+ async (f: Fixture, slug: string, who: Who) => f.call(who, name, await params(f, slug, who));+const sha = (text: string) => createHash('sha256').update(text).digest('hex');++export function pageBody(lines: number, title: string, type = 'company'): string {+ const prose = Array.from({ length: lines }, (_, i) => 'Line ' + i + ' of a long note kept on the page so it is stored in segments.').join('\n');+ return '---\ntype: ' + type + '\ntitle: ' + title + '\n---\n# ' + title + '\n\n' + prose + '\n';+}++/** Every op whose handler loads a page it is pointed at (by slug, entity, target or a row on the page). */+export const PAGE_OPS: Record<string, Case> = {+ remember: { who: MEMORY, run: op('remember', (_f, slug) => ({ fact: 'Rule ' + randomUUID(), entity: slug, provenance: 'sweep' })) },+ forget: { who: MEMORY, skipOver: NO_FENCE_ROW, run: op('forget', async (f, slug) => ({ id: String(await f.localFact(slug)), reason: 'sweep' })) },+ forget_fact: { who: MEMORY, skipOver: NO_FENCE_ROW, run: op('forget_fact', async (f, slug) => ({ id: await f.localFact(slug), reason: 'sweep' })) },+ memory_propose: { who: ['qm'], run: op('memory_propose', (_f, slug) => ({ kind: 'timeline', target: slug, idempotency_key: randomUUID(), date: '2026-01-02', summary: 'Proposed ' + randomUUID() })) },+ put_page: { who: REMOTE, replaces: true, run: op('put_page', async (f, slug) => ({ slug, content: pageBody(SEGMENTED_LINES, 'Acme Example') + '\nOne more line.\n', expected_revision: await f.revision(slug) })) },+ put_pages: { who: REMOTE, replaces: true, run: op('put_pages', (_f, slug) => ({ pages: [{ slug, content: pageBody(SEGMENTED_LINES, 'Acme Example') + '\nOne more line.\n' }], request_id: randomUUID() })) },+ capture: { who: REMOTE, replaces: true, run: op('capture', async (f, slug) => ({ slug, content: pageBody(SEGMENTED_LINES, 'Acme Example') + '\nCaptured line.\n', expected_revision: await f.revision(slug) })) },+ begin_page_upload: { who: REMOTE, replaces: true, run: async (f, slug, who) => {+ const text = pageBody(SEGMENTED_LINES, 'Acme Example') + '\nUploaded line.\n';+ const begun = await f.call(who, 'begin_page_upload', { slug, mode: 'replace', total_bytes: Buffer.byteLength(text), sha256: sha(text), expected_revision: await f.revision(slug), request_id: randomUUID() });+ if (begun.isError) return begun;+ for (let at = 0, part = 0; at < text.length; at += UPLOAD_PART_CHARS, part++) {+ const piece = text.slice(at, at + UPLOAD_PART_CHARS);+ const sent = await f.call(who, 'upload_page_part', { upload_id: begun.json.upload_id, part, text: piece, part_sha256: sha(piece) });+ if (sent.isError) return sent;+ }+ return f.call(who, 'commit_page_upload', { upload_id: begun.json.upload_id });+ } },+ edit_page: { who: REMOTE, run: op('edit_page', async (f, slug, who) => {+ const line = 'Line ' + (100 + MEMORY.indexOf(who)) + ' of a long note';+ return { slug, expected_revision: await f.revision(slug), edits: [{ old_text: line, new_text: line + ', edited' }] };+ }) },+ append_page: { who: REMOTE, run: op('append_page', (_f, slug) => ({ slug, text: 'Appended ' + randomUUID() + '.', request_id: randomUUID() })) },+ add_tag: { who: REMOTE, run: op('add_tag', (_f, slug) => ({ slug, tag: 'sweep-tag' })) },+ remove_tag: { who: REMOTE, run: async (f, slug, who) => {+ await f.call('local', 'add_tag', { slug, tag: 'sweep-gone' });+ return f.call(who, 'remove_tag', { slug, tag: 'sweep-gone' });+ } },+ add_link: { who: REMOTE, run: op('add_link', (_f, slug) => ({ from: slug, to: OTHER, link_type: 'mentions' })) },+ remove_link: { who: REMOTE, run: async (f, slug, who) => {+ await f.call('local', 'add_link', { from: slug, to: OTHER, link_type: 'mentions' });+ return f.call(who, 'remove_link', { from: slug, to: OTHER, link_type: 'mentions' });+ } },+ add_timeline_entry: { who: REMOTE, run: op('add_timeline_entry', (_f, slug) => ({ slug, date: '2026-01-02', summary: 'Entry ' + randomUUID() })) },+ revert_version: { who: REMOTE, run: async (f, slug, who) => {+ await f.call('local', 'add_tag', { slug, tag: 'sweep-version-' + who });+ return f.call(who, 'revert_version', { slug, version_id: await f.versionId(slug), expected_revision: await f.revision(slug) });+ } },+ put_raw_data: { who: REMOTE, run: op('put_raw_data', (_f, slug) => ({ slug, source: 'sweep', data: { note: 'raw' } })) },+ ontology_propose: { who: REMOTE, run: op('ontology_propose', (_f, slug) => ({ entity: slug, dimension: 'industry', value: 'ledgers', visibility: 'world' })) },+ extract_entities: { who: REMOTE, run: op('extract_entities', (_f, slug) => ({ text: 'Globex Example met the team.', source_slug: slug })) },+ extract_facts: { who: REMOTE, run: op('extract_facts', (_f, slug) => ({ turn_text: 'Acme Example ships ledgers.', source_slug: slug, entity_hints: [slug], visibility: 'world' })) },+ takes_add: { who: REMOTE, run: op('takes_add', (_f, slug) => ({ slug, claim: 'Acme Example will grow ' + randomUUID(), kind: 'take', holder: 'world', weight: 0.6 })) },+ takes_update: { who: REMOTE, skipOver: NO_FENCE_ROW, run: async (f, slug, who) => f.call(who, 'takes_update', { slug, row_num: await f.localTake(slug), weight: 0.7 }) },+ takes_resolve: { who: REMOTE, skipOver: NO_FENCE_ROW, run: async (f, slug, who) => f.call(who, 'takes_resolve', { slug, row_num: await f.localTake(slug), quality: 'correct' }) },+ takes_supersede: { who: REMOTE, skipOver: NO_FENCE_ROW, run: async (f, slug, who) => f.call(who, 'takes_supersede', { slug, row_num: await f.localTake(slug), claim: 'Acme Example will grow faster ' + randomUUID() }) },+ takes_remove: { who: LOCAL, skipOver: NO_FENCE_ROW, run: async (f, slug, who) => f.call(who, 'takes_remove', { slug, row_num: await f.localTake(slug) }) },+ takes_rebuild: { who: LOCAL, run: op('takes_rebuild', (_f, slug) => ({ slug })) },+ confirm_memory: { who: REMOTE, run: op('confirm_memory', (_f, slug) => ({ ref: 'p:' + SRC + '/' + slug })) },+ extraction_review: { who: LOCAL, run: op('extraction_review', (_f, slug) => ({ action: 'distinct', slugs: [slug], of: OTHER })) },+ entity_identity_link: { who: LOCAL, run: op('entity_identity_link', (_f, slug) => ({ entity_id: 'acme-example', slug, source_id: SRC })) },+ delete_page: { who: REMOTE, replaces: true, run: op('delete_page', async (f, slug) => ({ slug, expected_revision: await f.revision(slug) })) },+ restore_page: { who: REMOTE, replaces: true, run: async (f, slug, who) => {+ await f.call('local', 'delete_page', { slug, expected_revision: await f.revision(slug) });+ return f.call(who, 'restore_page', { slug, expected_revision: await f.revision(slug) });+ } },+};++/** Mutating ops that never load an existing page as a Page object, with the reason; a new op must land in one list. */+export const NO_PAGE_TARGET: Record<string, string> = {+ purge_deleted_pages: 'bulk retention purge; its over-ceiling shared-origin case is pinned in segmented-write-sweep-over-ceiling.slow',+ upload_page_part: 'a part of an upload begin_page_upload opened (driven there)',+ commit_page_upload: 'commits an upload begin_page_upload opened (driven there)',+ abort_page_upload: 'drops an open upload; no page read',+ cancel_write_request: 'cancels a write request row',+ rate_answer: 'stores feedback on an answer; page slugs are recorded as text',+ put_skill: 'skill packs, not pages', delete_skill: 'skill packs, not pages', set_skill_policy: 'skill packs, not pages',+ prune_skill_revisions: 'skill packs, not pages', retain_skill_revision: 'skill packs, not pages', import_skill_proposal: 'skill packs, not pages',+ join_brain: 'brain membership', sync_brain_skills: 'brain membership', leave_brain: 'brain membership',+ sync_brain: 'repository sync; its segmented paths are pinned by the managed-sync segmented suites',+ log_ingest: 'appends an ingest log row; page slugs are text',+ file_upload: 'files row keyed by page slug; the page id is read by SQL, no Page object',+ file_register: 'files row keyed by page slug; the page id is read by SQL, no Page object',+ submit_job: 'job queue', cancel_job: 'job queue', retry_job: 'job queue', pause_job: 'job queue', resume_job: 'job queue',+ replay_job: 'job queue', send_job_message: 'job queue', submit_agent: 'job queue', watch_job: 'job queue', unwatch: 'job queue',+ think: 'creates its own answer page; it reads pages as search results, not snapshots',+ sources_add: 'source registry', sources_remove: 'source registry',+ request_tools: 'tool surface request', connector_sync: 'connector pages it creates; its segmented holds are pinned by connector-segmented-page-9062',+ chronicle_backfill: 'admin backfill over search results',+ entity_identity_unlink: 'removes an identity row by entity id and slug; no page read',+ purge_fact: 'admin purge of fact rows; a segmented fence read is pinned by the withdrawal suites',+ unpurge_page: 'clears a purge tombstone; the page no longer exists',+ memory_write: 'writes only to the caller\'s member page or memory/scope; the segmented scope page is pinned in remember-segmented-entity-9213',+ set_memory_writeback: 'config', memory_conversation_mode: 'config', mute_notice: 'config',+ code_traversal_cache_clear: 'cache', migrate_embeddings: 'embeddings', schema_apply_mutations: 'schema pack',+ run_onboard: 'onboarding job', run_skillopt: 'skill optimizer',+ loops_close: 'open-loop rows', loops_mute: 'open-loop rows', loops_unmute: 'open-loop rows',+ questions_pin: 'pinned questions', questions_refresh: 'pinned questions', questions_unpin: 'pinned questions',+};++/** segmentedRevertRefusal's message (src/core/page-state/versions.ts). */+const REVERT_REFUSAL = 'is stored in segments, so revert_version cannot restore it yet';++export type Outcome = { op: string; who: Who; segmented: boolean; getter: boolean; ceiling: boolean; readFix: boolean; dispatched: boolean; error: string | null };+export function outcome(name: string, who: Who, out: Call): Outcome {+ return {+ op: name, who, dispatched: out.dispatched,+ segmented: out.text.includes('page_body_segmented'),+ getter: /\.(compiled_truth|timeline|content): page .* stores its body in segments, and this path reads or writes the whole body as one string/.test(out.text),+ ceiling: out.text.includes('24 MiB') || out.text.includes(String(PAGE_MAX_BYTES)) || out.text.includes(REVERT_REFUSAL),+ readFix: out.json.fix?.mcp?.tool === 'get_page',+ error: out.isError ? String(out.json.code ?? out.json.error ?? out.text.slice(0, 160)) : null,+ };+}++export interface SweepBrain extends Fixture { engine: BrainEngine; storage: (slug: string) => Promise<{ body_storage: string; body_bytes: number; deleted: boolean } | undefined>; close: () => Promise<void> }++/** A repo-less brain in source-a with the owner, a member, a linked attested actor and one credential per binding. */+export async function openSweepBrain(kind: TestBackend): Promise<SweepBrain> {+ configureGateway({ embedding_model: 'openai:text-embedding-3-small', embedding_dimensions: DIMS, env: { OPENAI_API_KEY: 'test' } });+ __setEmbedTransportForTests((async ({ values }: { values: string[] }) => ({ embeddings: values.map(() => Array.from({ length: DIMS }, (_, i) => (i === 0 ? 1 : 0))) })) as never);+ let engine: BrainEngine;+ let closeEngine: () => Promise<void>;+ if (kind === 'postgres') ({ engine, close: closeEngine } = await isolatedPersistencePostgres(process.env.DATABASE_URL!));+ else { engine = new PGLiteEngine(); await engine.connect({ engine: 'pglite' } as never); await engine.initSchema(); closeEngine = () => engine.disconnect(); }+ __resetPrivateVisibilityCacheForTests();+ const provider = () => new GBrainOAuthProvider({ sql: sqlQueryForEngine(engine), transaction: fn => engine.transaction(tx => fn(sqlQueryForEngine(tx))) });+ await engine.executeRaw('INSERT INTO sources (id, name) VALUES ($1, $1) ON CONFLICT (id) DO NOTHING', [SRC]);+ for (const id of [OWNER, 'alice-example']) await addMember(engine, id);+ await setOwner(engine, OWNER);+ await linkMember(engine, 'alice-example', 'qm', QM_ALICE);+ await importFromContent(engine, OTHER, '---\ntype: company\ntitle: Globex Example\n---\n# Globex Example\n\nGlobex example runs a pilot.\n', { sourceId: SRC });+ const tokens: Partial<Record<Who, string>> = {};+ const bindings: Record<Exclude<Who, 'local'>, Parameters<typeof bindCredential>[2] | null> = {+ owner: { member: OWNER }, alice: { member: 'alice-example' }, plain: null, qm: { attestActor: 'qm', attestOps: MEMORY_OPS },+ };+ for (const [name, binding] of Object.entries(bindings) as Array<[Exclude<Who, 'local'>, Parameters<typeof bindCredential>[2] | null]>) {+ const c = await provider().registerClientManual('sweep-' + name + '-' + randomUUID().slice(0, 8), ['client_credentials'],+ name === 'owner' ? 'read write memory_confirm' : 'read write', [], SRC);+ if (binding) await bindCredential(engine, { kind: 'client', id: c.clientId }, binding);+ tokens[name] = (await provider().exchangeClientCredentials(c.clientId, c.clientSecret ?? '')).access_token;+ }+ const parse = (text: string) => { try { return JSON.parse(text) as Record<string, any>; } catch { return {}; } };+ async function call(who: Who, name: string, params: Record<string, unknown>): Promise<Call> {+ if (who === 'local' && operationsByName[name]?.localOnly) {+ // A local-only op is not on the MCP surface: run its handler as the trusted CLI does.+ const ctx: OperationContext = { engine, config: { engine: engine.kind, embedding_disabled: true } as never, sourceId: SRC, remote: false, dryRun: false,+ logger: { info() {}, warn() {}, error() {} }, writeWaitMs: WRITE_WAIT_MS };+ try {+ const text = JSON.stringify(await operationsByName[name]!.handler(ctx, { ...params }));+ return { isError: false, text, json: parse(text), dispatched: false };+ } catch (error) {+ if (!(error instanceof OperationError)) throw error;+ const text = JSON.stringify({ ...error.toJSON(), message: error.message });+ return { isError: true, text, json: parse(text), dispatched: false };+ }+ }+ const remote = who !== 'local';+ const auth = remote ? await provider().verifyAccessToken(tokens[who]!) as unknown as AuthInfo : undefined;+ const out = await dispatchToolCall(engine, name, { ...params }, remote+ ? { remote: true, transport: 'http', auth, sourceId: SRC, takesHoldersAllowList: ['world'], writeWaitMs: WRITE_WAIT_MS, ...(who === 'qm' ? { actor: { header: QM_ALICE } } : {}) }+ : { remote: false, sourceId: SRC, writeWaitMs: WRITE_WAIT_MS });+ return { isError: out.isError === true, text: out.content.map(c => c.text).join('\n'), json: parse(out.content[0]?.text ?? ''), dispatched: true };+ }+ const revision = async (slug: string) => (await engine.executeRaw<{ r: string }>('SELECT knowledge_revision::text AS r FROM pages WHERE source_id = $1 AND slug = $2', [SRC, slug]))[0]!.r;+ return {+ engine, call, revision,+ localFact: async slug => {+ const out = await call('local', 'remember', { fact: 'Sweep fact ' + randomUUID(), entity: slug, provenance: 'sweep', visibility: 'world' });+ expect({ setup: 'remember', isError: out.isError }).toEqual({ setup: 'remember', isError: false });+ return Number(out.json.id);+ },+ localTake: async slug => {+ const out = await call('local', 'takes_add', { slug, claim: 'Acme Example will grow ' + randomUUID(), kind: 'take', holder: 'world', weight: 0.5 });+ expect({ setup: 'takes_add', isError: out.isError }).toEqual({ setup: 'takes_add', isError: false });+ return Number((await engine.executeRaw<{ n: number }>(+ 'SELECT max(t.row_num) AS n FROM takes t JOIN pages p ON p.id = t.page_id WHERE p.source_id = $1 AND p.slug = $2', [SRC, slug]))[0]!.n);+ },+ versionId: async slug => Number((await engine.executeRaw<{ id: number }>(+ 'SELECT v.id FROM page_versions v JOIN pages p ON p.id = v.page_id WHERE p.source_id = $1 AND p.slug = $2 ORDER BY v.id DESC LIMIT 1', [SRC, slug]))[0]?.id ?? 0),+ storage: async slug => {+ const [row] = await engine.executeRaw<{ body_storage: string; body_bytes: string | null; deleted: boolean }>(+ 'SELECT body_storage, body_bytes::text AS body_bytes, deleted_at IS NOT NULL AS deleted FROM pages WHERE source_id = $1 AND slug = $2', [SRC, slug]);+ return row && { body_storage: row.body_storage, body_bytes: Number(row.body_bytes ?? 0), deleted: row.deleted === true };+ },+ close: async () => {+ __setEmbedTransportForTests(null);+ resetGateway();+ await disposePersistenceConsumer(engine).catch(() => undefined);+ await closeEngine();+ },+ };+}diff --git a/test/large-pages/segmented-write-sweep-over-ceiling.slow.test.ts b/test/large-pages/segmented-write-sweep-over-ceiling.slow.test.tsnew file mode 100644index 0000000000..68e5f176f6--- /dev/null+++ b/test/large-pages/segmented-write-sweep-over-ceiling.slow.test.ts@@ -0,0 +1,148 @@+/**+ * #9213 sweep, over the 24 MiB single-string ceiling: on a page that size only the writes that edit its body whole+ * refuse, and the retention purge of an over-ceiling shared-origin tombstone removes it.+ *+ * 1. Protects: on a page over the ceiling every op of PAGE_OPS (test/helpers/segmented-write-sweep.ts) that does not+ * rewrite the body whole lands; the ops in OVER_CEILING_REFUSALS refuse page_body_segmented by the route listed+ * there ('ceiling': a refusal that names the ceiling; 'getter': a whole-body rewrite that reads the body through the+ * page's guarded getter), and a dispatched refusal never hands back the get_page read fix, which cannot help a write.+ * An expired tombstone of a segmented page over the ceiling whose file another page records (shared origin) is+ * purged by the retention purge, which reads no body.+ * 2. Fails when: a label or bookkeeping path reads the body of an over-ceiling page (a new getter refusal), a listed+ * refusal starts landing or changes route without the list changing, or the shared-origin retention purge copies+ * the page with its body getters again (managed_purge_failed, rowToPage.compiled_truth).+ * 3. Existing coverage: segmented-write-sweep.test.ts is the same sweep below the ceiling;+ * test/purge-shared-origin-tombstone-7311.test.ts pins the shared-origin retention purge on small pages.+ * 4. Real seams: MCP dispatch with real OAuth tokens, a repo-less brain, the streamed import of an over-ceiling page, a+ * managed brain with a git worktree, the coordinated purge, PGLite and Postgres.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { execFileSync } from 'node:child_process';+import { randomUUID } from 'node:crypto';+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import type { BrainEngine } from '../../src/core/engine.ts';+import { importFromFile } from '../../src/core/import-file.ts';+import { readPageBodyPolicy } from '../../src/core/page-body/limits.ts';+import { PAGE_MAX_BYTES } from '../../src/core/page-size-policy.ts';+import { submitPageMutation } from '../../src/core/persistence/page-mutations.ts';+import { performManagedSync } from '../../src/core/persistence/sync-run.ts';+import { purgeDeletedPagesCoordinated } from '../../src/core/persistence/purge-deleted.ts';+import { requirePostgresTestDatabase, testBackends } from '../helpers/test-backends.ts';+import { managedBrain } from '../helpers/managed-brain.ts';+import { dropOriginIndex } from '../helpers/origin-index.ts';+import { PAGE_OPS, SRC, openSweepBrain, outcome, pageBody, type Outcome, type SweepBrain, type Who } from '../helpers/segmented-write-sweep.ts';++const SWEEP_MS = 1_800_000;+const PURGE_MS = 600_000;+/** Lines of a note over the 24 MiB ceiling (a type with no derived aliases and no fences, which its streamed import refuses). */+const OVER_CEILING_LINES = 350_000;+const OVER_CEILING_BINDINGS: readonly Who[] = ['local', 'plain', 'owner'];+/** Retention window of the purge, in hours, and the age a tombstone is given past it. */+const RETENTION_HOURS = 72;+const EXPIRED_AGE = '73 hours';++/** Ops that refuse a page over the ceiling, with why and by which route. */+const OVER_CEILING_REFUSALS: Record<string, { why: string; via: 'ceiling' | 'getter' }> = {+ remember: { via: 'ceiling', why: 'adds a row to the facts fence, read whole (segmentedRememberRefusal; its fix saves the claim unattributed)' },+ add_timeline_entry: { via: 'ceiling', why: 'splices the timeline, read whole' },+ takes_add: { via: 'ceiling', why: 'edits the takes fence, read whole' },+ revert_version: { via: 'ceiling', why: 'reverting a segmented page is refused at any size (segmented_revert)' },+ put_page: { via: 'getter', why: 'whole-body rewrite: the local put reads the old body for its non-empty check (remote puts refuse page_shrink_refused first)' },+ capture: { via: 'getter', why: 'whole-body rewrite of the page' },+ begin_page_upload: { via: 'getter', why: 'whole-body replace upload (remote uploads refuse page_shrink_refused first)' },+ confirm_memory: { via: 'getter', why: 'rewrites the body whole to drop the unconfirmed marker' },+ extraction_review: { via: 'getter', why: 'records the review by editing the body as one string' },+};++describe('the over-ceiling list names page ops the sweep runs', () => {+ test('every listed op is in PAGE_OPS and runs over the ceiling', () => {+ expect(Object.keys(OVER_CEILING_REFUSALS).filter(name => !(name in PAGE_OPS) || PAGE_OPS[name]!.skipOver)).toEqual([]);+ });+});++for (const kind of testBackends()) {+ describe('writes on a segmented page over the ceiling (' + kind + ', repo-less, #9213 sweep)', () => {+ let brain: SweepBrain;+ let dir: string;+ beforeAll(async () => {+ brain = await openSweepBrain(kind);+ dir = mkdtempSync(join(tmpdir(), 'gbrain-sweep-9213-'));+ const text = pageBody(OVER_CEILING_LINES, 'Acme Example', 'note');+ expect(Buffer.byteLength(text)).toBeGreaterThan(PAGE_MAX_BYTES);+ writeFileSync(join(dir, 'page.md'), text);+ }, SWEEP_MS);+ afterAll(async () => {+ if (dir) rmSync(dir, { recursive: true, force: true });+ await brain?.close();+ }, SWEEP_MS);++ /** A live page over the ceiling stored in segments at slug: imported again only when it no longer is one. */+ async function overCeilingPage(slug: string): Promise<void> {+ const usable = (row: Awaited<ReturnType<SweepBrain['storage']>>) => row && !row.deleted && row.body_storage === 'segmented' && row.body_bytes > PAGE_MAX_BYTES;+ const row = await brain.storage(slug);+ if (usable(row)) return;+ if (row?.deleted) {+ expect(await brain.call('local', 'restore_page', { slug, expected_revision: await brain.revision(slug) })).toMatchObject({ isError: false });+ if (usable(await brain.storage(slug))) return;+ }+ expect(await importFromFile(brain.engine, join(dir, 'page.md'), slug + '.md', { noEmbed: true, sourceId: SRC, bodyPolicy: await readPageBodyPolicy(brain.engine) })).toMatchObject({ status: 'imported' });+ const after = await brain.storage(slug);+ expect({ slug, storage: after?.body_storage, deleted: after?.deleted, over: (after?.body_bytes ?? 0) > PAGE_MAX_BYTES }).toEqual({ slug, storage: 'segmented', deleted: false, over: true });+ }++ test('only the listed whole-body writes refuse, each by its listed route', async () => {+ const outcomes: Outcome[] = [];+ for (const [name, c] of Object.entries(PAGE_OPS).filter(([, c]) => !c.skipOver)) {+ const who = c.who.filter(w => OVER_CEILING_BINDINGS.includes(w));+ const slug = c.replaces ? 'notes/sweep-over-ceiling-' + name.replace(/_/g, '-') : 'notes/sweep-over-ceiling';+ for (const w of who.length ? who : c.who) {+ await overCeilingPage(slug);+ outcomes.push(outcome(name, w, await c.run(brain, slug, w)));+ }+ }+ console.log('[sweep over ceiling] refusals ' + JSON.stringify(outcomes.filter(o => o.error).map(o => [o.op, o.who, o.error, o.getter ? 'getter' : o.ceiling ? 'ceiling' : '-'])));+ const route = (o: Outcome) => (o.getter ? 'getter' : o.ceiling ? 'ceiling' : 'other');+ expect(outcomes.filter(o => o.segmented && OVER_CEILING_REFUSALS[o.op]?.via !== route(o))).toEqual([]);+ expect(outcomes.filter(o => o.getter && !o.segmented)).toEqual([]);+ const refused = new Set(outcomes.filter(o => o.segmented).map(o => o.op));+ expect(Object.keys(OVER_CEILING_REFUSALS).filter(name => !refused.has(name))).toEqual([]);+ expect(outcomes.filter(o => o.segmented && o.dispatched && o.readFix)).toEqual([]);+ }, SWEEP_MS);+ });+}++const git = (root: string, ...args: string[]) => execFileSync('git', ['-C', root, ...args], { encoding: 'utf8' }).trim();+const SMALL_FILE = 'notes/x-example.md', BIG_FILE = 'notes/big-example.md', BIG = 'notes/big-example';+/** A fixture write as legacy data left it: managed persistence off around the statement. */+async function raw<T>(engine: BrainEngine, fn: () => Promise<T>): Promise<T> {+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');+ try { return await fn(); } finally { await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1'); }+}+const setup = ({ root }: { root: string }) => {+ mkdirSync(join(root, 'notes'), { recursive: true }); git(root, 'init', '-q');+ writeFileSync(join(root, SMALL_FILE), '---\ntype: note\ntitle: X Example\n---\n\nSmall.\n');+ writeFileSync(join(root, BIG_FILE), pageBody(OVER_CEILING_LINES, 'Big Example', 'note'));+ git(root, 'add', '-A'); git(root, '-c', 'user.name=Example', '-c', '[email protected]', 'commit', '-qm', 'notes');+};++for (const kind of testBackends()) {+ const databaseUrl = kind === 'postgres' ? requirePostgresTestDatabase() : undefined;+ describe('retention purge of an over-ceiling shared-origin tombstone (' + kind + ', #9213 sweep)', () => {+ test('the expired tombstone is purged; nothing is blocked page_body_segmented', () => managedBrain(async ({ engine, ctx }) => {+ expect((await performManagedSync(engine, { sourceId: 'default', noPull: true, noEmbed: true, noExtract: true })).status).toBe('first_sync');+ const [big] = await engine.executeRaw<{ body_storage: string; body_bytes: string }>("SELECT body_storage, body_bytes::text AS body_bytes FROM pages WHERE source_id='default' AND slug=$1", [BIG]);+ expect({ storage: big?.body_storage, over: Number(big?.body_bytes) > PAGE_MAX_BYTES }).toEqual({ storage: 'segmented', over: true });+ await dropOriginIndex(engine);+ await raw(engine, () => engine.executeRaw("UPDATE pages SET source_path=$1 WHERE source_id='default' AND slug=$2", [SMALL_FILE, BIG]));+ const [row] = await engine.executeRaw<{ revision: string }>("SELECT knowledge_revision::text AS revision FROM pages WHERE source_id='default' AND slug=$1", [BIG]);+ const deleted = await submitPageMutation(ctx, { operation: 'delete_page', params: { slug: BIG, expected_revision: row!.revision, request_id: randomUUID() } });+ expect(deleted).toMatchObject({ status: 'soft_deleted', write_through: { skipped: 'shared_origin', written: false } });+ await raw(engine, () => engine.executeRaw("UPDATE pages SET deleted_at = now() - $1::interval WHERE source_id='default' AND deleted_at IS NOT NULL", [EXPIRED_AGE]));+ const out = await purgeDeletedPagesCoordinated(engine, RETENTION_HOURS, { automatic: true });+ expect({ count: out.count, blocked: out.blocked, error: out.error ?? null }).toEqual({ count: 1, blocked: [], error: null });+ expect(await engine.executeRaw("SELECT slug FROM pages WHERE source_id='default' AND slug=$1", [BIG])).toEqual([]);+ }, { setup, databaseUrl }), PURGE_MS);+ });+}diff --git a/test/large-pages/segmented-write-sweep.test.ts b/test/large-pages/segmented-write-sweep.test.tsnew file mode 100644index 0000000000..bf4378dd29--- /dev/null+++ b/test/large-pages/segmented-write-sweep.test.ts@@ -0,0 +1,74 @@+/**+ * #9213 sweep, below the 24 MiB ceiling: every write that can target an existing page, run against a page stored in+ * segments under every credential binding, reads only what it needs.+ *+ * 1. Protects: a label check (visibility, readers, folder rules, scope sharing) never touches the body of a page stored+ * in segments, so on a 1.3 MB segmented page no op refuses page_body_segmented under any binding (local CLI, unbound+ * token, member-bound, owner-bound, attested for the memory ops), except revert_version, which refuses every+ * segmented page by design; a dispatched write refused page_body_segmented never hands back the get_page read fix.+ * 2. Fails when: a write or access-check path spreads, stringifies or copies a page loaded with guardSegmentedBody's+ * throwing getters (rowToPage.compiled_truth), or a new mutating op joins the registry without being classified in+ * test/helpers/segmented-write-sweep.ts.+ * 3. Existing coverage: test/remember-segmented-entity-9213.test.ts pins the remember and scope-page cases with their+ * stored facts; segmented-write-sweep-over-ceiling.slow.test.ts runs the same ops over the ceiling.+ * 4. Real seams: the operation registry, OAuth client-credentials tokens, MCP dispatch as remote and local callers, a+ * repo-less brain, PGLite and Postgres.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { importFromContent } from '../../src/core/import-file.ts';+import { operations } from '../../src/core/operations.ts';+import { testBackends } from '../helpers/test-backends.ts';+import { NO_PAGE_TARGET, PAGE_OPS, SEGMENTED_LINES, SRC, openSweepBrain, outcome, pageBody, type Outcome, type SweepBrain } from '../helpers/segmented-write-sweep.ts';++const SWEEP_MS = 900_000;+/** Ops whose every binding is refused for a reason of their own. */+const NOT_REACHED: Record<string, string> = {+ revert_version: 'refuses every segmented page by design (page_body_segmented, reason segmented_revert)',+};++describe('the sweep classifies every mutating op in the registry', () => {+ test('each mutating op is a page op or names why it loads no page; no stale names, no overlap', () => {+ const mutating = operations.filter(o => o.mutating).map(o => o.name).sort();+ const classified = [...Object.keys(PAGE_OPS), ...Object.keys(NO_PAGE_TARGET)];+ expect(mutating.filter(name => !classified.includes(name))).toEqual([]);+ expect(classified.filter(name => !mutating.includes(name))).toEqual([]);+ expect(Object.keys(PAGE_OPS).filter(name => name in NO_PAGE_TARGET)).toEqual([]);+ });+});++for (const kind of testBackends()) {+ describe('writes on a segmented page below the ceiling (' + kind + ', repo-less, #9213 sweep)', () => {+ let brain: SweepBrain;+ beforeAll(async () => { brain = await openSweepBrain(kind); }, SWEEP_MS);+ afterAll(async () => { await brain?.close(); }, SWEEP_MS);++ /** A live page stored in segments at slug: imported when it is missing, deleted or no longer segmented. */+ async function segmentedPage(slug: string): Promise<void> {+ const row = await brain.storage(slug);+ if (!row || row.deleted || row.body_storage !== 'segmented') {+ if (row?.deleted) await brain.call('local', 'restore_page', { slug, expected_revision: await brain.revision(slug) });+ await importFromContent(brain.engine, slug, pageBody(SEGMENTED_LINES, 'Acme Example'), { sourceId: SRC });+ }+ const after = await brain.storage(slug);+ expect({ slug, storage: after?.body_storage, deleted: after?.deleted }).toEqual({ slug, storage: 'segmented', deleted: false });+ }++ test('no op refuses page_body_segmented under any binding, and each op lands for some binding', async () => {+ const outcomes: Outcome[] = [];+ for (const [name, c] of Object.entries(PAGE_OPS)) {+ const slug = 'companies/sweep-' + name.replace(/_/g, '-');+ for (const who of c.who) {+ await segmentedPage(slug);+ outcomes.push(outcome(name, who, await c.run(brain, slug, who)));+ }+ }+ console.log('[sweep below ceiling] refusals ' + JSON.stringify(outcomes.filter(o => o.error).map(o => [o.op, o.who, o.error])));+ expect(outcomes.filter(o => o.getter)).toEqual([]);+ expect(outcomes.filter(o => o.segmented && !(o.op in NOT_REACHED))).toEqual([]);+ const landed = new Set(outcomes.filter(o => o.error === null).map(o => o.op));+ expect(Object.keys(PAGE_OPS).filter(name => !landed.has(name) && !(name in NOT_REACHED))).toEqual([]);+ expect(outcomes.filter(o => o.op === 'revert_version').map(o => [o.error, o.ceiling])).toEqual(PAGE_OPS.revert_version!.who.map(() => ['page_body_segmented', true]));+ expect(outcomes.filter(o => o.segmented && o.dispatched && o.readFix)).toEqual([]);+ }, SWEEP_MS);+ });+}diff --git a/test/persistence-owner-fault-9224.test.ts b/test/persistence-owner-fault-9224.test.tsnew file mode 100644index 0000000000..1d8570aa4e--- /dev/null+++ b/test/persistence-owner-fault-9224.test.ts@@ -0,0 +1,77 @@+/**+ * #9224: a fault inside the persistence owner that is not an OperationError reached a delegated caller as+ * "storage_error: The persistence owner could not complete this request", with a doctor fix that could not see it,+ * and the owner kept no trace of the cause.+ *+ * 1. Protects: the caller gets `internal_error` (detail `owner_internal`) naming an incident ID, that the request+ * was not at fault, how to recover, the write's request ID when it was a write, and a read-only fix naming the+ * owner; the cause goes to the owner's own stderr under the same incident ID and never crosses the socket.+ * 2. Fails when: the cause (a driver message, a connection string) crosses the socket, or the caller gets no code,+ * fix or incident to act on.+ * 3. Real seams: the real persistence listener and client over a local socket.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { randomUUID } from 'node:crypto';+import { mkdtempSync, rmSync } from 'node:fs';+import { once } from 'node:events';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { OperationError } from '../src/core/ops/contract.ts';+import { requestPersistenceOperation, startPersistenceIpcServer, type PersistenceIpcBinding, type PersistenceIpcRequest } from '../src/core/persistence/ipc.ts';++const CANARY = 'OWNER_FAULT_CANARY_9224';+const BRAIN = randomUUID();+const home = mkdtempSync(join(tmpdir(), 'gbrain-owner-fault-'));+let ipc: PersistenceIpcBinding;+const logged: string[] = [];++function request(operation: PersistenceIpcRequest['operation'], params: Record<string, unknown>): PersistenceIpcRequest {+ return { version: 1, kind: 'operation', brain_id: BRAIN, operation, params,+ registration: { id: randomUUID(), credential: 'a'.repeat(64), lane: 'cli' }, routing: { source: 'source-a', cwd: home } };+}++async function refusal(req: PersistenceIpcRequest): Promise<OperationError> {+ const write = process.stderr.write.bind(process.stderr);+ process.stderr.write = ((chunk: string | Uint8Array) => { logged.push(String(chunk)); return true; }) as typeof process.stderr.write;+ try {+ return await requestPersistenceOperation(ipc.socketPath, req).then(() => { throw new Error('the owner fault was not refused'); }, (e: unknown) => e as OperationError);+ } finally { process.stderr.write = write; }+}++describe('an owner fault over the persistence socket (#9224)', () => {+ beforeAll(async () => {+ ipc = (await startPersistenceIpcServer(join(home, 'owner.sock'), {+ brainId: BRAIN,+ dispatch: async () => { throw new TypeError(`${CANARY} at postgres://writer:[email protected]/brain`); },+ }))!;+ });+ afterAll(async () => { const closed = once(ipc.server, 'close'); ipc.close(); await closed; rmSync(home, { recursive: true, force: true }); });++ test('a read gets internal_error with an incident, the recovery and a read-only fix naming the owner', async () => {+ logged.length = 0;+ const error = await refusal(request('get_page', { slug: 'notes/alpha-example' }));+ expect(error).toBeInstanceOf(OperationError);+ expect(error.code).toBe('internal_error');+ expect(error.detail).toBe('owner_internal');+ const incident = /incident ([0-9a-f-]{36})/.exec(error.message)?.[1];+ expect(incident).toBeDefined();+ expect(error.message).toContain('the request itself was not at fault');+ expect(error.suggestion).toContain('Restart that owner');+ expect(error.suggestion).not.toContain('write-request');+ expect(error.fix).toMatchObject({ argv: ['gbrain', 'sources', 'writer', 'status', '--json'], actor: 'agent', consent: [] });+ const wire = JSON.stringify(error.toJSON());+ expect(wire).not.toContain(CANARY);+ expect(wire).not.toContain('hunter2');+ const line = logged.find(l => l.includes(incident!)) ?? '';+ expect(line).toContain(CANARY);+ expect(line).not.toContain('hunter2');+ });++ test('a write names its request ID to inspect before resubmitting', async () => {+ const requestId = randomUUID();+ const error = await refusal(request('put_page', { slug: 'notes/alpha-example', content: 'Alpha example.', request_id: requestId }));+ expect(error.code).toBe('internal_error');+ expect(error.suggestion).toContain(`gbrain write-request ${requestId}`);+ expect(JSON.stringify(error.toJSON())).not.toContain(CANARY);+ });+});diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txtindex 8844966e9f..fc0ffc230a 100644--- a/test/postgres-unit-arms.txt+++ b/test/postgres-unit-arms.txt@@ -81,6 +81,7 @@ test/db-lock-reconnect.test.tstest/db-only-labels-gst2519.test.tstest/decide/conflict-proposals-managed.test.tstest/declared-lineage-visibility.test.ts+test/degraded-engine-recovered-surface-9224.test.tstest/derived-link-reconciliation.test.tstest/direct-pool-profile.test.tstest/doctor-attest-read-shared-scope.test.ts@@ -273,6 +274,8 @@ test/large-pages/segmented-timeline-retract-versions.test.tstest/large-pages/segmented-versions.test.tstest/large-pages/segmented-withdrawal-mirror.test.tstest/large-pages/segmented-withdrawn-fence-delete.test.ts+test/large-pages/segmented-write-sweep-over-ceiling.slow.test.ts+test/large-pages/segmented-write-sweep.test.tstest/large-pages/streamed-import-drift.test.tstest/large-pages/streamed-sync-origin-b14.test.tstest/large-pages/stuck-recovery-large.slow.test.ts@@ -531,6 +534,7 @@ test/refresh-write-barrier.test.tstest/remediation-manual-only.test.tstest/remember-batch-entity-7432.test.tstest/remember-pageless-entity-gst2446.test.ts+test/remember-segmented-entity-9213.test.tstest/remember-share-gst2243.test.tstest/remember-strict-held-gst2492.test.tstest/repair-apply-pending-6543.test.tsdiff --git a/test/remember-segmented-entity-9213.test.ts b/test/remember-segmented-entity-9213.test.tsnew file mode 100644index 0000000000..a8b6d4f14d--- /dev/null+++ b/test/remember-segmented-entity-9213.test.ts@@ -0,0 +1,157 @@+/**+ * #9213: a remember onto an entity page stored in segments, from every credential binding, reads the page's labels and+ * never its body.+ *+ * 1. Protects: the owner-bound remember (explicit visibility "world" and the default visibility) onto a segmented+ * entity page commits as the unbound one does; a member-bound and an attested remember name it as their entity and+ * commit; an attested memory_write saves onto a segmented scope page (memory/scope).+ * 2. Fails when: a label check (owner visibility, folder rules, scope-page sharing) spreads the snapshot page, whose+ * segmented body fields are getters that throw page_body_segmented on purpose.+ * 3. Real seams: OAuth client-credentials tokens bound to the owner, a member and an attested actor, MCP dispatch as+ * remote callers, a repo-less brain, pages imported large enough to be stored in segments, PGLite and Postgres.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { randomUUID } from 'node:crypto';+import type { BrainEngine } from '../src/core/engine.ts';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { importFromContent } from '../src/core/import-file.ts';+import { configureGateway, resetGateway, __setEmbedTransportForTests } from '../src/core/ai/gateway.ts';+import { GBrainOAuthProvider } from '../src/core/oauth-provider.ts';+import { sqlQueryForEngine } from '../src/core/sql-query.ts';+import { dispatchToolCall } from '../src/mcp/dispatch.ts';+import { __resetPrivateVisibilityCacheForTests } from '../src/core/search/private-visibility.ts';+import { addMember, bindCredential } from '../src/core/access/members.ts';+import { setOwner } from '../src/core/access/owner.ts';+import { linkMember } from '../src/core/access/actor.ts';+import { rescopeClientGrant } from '../src/core/grants/service.ts';+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';+import type { AuthInfo } from '../src/core/ops/contract.ts';+import { testBackends } from './helpers/test-backends.ts';+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';++const SRC = 'source-a';+const SCOPE = 'scope-a';+const OWNER = 'carol-example';+const ENTITY = 'companies/acme-example';+const SCOPE_PAGE = 'memory/scope';+const QM_ALICE = 'U0ALICE';+const MEMORY_OPS = ['forget', 'forget_fact', 'get_write_request', 'memory_recall', 'memory_write', 'remember'];+const DIMS = 1536;+const LONG_LINES = 16_000;+const TEST_MS = 240_000;+const WRITE_WAIT_MS = 30_000;++/** A page body over the 1 MiB inline ceiling, so import stores it in segments. */+function largePage(type: string, title: string): string {+ const prose = Array.from({ length: LONG_LINES }, (_, i) => 'Line ' + i + ' of a long standing note kept on the page so it is stored in segments.').join('\n');+ return '---\ntype: ' + type + '\ntitle: ' + title + '\n---\n# ' + title + '\n\n' + prose + '\n';+}++type Who = 'owner' | 'alice' | 'plain' | 'qm' | 'scopes';+type Call = { isError: boolean; text: string };++for (const kind of testBackends()) {+ describe('remember onto a segmented page (' + kind + ', repo-less, #9213)', () => {+ let engine: BrainEngine;+ let close: () => Promise<void>;+ const tokens: Partial<Record<Who, string>> = {};+ const provider = () => new GBrainOAuthProvider({ sql: sqlQueryForEngine(engine), transaction: fn => engine.transaction(tx => fn(sqlQueryForEngine(tx))) });++ async function call(who: Who, op: string, params: Record<string, unknown>): Promise<Call> {+ const auth = await provider().verifyAccessToken(tokens[who]!) as unknown as AuthInfo;+ const actor = who === 'qm' || who === 'scopes' ? { actor: { header: QM_ALICE } } : {};+ const out = await dispatchToolCall(engine, op, { ...params }, {+ remote: true, transport: 'http', auth, sourceId: SRC, takesHoldersAllowList: ['world'], writeWaitMs: WRITE_WAIT_MS, ...actor,+ });+ return { isError: out.isError === true, text: out.content.map(c => c.text).join('\n') };+ }+ const factRow = async (canary: string) => (await engine.executeRaw<{ source_id: string; visibility: string; source_markdown_slug: string | null; entity_slug: string | null }>(+ 'SELECT source_id, visibility, source_markdown_slug, entity_slug FROM facts WHERE fact LIKE $1 ORDER BY id DESC LIMIT 1', ['%' + canary + '%']))[0];+ const storage = async (sourceId: string, slug: string) => (await engine.executeRaw<{ body_storage: string }>(+ 'SELECT body_storage FROM pages WHERE source_id = $1 AND slug = $2', [sourceId, slug]))[0]?.body_storage;+ const canary = (tag: string) => 'canary' + tag + randomUUID().slice(0, 8);++ beforeAll(async () => {+ configureGateway({ embedding_model: 'openai:text-embedding-3-small', embedding_dimensions: DIMS, env: { OPENAI_API_KEY: 'test' } });+ __setEmbedTransportForTests((async ({ values }: { values: string[] }) => ({ embeddings: values.map(() => Array.from({ length: DIMS }, (_, i) => (i === 0 ? 1 : 0))) })) as never);+ if (kind === 'postgres') ({ engine, close } = await isolatedPersistencePostgres(process.env.DATABASE_URL!));+ else { engine = new PGLiteEngine(); await engine.connect({ engine: 'pglite' } as never); await engine.initSchema(); close = () => engine.disconnect(); }+ __resetPrivateVisibilityCacheForTests();+ for (const id of [SRC, SCOPE]) await engine.executeRaw('INSERT INTO sources (id, name) VALUES ($1, $1) ON CONFLICT (id) DO NOTHING', [id]);+ for (const id of [OWNER, 'alice-example']) await addMember(engine, id);+ await setOwner(engine, OWNER);+ await linkMember(engine, 'alice-example', 'qm', QM_ALICE);+ await importFromContent(engine, ENTITY, largePage('company', 'Acme Example'), { sourceId: SRC });+ await importFromContent(engine, SCOPE_PAGE, largePage('note', 'Scope memory'), { sourceId: SCOPE });+ const bindings: Record<Who, Parameters<typeof bindCredential>[2] | null> = {+ owner: { member: OWNER }, alice: { member: 'alice-example' }, plain: null,+ qm: { attestActor: 'qm', attestOps: MEMORY_OPS },+ scopes: { attestActor: 'qm', attestOps: MEMORY_OPS.filter(op => op !== 'remember'), attestSources: [SCOPE] },+ };+ for (const [name, binding] of Object.entries(bindings) as Array<[Who, Parameters<typeof bindCredential>[2] | null]>) {+ const c = await provider().registerClientManual('s9213-' + name + '-' + randomUUID().slice(0, 8), ['client_credentials'], 'read write', [], SRC);+ if (binding) await bindCredential(engine, { kind: 'client', id: c.clientId }, binding);+ if (name === 'scopes') await rescopeClientGrant(engine, c.clientId, { federatedRead: [SRC, SCOPE] }, { actor: 'test' });+ tokens[name] = (await provider().exchangeClientCredentials(c.clientId, c.clientSecret ?? '')).access_token;+ }+ }, TEST_MS);++ afterAll(async () => {+ __setEmbedTransportForTests(null);+ resetGateway();+ await disposePersistenceConsumer(engine).catch(() => undefined);+ await close?.();+ }, TEST_MS);++ test('both pages are stored in segments', async () => {+ expect(await storage(SRC, ENTITY)).toBe('segmented');+ expect(await storage(SCOPE, SCOPE_PAGE)).toBe('segmented');+ }, TEST_MS);++ test('the owner-bound remember with visibility "world" is saved world on the entity page', async () => {+ const c = canary('ownerworld');+ const out = await call('owner', 'remember', { fact: 'Standing rule ' + c, entity: ENTITY, visibility: 'world', provenance: 'test' });+ expect(out.text).not.toContain('page_body_segmented');+ expect(out.isError).toBe(false);+ expect(await factRow(c)).toMatchObject({ source_id: SRC, visibility: 'world', source_markdown_slug: ENTITY, entity_slug: ENTITY });+ }, TEST_MS);++ test('the owner-bound remember with the default visibility is saved world on the entity page', async () => {+ const c = canary('ownerdefault');+ const out = await call('owner', 'remember', { fact: 'Standing rule ' + c, entity: ENTITY, provenance: 'test' });+ expect(out.text).not.toContain('page_body_segmented');+ expect(out.isError).toBe(false);+ expect(await factRow(c)).toMatchObject({ source_id: SRC, visibility: 'world', source_markdown_slug: ENTITY, entity_slug: ENTITY });+ }, TEST_MS);++ test('the owner-bound remember with visibility "private" goes to the owner page, keyed to the entity', async () => {+ const c = canary('ownerprivate');+ const out = await call('owner', 'remember', { fact: 'Standing rule ' + c, entity: ENTITY, visibility: 'private', provenance: 'test' });+ expect(out.text).not.toContain('page_body_segmented');+ expect(out.isError).toBe(false);+ expect(await factRow(c)).toMatchObject({ visibility: 'private', source_markdown_slug: 'memory/members/' + OWNER, entity_slug: ENTITY });+ }, TEST_MS);++ test('an unbound, a member-bound and an attested remember naming the entity are saved', async () => {+ const expected: Record<string, { visibility: string; source_markdown_slug: string }> = {+ plain: { visibility: 'world', source_markdown_slug: ENTITY },+ alice: { visibility: 'private', source_markdown_slug: 'memory/members/alice-example' },+ qm: { visibility: 'private', source_markdown_slug: 'memory/members/alice-example' },+ };+ for (const who of ['plain', 'alice', 'qm'] as const) {+ const c = canary(who);+ const out = await call(who, 'remember', { fact: 'Standing rule ' + c, entity: ENTITY, provenance: 'test' });+ expect({ who, isError: out.isError, text: out.isError ? out.text : '' }).toEqual({ who, isError: false, text: '' });+ expect(await factRow(c)).toMatchObject({ ...expected[who], entity_slug: ENTITY });+ }+ }, TEST_MS);++ test('an attested memory_write onto a segmented scope page is saved world there', async () => {+ const c = canary('scope');+ const out = await call('scopes', 'memory_write', { facts: [{ fact: 'Scope rule ' + c, provenance: 'test' }], idempotency_key: randomUUID(), source_id: SCOPE });+ expect(out.text).not.toContain('page_body_segmented');+ expect(out.isError).toBe(false);+ expect(await factRow(c)).toMatchObject({ source_id: SCOPE, visibility: 'world', source_markdown_slug: SCOPE_PAGE });+ }, TEST_MS);+ });+}diff --git a/test/serve-status-mode.serial.test.ts b/test/serve-status-mode.serial.test.tsindex a5abc58890..06e9d152a4 100644--- a/test/serve-status-mode.serial.test.ts+++ b/test/serve-status-mode.serial.test.ts@@ -80,6 +80,13 @@ describe('status-only serve: lock contention → recovery in place (a)', () => {mkdirSync(notes, { recursive: true });writeFileSync(join(notes, 'm.md'), `---\ntitle: ${MARKER}\n---\n\n# ${MARKER}\n\nStatus-mode recall proof ${MARKER}.\n`);expect(cli(['import', notes, '--no-embed'], env).status).toBe(0);+ repo = join(home, 'repo');+ mkdirSync(repo);+ writeFileSync(join(repo, 'alpha.md'), '# Alpha example\n\nThe first committed note.\n');+ git('init', '-q');+ commitAll('first');+ expect(cli(['sources', 'add', 'repo-notes', '--path', repo], env).status).toBe(0);+ expect(cli(['sync', '--source', 'repo-notes', '--no-pull', '--json'], env).status).toBe(0);}, 120_000);afterAll(async () => {@@ -87,6 +94,10 @@ describe('status-only serve: lock contention → recovery in place (a)', () => {rmSync(home, { recursive: true, force: true });});+ let repo: string;+ const git = (...args: string[]) => expect(spawnSync('git', ['-C', repo, ...args], { encoding: 'utf8' }).status).toBe(0);+ const commitAll = (message: string) => { git('add', '.'); git('-c', 'user.name=Example', '-c', '[email protected]', 'commit', '-qm', message); };+test('second serve handshakes with gbrain_status naming the owner, then recovers when the owner closes', async () => {const owner = await connect(env);opened.push(owner);@@ -131,6 +142,18 @@ describe('status-only serve: lock contention → recovery in place (a)', () => {expect(JSON.stringify(body(found))).toContain(MARKER);}, 180_000);+ // #9224: the recovered serve is now the persistence owner, and a delegated sync with pages to write takes the sync+ // lock on its engine; before, it failed with storage_error (the owner: "Unknown engine kind for db-lock: pglite").+ test('the recovered serve owns the brain: a delegated sync with pages to write commits', () => {+ writeFileSync(join(repo, 'alpha.md'), '# Alpha example\n\nThe first committed note, edited.\n');+ writeFileSync(join(repo, 'beta.md'), '# Beta example\n\nA second committed note.\n');+ commitAll('second');+ const synced = cli(['sync', '--source', 'repo-notes', '--no-pull', '--json'], env);+ expect({ status: synced.status, stderr: synced.stderr.slice(-2000) }).toMatchObject({ status: 0 });+ expect(synced.stderr).toContain('Delegating to the registered PGLite owner');+ expect(JSON.parse(synced.stdout)).toMatchObject({ source_id: 'repo-notes', sync_status: 'synced', added: 1, modified: 1 });+ }, 120_000);+test('--fail-fast keeps the supervisor exit', () => {const holder = spawnSync('bun', ['--no-env-file', 'run', 'src/cli.ts', 'serve', '--fail-fast'], { cwd: process.cwd(), env: { ...env, GBRAIN_HOME: join(home, 'nope') }, input: '', encoding: 'utf8', timeout: 60_000 });expect(holder.status).not.toBe(0);