Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

Read the persistence mode fail-closed (#6482, fix wave 15 P4.1)

garrytan75d703e23436
diff --git a/docs/guides/error-codes.md b/docs/guides/error-codes.md
index a20918744e..099ab9c5ca 100644
--- a/docs/guides/error-codes.md
+++ b/docs/guides/error-codes.md
@@ -2774,7 +2774,7 @@ More: [docs/guides/google-connect.md#troubleshooting](../../docs/guides/google-c
| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |
|---|---|---|---|---|---|---|
-| Reading or writing durable storage failed. | The server failed; this is not a caller mistake. | Server-side failure, not a caller mistake. Run `gbrain doctor --json` on the brain host; if it repeats, report it to the user. | host_admin | `gbrain doctor --json` | 1 | no |
+| Reading or writing durable storage failed. | Usually a dropped connection or a failed statement; the same error after a rerun is not transient. `detail: persistence_mode_unknown` (#6482): the persistence_brain singleton is missing, duplicated or carries a non-boolean `enabled`, so gbrain cannot tell whether the brain is managed and refuses every write, sync, connector run and activation step that depends on it rather than route a managed brain through the unmanaged writer; only a well-formed `enabled: false` row selects the unmanaged path. | For persistence_mode_unknown: run gbrain sources writer status --probe --json on the brain host (it reports the malformed state instead of refusing), fix the persistence_brain row it names, then gbrain doctor --json. | host_admin | `gbrain doctor --json` | 1 | no |
### sync_in_progress
diff --git a/src/commands/doctor/checks/sync-failures.ts b/src/commands/doctor/checks/sync-failures.ts
index a972da681b..9d67e8acee 100644
--- a/src/commands/doctor/checks/sync-failures.ts
+++ b/src/commands/doctor/checks/sync-failures.ts
@@ -5,6 +5,7 @@ import { formatManagedSyncFailure, managedSyncRetryCommand, readManagedSyncFailu
import { resolveHoursEnv } from '../../../core/env-number.ts';
import { makeRemediationStep } from '../../../core/remediation-step.ts';
import { classifyManagedSyncOrphans } from '../../../core/persistence/managed-sync-orphans.ts';
+import { readManagedMode } from '../../../core/persistence/ownership.ts';
export async function checkSyncFailures(engine: BrainEngine | null, opts: { sourceIds?: string[]; remote?: boolean } = {}): Promise<Check | null> {
// #5452: sync refuses an archived source, so its failures cannot be cleared and are not a live health signal.
@@ -22,8 +23,9 @@ export async function checkSyncFailures(engine: BrainEngine | null, opts: { sour
if (!severity.unresolved) return entries.length || archivedCount ? { name: 'sync_failures', status: 'ok', message: `${entries.length ? 'All historical sync failures are acknowledged.' : 'No sync failures on active sources.'}${archivedNote}` } : null;
const summary = `${severity.unresolved} unresolved sync failure(s)${severity.auto_skipped ? ` (${severity.auto_skipped} auto-skipped — pages NOT indexed)` : ''}.${archivedNote}`;
if (opts.remote !== false) return { name: 'sync_failures', status: severity.status, message: summary + ' Ask the host operator to inspect doctor and repair the accepted sync; no paths or receipt details are exposed remotely.' };
- const [brain] = engine ? await engine.executeRaw<{ enabled: boolean }>('SELECT enabled FROM persistence_brain WHERE singleton=1') : [];
- const requiresManagedRetry = brain?.enabled || managed.length > 0 || legacy.some(row => row.managed_cursor_key);
+ // The `engine ?` tolerance is the doctor's: with no engine there is no managed retry to name; the read itself fails closed (#6482).
+ const managedBrain = engine ? await readManagedMode(engine) : false;
+ const requiresManagedRetry = managedBrain || managed.length > 0 || legacy.some(row => row.managed_cursor_key);
const details = managed.map(formatManagedSyncFailure);
const unresolvedLegacy = unacknowledgedSyncFailures(legacy);
details.push(...unresolvedLegacy.map(row => `${row.source_id}: ${row.path} (${row.code}: ${row.error})`));
diff --git a/src/commands/google-attachments.ts b/src/commands/google-attachments.ts
index 32ff3f6a05..df1c65838a 100644
--- a/src/commands/google-attachments.ts
+++ b/src/commands/google-attachments.ts
@@ -12,6 +12,7 @@ import { isValidSourceId } from '../core/source-id.ts';
import { parseGoogleSourceConfig, runGoogleAttachmentBackfill } from '../core/google/google-source.ts';
import type { FetchImpl } from '../core/google/google-clients.ts';
import { managedSyncAuthority } from '../core/persistence/sync-authority.ts';
+import { readManagedMode } from '../core/persistence/ownership.ts';
import { connectorCheckpointKey, connectorIdentity } from '../core/persistence/connector-identity.ts';
import type { GoogleSourceState } from '../core/google/types.ts';
import { isCredentialError } from '../core/creds/errors.ts';
@@ -108,8 +109,7 @@ export async function runGoogleAttachments(args: string[], connected?: BrainEngi
`Source ${parsed.sourceId} is missing, archived, or not a Google source in brain ${brain}. List the sources and pass the active Google one with --source.`,
{ fix: readFix(`Lists brain ${brain}'s sources with their kinds.`, { argv: ['gbrain', 'sources', 'list', '--brain', brain, '--json'] }) });
}
- const [mode] = await engine.executeRaw<{ enabled: boolean }>('SELECT enabled FROM persistence_brain WHERE singleton=1');
- if (!mode?.enabled) {
+ if (!await readManagedMode(engine)) {
throw opError('writer_coordinator_required', 'Attachment repair requires already-enabled managed persistence.',
`Brain ${brain} does not run managed persistence, and this repair never enables it. Ordinary ingestion of source ${parsed.sourceId} keeps working; enabling managed persistence is a separate decision for the user.`,
{ fix: readFix(`Shows brain ${brain}'s persistence and writer state.`, { argv: ['gbrain', 'doctor', '--brain', brain, '--json'] }) });
diff --git a/src/commands/import.ts b/src/commands/import.ts
index b71e045c26..f68f15a27f 100644
--- a/src/commands/import.ts
+++ b/src/commands/import.ts
@@ -44,6 +44,7 @@ import { acceptedPendingReceipt } from '../core/persistence/accepted-pending.ts'
import { estimateCostFromChars, lookupEmbeddingPrice } from '../core/embedding-pricing.ts';
import { getEmbeddingModel } from '../core/ai/gateway.ts';
import { managedRootMarkerFor } from '../core/persistence/root-registry.ts';
+import { readManagedMode } from '../core/persistence/ownership.ts';
/** Return a refusal when an import target lies outside every admitted root. */
export function configuredRootImportError(dir: string, configuredRoots: string[]): string | null {
@@ -502,8 +503,7 @@ export async function runImport(
throw new ImportAbortError(`import target not readable: ${dirArg}`);
}
- const [persistence] = await engine.executeRaw<{ enabled: boolean }>('SELECT enabled FROM persistence_brain WHERE singleton=1');
- const managedImport = persistence?.enabled === true;
+ const managedImport = await readManagedMode(engine);
if (managedImport && dir !== resolve(dirArg)) throw symlinkedRootAbort(dirArg, dir);
const singleFile = managedImport && lstatSync(dir).isFile();
const importRoot = singleFile ? dirname(dir) : dir;
diff --git a/src/commands/sync-delegate.ts b/src/commands/sync-delegate.ts
index 2927391569..9592a00ebc 100644
--- a/src/commands/sync-delegate.ts
+++ b/src/commands/sync-delegate.ts
@@ -527,8 +527,8 @@ export async function maybeDelegateManagedSyncToServe(engine: BrainEngine, args:
if (cfg?.engine !== 'postgres' || !cfg.database_url) return own('not_postgres');
const sourceId = opts.sourceId ?? 'default';
// 1. Only a managed source has the two-consumer problem; classic sync keeps its own path.
- const [brain] = await engine.executeRaw<{ enabled: boolean }>('SELECT enabled FROM persistence_brain WHERE singleton=1');
- if (!brain?.enabled) return own('not_managed');
+ const { readManagedMode } = await import('../core/persistence/managed-mode.ts');
+ if (!await readManagedMode(engine)) return own('not_managed');
// 2. The owner probe: the B3 heartbeat row, through the database (the persistence socket does not exist on Postgres).
let owner: ConsumerRow | null;
try {
diff --git a/src/core/company-brain/admission.ts b/src/core/company-brain/admission.ts
index 0afddd7192..2f8af7e181 100644
--- a/src/core/company-brain/admission.ts
+++ b/src/core/company-brain/admission.ts
@@ -8,7 +8,7 @@ import { readFix, trustedCliRequired } from '../ops/op-fix.ts';
import { isValidSourceId } from '../source-id.ts';
import { assertNoOverlappingPath } from '../sources-ops.ts';
import { checkApprovedSchemaForEngine } from '../schema-pack/engine-resolution.ts';
-import { getWorktreeBinding, managedPersistenceEnabled } from '../persistence/ownership.ts';
+import { getWorktreeBinding, managedPersistenceEnabled, readPersistenceBrain } from '../persistence/ownership.ts';
import { registerLocalWriter, localHostId, currentVerifiedLocalWriter } from '../persistence/identity.ts';
import { isWriteRequestId } from '../persistence/types.ts';
import { currentSubmissionAuthority } from '../minions/submission-authority.ts';
@@ -177,8 +177,8 @@ export async function checkCompanyBrainDestination(engine: BrainEngine, input: C
assertCompanyBrainCaller(input);
await assertIngestionStorage(engine);
if (!input.plan.ready || !input.plan.revision || !input.plan.schema) throw planNotReady('source_not_ready', 'The inspected source is not ready to connect.', input.path);
- const [brain] = await engine.executeRaw<{ brain_id: string; enabled: boolean }>('SELECT brain_id,enabled FROM persistence_brain WHERE singleton=1');
- if (!brain) throw brainUninitialized('Initialize the selected brain before connecting a source.', input.brainId);
+ // #6482: `assertIngestionStorage` has already proven the table exists; a malformed singleton is `storage_error`, never "unmanaged".
+ const brain = await readPersistenceBrain(engine);
if (newSource && (await engine.executeRaw('SELECT id FROM sources WHERE id=$1', [input.sourceId])).length) {
throw sourceTaken('Connect requires a new source. Resume the existing source through sync.', input);
}
diff --git a/src/core/company-brain/receipts.ts b/src/core/company-brain/receipts.ts
index 26b1dc384e..7d66abd619 100644
--- a/src/core/company-brain/receipts.ts
+++ b/src/core/company-brain/receipts.ts
@@ -1,6 +1,7 @@
import type { BrainEngine } from '../engine.ts';
import { isValidSourceId } from '../source-id.ts';
import { isWriteRequestId } from '../persistence/types.ts';
+import { readManagedMode } from '../persistence/ownership.ts';
import { opError, type OpErrorOpts } from '../ops/contract.ts';
import { readFix } from '../ops/op-fix.ts';
import type { RegistryCode } from '../error-registry.ts';
@@ -116,9 +117,9 @@ function sanitizedDiagnostic(value: unknown): SourceIngestionDiagnostic {
async function lockScope(tx: BrainEngine, input: SourceIngestionScope & { fence: SourceIngestionFence }): Promise<void> {
validateScope(input);
- const [brain] = await tx.executeRaw<{ enabled: boolean }>('SELECT enabled FROM persistence_brain WHERE singleton=1 FOR SHARE');
+ const managed = await readManagedMode(tx, { lock: 'share' });
if (!input.fence || !['managed', 'unmanaged'].includes(input.fence.mode)) fail('receipt_fence_required', 'An explicit ingestion authority fence is required.', internal, { fix: statusFix(input.sourceId) });
- if (brain?.enabled && input.fence.mode !== 'managed') fail('receipt_fence_required', 'Managed ingestion requires its worktree owner and topology fence.',
+ if (managed && input.fence.mode !== 'managed') fail('receipt_fence_required', 'Managed ingestion requires its worktree owner and topology fence.',
`This brain uses managed persistence: run the connect or ${resume(input.sourceId)} on the host that owns source ${input.sourceId}'s worktree, so the ingestion carries its owner fence.`,
{ fix: ownerFix(input.sourceId), docs: RESUME_DOCS });
if (input.fence.mode === 'managed') {
diff --git a/src/core/connectors/item-holds-store.ts b/src/core/connectors/item-holds-store.ts
index f4a07d1585..57c10ff972 100644
--- a/src/core/connectors/item-holds-store.ts
+++ b/src/core/connectors/item-holds-store.ts
@@ -23,6 +23,7 @@ import type { BrainEngine } from '../engine.ts';
import { digest } from '../persistence/digest.ts';
import { connectorCheckpointKey, connectorIdentity, isConnectorSourceKind, type ConnectorKind } from '../persistence/connector-identity.ts';
import { connectorStateKey } from '../persistence/connector-state.ts';
+import { readManagedMode } from '../persistence/managed-mode.ts';
import { heldItems, type ItemHoldRecord } from './item-holds.ts';
export const HOLD_RETRY_OP = 'connector-hold-retry';
@@ -32,9 +33,8 @@ type Exec = Pick<BrainEngine, 'executeRaw'>;
export interface ConnectorSourceRow { id: string; incarnation: string; local_path: string | null; config: Record<string, unknown> }
export async function managedBrain(engine: Exec): Promise<boolean> {
- // A failed mode query propagates: guessing "unmanaged" would read a stale state file and report no holds.
- const [brain] = await engine.executeRaw<{ enabled: boolean }>('SELECT enabled FROM persistence_brain WHERE singleton=1');
- return brain?.enabled === true;
+ // A failed or impossible mode read propagates: guessing "unmanaged" would read a stale state file and report no holds.
+ return readManagedMode(engine);
}
/** The classic-mode state file of a connector source, or null when it has no state directory. */
diff --git a/src/core/error-registry.ts b/src/core/error-registry.ts
index ca91d28e6a..7c0c0f21f6 100644
--- a/src/core/error-registry.ts
+++ b/src/core/error-registry.ts
@@ -401,7 +401,9 @@ export const CODES = {
split_unparseable: { class: 'caller', summary: "Split unparseable." },
stale_unavailable: { class: 'unavailable', summary: "No complete, current authorized shared-skills view is available; cached shared skills stay unused.", docs: 'docs/guides/shared-brain-skills.md#troubleshoot-leave-and-recover' },
state_mismatch: { class: 'caller', summary: "Google connect credential error: state mismatch.", docs: 'docs/guides/google-connect.md#troubleshooting' },
- storage_error: { class: 'server', summary: "Reading or writing durable storage failed." },
+ storage_error: { class: 'server', summary: "Reading or writing durable storage failed.",
+ why: "Usually a dropped connection or a failed statement; the same error after a rerun is not transient. `detail: persistence_mode_unknown` (#6482): the persistence_brain singleton is missing, duplicated or carries a non-boolean `enabled`, so gbrain cannot tell whether the brain is managed and refuses every write, sync, connector run and activation step that depends on it rather than route a managed brain through the unmanaged writer; only a well-formed `enabled: false` row selects the unmanaged path.",
+ suggestion: 'For persistence_mode_unknown: run gbrain sources writer status --probe --json on the brain host (it reports the malformed state instead of refusing), fix the persistence_brain row it names, then gbrain doctor --json.' },
sync_not_applicable: { class: 'caller', summary: "Sync does not apply to this source: its directory is not a Git checkout.", why: "Sync imports changes between Git commits. A gbrain-owned content directory (created by init) holds files gbrain manages itself and is not a Git repository, so there is nothing to sync; gbrain never initializes Git on its own.", reasons: ['content_directory'] },
sync_in_progress: { class: 'retryable', summary: "A sync is running on this source, or a write in flight or the sync's frozen manifest still names the file a repair would write.",
why: "A repair that changed a file the running sync admits later would make that entry refuse on its raw hash, and a file a write in flight names would be written twice; so the one candidate waits while the rest of the source is repaired. `candidate_in_flight`: the file is named; `busy_set_unreadable`: the busy set could not be read, so every candidate waited.",
diff --git a/src/core/mentions/pass.ts b/src/core/mentions/pass.ts
index 6619170683..0711b7771f 100644
--- a/src/core/mentions/pass.ts
+++ b/src/core/mentions/pass.ts
@@ -495,7 +495,7 @@ export async function runMentionPass(engine: BrainEngine, opts: MentionPassOpts
const passStart = new Date().toISOString();
const policy = await readMentionPolicy(engine);
const sources = await sourcesInScope(engine, opts.sourceId);
- const managed = await managedPersistenceEnabled(engine).catch(() => false);
+ const managed = await managedPersistenceEnabled(engine);
if (!policy.enabled) {
const status = new Map((await engine.executeRaw<{ source_id: string; state: string }>(
'SELECT source_id, state FROM mention_index_status WHERE source_id = ANY($1::text[])', [sources])).map(r => [r.source_id, r.state]));
diff --git a/src/core/minions/handlers/facts-absorb.ts b/src/core/minions/handlers/facts-absorb.ts
index 93a6cf8846..f601476aec 100644
--- a/src/core/minions/handlers/facts-absorb.ts
+++ b/src/core/minions/handlers/facts-absorb.ts
@@ -8,6 +8,7 @@ import { loadConfig, loadConfigWithEngine } from '../../config.ts';
import type { FactsBackstopResult } from '../../facts/backstop.ts';
import { JobDeferredError, UnrecoverableError } from '../errors.ts';
import { ERROR_CATALOGUE } from '../../error-catalogue.ts';
+import { readManagedMode } from '../../persistence/managed-mode.ts';
/** Shared predicate: an inline result reporting execution-time unavailability. */
export function factsAbsorbUnavailable(result: FactsBackstopResult): boolean {
@@ -67,8 +68,7 @@ export function makeFactsAbsorbHandler(engine: BrainEngine): MinionHandler {
};
// #5362: before activation the legacy fence writer refuses every file in a claimed
// worktree, so check the source root before any inference is paid for.
- const [brain] = await engine.executeRaw<{ enabled: boolean }>('SELECT enabled FROM persistence_brain WHERE singleton=1');
- if (!brain?.enabled) {
+ if (!await readManagedMode(engine)) {
const [source] = await engine.executeRaw<{ local_path: string | null }>('SELECT local_path FROM sources WHERE id=$1', [sourceId]);
if (source?.local_path) {
const { assertLegacyFilesystemWriter } = await import('../../persistence/filesystem-guard.ts');
diff --git a/src/core/persistence/activation.ts b/src/core/persistence/activation.ts
index ba7ecadf7e..73d4878c59 100644
--- a/src/core/persistence/activation.ts
+++ b/src/core/persistence/activation.ts
@@ -4,7 +4,7 @@ import type { BrainEngine } from '../engine.ts';
import type { Action } from '../agent-output.ts';
import { opError, OperationError } from '../ops/contract.ts';
import { readFix } from '../ops/op-fix.ts';
-import { acquireWorktree, getWorktreeBinding, type WorktreeBinding } from './ownership.ts';
+import { acquireWorktree, getWorktreeBinding, readManagedMode, type WorktreeBinding } from './ownership.ts';
import { localHostId, existingLocalHostId, persistenceHome, registerLocalWriter } from './identity.ts';
import { nativeLockCapability, tryAcquireNativeLock, type NativeLockHandle } from './native-lock.ts';
import { managedFilesystemDatastorePath, refreshManagedFilesystemRoots } from './filesystem-guard.ts';
@@ -118,8 +118,7 @@ export async function activatePersistence(engine: BrainEngine, opts: { confirmQu
{ fix: writerStatusFix('Shows whether managed persistence is now enabled and which owners are active, read-only.') });
}
await probe.release();
- const [brain] = await engine.executeRaw<{ enabled: boolean }>('SELECT enabled FROM persistence_brain WHERE singleton=1');
- if (brain?.enabled && opts.expectedState === undefined) {
+ if (await readManagedMode(engine) && opts.expectedState === undefined) {
const [count] = await engine.executeRaw<{ count: number }>(`SELECT COUNT(*)::integer AS count FROM persistence_source_bindings b
JOIN sources s ON s.id=b.source_id AND s.incarnation=b.source_incarnation WHERE NOT s.archived`);
return { enabled: true, activated: false, filesystem_sources: count.count, native_lock: native, ...ALREADY_ENABLED };
@@ -154,9 +153,9 @@ export async function activatePersistence(engine: BrainEngine, opts: { confirmQu
return await engine.transaction(async tx => {
await tx.executeRaw("SELECT set_config('lock_timeout','2000ms',true),set_config('synchronous_commit','on',true)");
await assertWriterAdminState(tx, opts.expectedState);
- const [current] = await tx.executeRaw<{ enabled: boolean }>('SELECT enabled FROM persistence_brain WHERE singleton=1 FOR UPDATE');
+ const current = await readManagedMode(tx, { lock: 'update' });
await assertWriterAdminUnlocked(tx);
- if (current?.enabled) return { enabled: true, activated: false, filesystem_sources: initial.length, native_lock: native, ...ALREADY_ENABLED };
+ if (current) return { enabled: true, activated: false, filesystem_sources: initial.length, native_lock: native, ...ALREADY_ENABLED };
const currentSources = await configuredSources(tx, true);
const bindings = await validatedBindings(tx, currentSources, hostId, true);
const identity = (rows: WorktreeBinding[]) => JSON.stringify(rows.map(row => [row.source_id,row.source_incarnation,row.worktree_id,row.owner_host_id,
diff --git a/src/core/persistence/administration.ts b/src/core/persistence/administration.ts
index ed328eb4a2..d351b28f9b 100644
--- a/src/core/persistence/administration.ts
+++ b/src/core/persistence/administration.ts
@@ -8,7 +8,8 @@ import { isValidSourceId } from '../source-id.ts';
import { assertValidSlugPrefixes } from '../grants/encoding.ts';
import { isWriteRequestId } from './types.ts';
import { writerDiagnostics } from './control.ts';
-import { acceptWriterTransfer, claimWorktree, getWorktreeBinding, humanManifestProgress, prepareWriterTransfer, storedManifestScope, worktreeManifest, type StoredWorktreeManifest } from './ownership.ts';
+import { acceptWriterTransfer, claimWorktree, getWorktreeBinding, humanManifestProgress, prepareWriterTransfer, readManagedMode, storedManifestScope, worktreeManifest, type StoredWorktreeManifest } from './ownership.ts';
+import { inspectPersistenceBrain } from './managed-mode.ts';
import { existingLocalHostId, currentVerifiedLocalWriter, persistenceHome, readLocalWriter, registerLocalWriter, revokeLocalWriter, type LocalGrant } from './identity.ts';
import type { PersistenceAdminOperation } from './admin-contract.ts';
import { operationScopesAllowed } from '../scope.ts';
@@ -236,9 +237,10 @@ export async function runPersistenceAdministration(engine: BrainEngine, operatio
const writerVersions = await listWriterVersions(engine);
await assertWriterAdminState(engine, adminState, false);
const { cleanupRetiredManagedMarkers } = await import('./deactivation.ts');
- const [mode] = await engine.executeRaw<{ enabled: boolean; mode_epoch: string | null }>(
- "SELECT enabled, to_jsonb(persistence_brain)->>'mode_epoch' AS mode_epoch FROM persistence_brain WHERE singleton=1");
- return { ...diagnostics, mode: mode?.enabled ? 'managed' : 'classic', mode_epoch: Number(mode?.mode_epoch ?? 1),
+ // #6482: a malformed singleton reports `mode: 'unknown'` with its problem (this is the refusal's fix command), never refuses.
+ const mode = await inspectPersistenceBrain(engine);
+ return { ...diagnostics, mode: !mode.row ? 'unknown' : mode.row.enabled ? 'managed' : 'classic', mode_epoch: Number(mode.row?.mode_epoch ?? 1),
+ ...(mode.problem ? { mode_problem: mode.problem } : {}),
local_markers: await cleanupRetiredManagedMarkers(engine),
host_id: existingLocalHostId(), local_host_id: existingLocalHostId(), bindings, admin_state: adminState,
admin_lock: { locked: adminLock.locked, set_at: adminLock.set_at, host_id: adminLock.host_id }, blocking_effects: blockingEffects,
@@ -253,8 +255,7 @@ export async function runPersistenceAdministration(engine: BrainEngine, operatio
keys(params, ['source_id', 'path', 'dry_run', 'admin_intent', 'expected_state']);
const sourceId = source(params.source_id), root = path(params.path);
// #5198: say at claim time what the claim retires, before and after the fact.
- const [brain] = await engine.executeRaw<{ enabled: boolean }>('SELECT enabled FROM persistence_brain WHERE singleton=1');
- const notice = brain?.enabled ? {} : { activation_required: CLAIM_BEFORE_ACTIVATION_NOTICE };
+ const notice = await readManagedMode(engine) ? {} : { activation_required: CLAIM_BEFORE_ACTIVATION_NOTICE };
if (params.dry_run) return { dry_run: true, action: operation, source_id: sourceId, path: root, current: await getWorktreeBinding(engine, sourceId, existingLocalHostId()), ...notice };
const expectedState = await requireWriterAdminIntent(engine, operation, params);
return { claimed: true, binding: await claimWorktree(engine, sourceId, root, undefined, expectedState), ...notice };
diff --git a/src/core/persistence/automatic-sync-policy.ts b/src/core/persistence/automatic-sync-policy.ts
index c4d9143d48..42a56ce32a 100644
--- a/src/core/persistence/automatic-sync-policy.ts
+++ b/src/core/persistence/automatic-sync-policy.ts
@@ -1,8 +1,6 @@
-import { opError } from '../ops/contract.ts';
-import { readFix } from '../ops/op-fix.ts';
import { sourceConfigHasRemoteUrl } from '../sources-load.ts';
import type { SqlEngine } from './model.ts';
-import { getWorktreeBinding } from './ownership.ts';
+import { getWorktreeBinding, readManagedMode } from './ownership.ts';
/**
* Whether an automatic sync (autopilot freshness or per-source fanout) may
@@ -14,15 +12,8 @@ import { getWorktreeBinding } from './ownership.ts';
*/
export async function automaticSyncPull(engine: SqlEngine, source: { id: string; config: unknown }): Promise<boolean> {
if (!sourceConfigHasRemoteUrl(source.config)) return false;
- const rows = await engine.executeRaw<{ enabled: unknown }>('SELECT enabled FROM persistence_brain WHERE singleton=1');
- if (rows.length !== 1 || typeof rows[0]?.enabled !== 'boolean') {
- throw opError('storage_error', 'Automatic sync requires exactly one known boolean persistence state.',
- `Run the read-only probe in fix on the brain host and fix the persistence state it reports; automatic sync of ${source.id} resumes on the next tick.`, {
- why: `The persistence_brain singleton is missing, duplicated or not a boolean, so gbrain cannot tell whether ${source.id} is a managed canonical checkout; automatic sync is not queued rather than risk a Git pull over it.`,
- fix: { ...readFix('Shows the brain\'s persistence mode and each source\'s writer binding without changing anything.',
- { argv: ['gbrain', 'sources', 'writer', 'status', '--probe', '--json'] }), verify: { argv: ['gbrain', 'doctor', '--json'] } },
- });
- }
- if (rows[0].enabled) return false;
+ // #6482: the shared fail-closed predicate (`storage_error` on a missing, duplicated or non-boolean singleton) lives in ownership.ts.
+ if (await readManagedMode(engine, { refusal: { subject: 'Automatic sync',
+ consequence: `automatic sync of ${source.id} is not queued rather than risk a Git pull over it; it resumes on the next tick once the state is repaired` } })) return false;
return await getWorktreeBinding(engine, source.id, null) === null;
}
diff --git a/src/core/persistence/connector-path.ts b/src/core/persistence/connector-path.ts
index a9308b3481..4a8fba8104 100644
--- a/src/core/persistence/connector-path.ts
+++ b/src/core/persistence/connector-path.ts
@@ -3,6 +3,7 @@ import { OperationError } from '../ops/contract.ts';
import { isConnectorSourceKind } from './connector-identity.ts';
import { withCoordinatedWrite } from './context.ts';
import { maintenanceAttribution } from './attribution.ts';
+import { readManagedMode } from './managed-mode.ts';
/**
* `gbrain sources set-path <id> --clear` (#5673): clear a connector source's
@@ -28,9 +29,9 @@ export async function clearConnectorLocalPath(engine: BrainEngine, sourceId: str
`Inspect the binding with gbrain sources writer status ${sourceId}.`);
}
if (source.local_path === null) return { prior: null };
- const [brain] = await tx.executeRaw<{ enabled: boolean }>('SELECT enabled FROM persistence_brain WHERE singleton=1');
+ const managed = await readManagedMode(tx);
const clear = () => tx.executeRaw('UPDATE sources SET local_path=NULL WHERE id=$1 AND incarnation=$2::uuid', [sourceId, source.incarnation]);
- if (brain?.enabled) await withCoordinatedWrite(tx, [sourceId], clear, await maintenanceAttribution(tx));
+ if (managed) await withCoordinatedWrite(tx, [sourceId], clear, await maintenanceAttribution(tx));
else await clear();
return { prior: source.local_path };
});
diff --git a/src/core/persistence/connector-sync.ts b/src/core/persistence/connector-sync.ts
index c92ce3591f..739c4a77b3 100644
--- a/src/core/persistence/connector-sync.ts
+++ b/src/core/persistence/connector-sync.ts
@@ -18,7 +18,7 @@ import { authorizeStoredRequest, authorizeWrite } from './authority.ts';
import { materializeTimeline, prepareCanonicalProjections } from './canonical-projections.ts';
import { digest, sha256 } from './digest.ts';
import { admitWriteInTransaction, assertReplayIntent, getWriteRequest, getWriteRequestById, intentDigest, receiptFor } from './journal.ts';
-import { acquireWorktree, containsPath, getWorktreeBinding, probeWorktreeWriter, type WorktreeBinding } from './ownership.ts';
+import { acquireWorktree, containsPath, getWorktreeBinding, probeWorktreeWriter, readManagedMode, type WorktreeBinding } from './ownership.ts';
import { localHostId } from './identity.ts';
import { assertPersistenceAccepting, startPersistenceConsumer, waitForWrite, writeResponse } from './service.ts';
import { maintenancePublishWaitMs } from './maintenance-wait.ts';
@@ -209,8 +209,7 @@ async function connectorFileTarget(engine: BrainEngine, row: Pick<WriteRequest,
export async function beginConnectorSync(engine: BrainEngine, sourceId: string, connector: ConnectorKind,
suppliedConfig: unknown, opts: SyncOpts & { resetCheckpoint?: boolean }, lease?: ConnectorLease): Promise<ManagedConnectorSync | null> {
- const [brain] = await engine.executeRaw<{ enabled: boolean }>('SELECT enabled FROM persistence_brain WHERE singleton=1');
- if (!brain?.enabled) return null;
+ if (!await readManagedMode(engine)) return null;
assertPersistenceAccepting(engine);
validateManagedSyncOptions(opts);
if (opts.dryRun || opts.skipFailed || opts.srcSubpath || opts.exclude?.length || opts.includeHidden?.length ||
@@ -258,8 +257,7 @@ export async function beginConnectorSync(engine: BrainEngine, sourceId: string,
export async function withConnectorSync<T>(engine: BrainEngine, sourceId: string, connector: ConnectorKind,
config: unknown, opts: SyncOpts & { resetCheckpoint?: boolean }, work: (session: ManagedConnectorSync | null, opts: SyncOpts) => Promise<T>,
onPending?: (result: T | null, session: ManagedConnectorSync) => T): Promise<T> {
- const [brain] = await engine.executeRaw<{ enabled: boolean }>('SELECT enabled FROM persistence_brain WHERE singleton=1');
- if (!brain?.enabled) {
+ if (!await readManagedMode(engine)) {
if (opts.resetCheckpoint) throw new OperationError('invalid_params', '--reset-checkpoint applies to managed connector sources.',
`This brain does not use managed persistence; re-walk this connector with: gbrain sync --source ${sourceId} --full`);
// A preview never opens the autopilot dispatch gate (#5673).
diff --git a/src/core/persistence/context.ts b/src/core/persistence/context.ts
index dbcdd445c4..8c07d12bec 100644
--- a/src/core/persistence/context.ts
+++ b/src/core/persistence/context.ts
@@ -2,6 +2,7 @@ import { AsyncLocalStorage } from 'node:async_hooks';
import type { BrainEngine } from '../engine.ts';
import { opError, OperationError } from '../ops/contract.ts';
import type { WriteAttribution } from './attribution.ts';
+import { readPersistenceBrain } from './managed-mode.ts';
import { isTrustTier, nestWriteTrust, trustRankSql, type TrustTier, type WriteTrust } from '../trust/tier.ts';
import type { TrustTable } from '../trust/schema.ts';
@@ -142,8 +143,8 @@ export function withTrustBackfill<T>(engine: Pick<BrainEngine, 'executeRaw'>, fn
return withTransactionSettings(engine, [TRUST_BACKFILL_SETTING], () => ['on'], fn);
}
export async function assertCoordinatedWrite(engine: Pick<BrainEngine, 'executeRaw'>, sourceId: string): Promise<void> {
- const [brain] = await engine.executeRaw<{ brain_id: string; enabled: boolean }>('SELECT brain_id,enabled FROM persistence_brain WHERE singleton=1');
- if (!brain?.enabled) return;
+ const brain = await readPersistenceBrain(engine);
+ if (!brain.enabled) return;
const held = publication.getStore();
if (!held?.active || held.brainId !== brain.brain_id || !held.sourceIds.has(sourceId)) {
throw new OperationError('writer_coordinator_required', 'This writer must enter the canonical persistence coordinator.',
diff --git a/src/core/persistence/deactivation.ts b/src/core/persistence/deactivation.ts
index 5aeabb242b..1fb7d53496 100644
--- a/src/core/persistence/deactivation.ts
+++ b/src/core/persistence/deactivation.ts
@@ -29,7 +29,7 @@ import type { BrainEngine } from '../engine.ts';
import { configDir } from '../config.ts';
import { opError, OperationError } from '../ops/contract.ts';
import { readFix } from '../ops/op-fix.ts';
-import { acquireWorktree, getWorktreeBinding } from './ownership.ts';
+import { acquireWorktree, getWorktreeBinding, readPersistenceBrain, type PersistenceBrainRow } from './ownership.ts';
import { existingLocalHostId } from './identity.ts';
import type { NativeLockHandle } from './native-lock.ts';
import { assertWriterAdminState } from './admin-intent.ts';
@@ -77,19 +77,11 @@ export interface DeactivationReport {
local_markers?: LocalMarkerReport;
}
-interface BrainRow { brain_id: string; enabled: boolean; mode_epoch: string | number; skill_bundles_enabled: boolean | null; writer_protocol_floor: number | null }
+type BrainRow = PersistenceBrainRow;
-async function readBrain(engine: BrainEngine, lock = false): Promise<BrainRow> {
- const [brain] = await engine.executeRaw<BrainRow>(`SELECT brain_id, enabled, mode_epoch,
- (to_jsonb(persistence_brain)->>'skill_bundles_enabled')::boolean AS skill_bundles_enabled,
- (to_jsonb(persistence_brain)->>'writer_protocol_floor')::int AS writer_protocol_floor
- FROM persistence_brain WHERE singleton=1${lock ? ' FOR UPDATE' : ''}`);
- if (!brain) {
- throw opError('writer_not_initialized', 'Persistence identity is missing.',
- 'This brain has no persistence identity row, so there is no managed mode to read or deactivate. List the pending migrations that create it and ask the user before applying them.',
- { fix: { argv: ['gbrain', 'apply-migrations', '--dry-run', '--json'], consent: [], actor: 'agent', why: 'Lists the pending migrations without applying them.', requires_exclusive: false } });
- }
- return brain;
+/** #6482: the shared fail-closed read; a missing, duplicated or non-boolean singleton refuses `storage_error`. */
+function readBrain(engine: BrainEngine, lock = false): Promise<BrainRow> {
+ return readPersistenceBrain(engine, lock ? { lock: 'update' } : {});
}
/** Every piece of work that keeps the brain from quiescing, with its CLI exit. Read-only. */
@@ -320,9 +312,7 @@ export async function cleanupRetiredManagedMarkers(engine: BrainEngine): Promise
const report: LocalMarkerReport = { state: 'cleared', removed: [], pending: [] };
const [present] = await engine.executeRaw<{ present: boolean }>("SELECT to_regclass('persistence_topology_changes') IS NOT NULL AS present");
if (!present?.present) return report;
- const [brain] = await engine.executeRaw<{ brain_id: string; enabled: boolean; mode_epoch: string | null }>(
- "SELECT brain_id, enabled, to_jsonb(persistence_brain)->>'mode_epoch' AS mode_epoch FROM persistence_brain WHERE singleton=1");
- if (!brain) return report;
+ const brain = await readPersistenceBrain(engine);
const current = Number(brain.mode_epoch ?? 1);
const retired = await readRetired(engine, brain.brain_id);
if (!retired.epochs.size && !retired.worktrees.size) return report;
diff --git a/src/core/persistence/diagnostics.ts b/src/core/persistence/diagnostics.ts
index dee14bda18..d58c9f39f8 100644
--- a/src/core/persistence/diagnostics.ts
+++ b/src/core/persistence/diagnostics.ts
@@ -4,6 +4,7 @@ import type { JournalLimits } from './model.ts';
import { publicationConcurrency } from './pool-capacity.ts';
import { WRITER_INSPECTION_HINT } from './admin-intent.ts';
import { writeHealth } from './health.ts';
+import { inspectPersistenceBrain } from './managed-mode.ts';
import { claimStall, claimStateOf, isOwnerThisProcess, sqlLabel, type ClaimRow, type ClaimState, type ClaimStall } from './claim-phase.ts';
import { cliRenderContext, renderAction, type Action, type RenderedAction } from '../agent-output.ts';
import { enginePoolStats } from '../postgres-engine/pool-stats.ts';
@@ -134,7 +135,9 @@ export function capacityDiagnostics(counters: Counter[], limits: JournalLimits)
}
/** Trusted-admin counts only: neither normalized intent nor private paths leave here. */
export async function readWriterDiagnostics(engine: BrainEngine) {
- const [brain] = await engine.executeRaw<{ enabled: boolean; brain_id: string }>('SELECT enabled,brain_id FROM persistence_brain WHERE singleton=1');
+ // #6482: writer status is the probe the mode refusal names, so a malformed singleton is reported here, never refused.
+ const inspected = await inspectPersistenceBrain(engine);
+ const brain = inspected.row ? { enabled: inspected.row.enabled, brain_id: inspected.row.brain_id } : { enabled: false, brain_id: null, persistence_mode_problem: inspected.problem };
const worktrees = await engine.executeRaw(`SELECT w.id,w.owner_host_id,w.owner_epoch::text AS owner_epoch,w.topology_generation::text AS topology_generation,w.state,w.heartbeat_at,
COUNT(r.id) FILTER (WHERE r.state='queued')::integer AS queued,
COUNT(r.id) FILTER (WHERE r.state='running')::integer AS running,
diff --git a/src/core/persistence/effect-facts.ts b/src/core/persistence/effect-facts.ts
index 429b35e558..46d7e6d362 100644
--- a/src/core/persistence/effect-facts.ts
+++ b/src/core/persistence/effect-facts.ts
@@ -8,6 +8,7 @@ import type { MinionJobStatus } from '../minions/types.ts';
import type { PageSnapshot } from '../page-state/types.ts';
import { OperationError, opError } from '../ops/contract.ts';
import { readFix } from '../ops/op-fix.ts';
+import { readManagedMode } from './managed-mode.ts';
import { authorizeStoredRequest, authorizeWrite } from './authority.ts';
import { completeEffect } from './effect-journal.ts';
import { guardEffectSource } from './effect-recovery.ts';
@@ -101,8 +102,7 @@ export async function prepareFactsBackstop(engine: BrainEngine, row: WriteReques
export async function readFactsBackstopJobPage(engine: BrainEngine, data: Record<string, unknown>) {
const slug = typeof data.slug === 'string' ? data.slug : '';
const sourceId = typeof data.sourceId === 'string' ? data.sourceId : 'default';
- const [brain] = await engine.executeRaw<{ enabled: boolean }>('SELECT enabled FROM persistence_brain WHERE singleton=1');
- if (brain?.enabled && data.persistence_request_id === undefined) return { skipped: 'missing_write_authority' } as const;
+ if (await readManagedMode(engine) && data.persistence_request_id === undefined) return { skipped: 'missing_write_authority' } as const;
const snapshot = await engine.readPageSnapshot(slug, { sourceId });
if (!snapshot) return { skipped: 'page_missing' } as const;
if (data.persistence_request_id !== undefined) {
diff --git a/src/core/persistence/engine-graduation.ts b/src/core/persistence/engine-graduation.ts
index ed035bb95f..5b4e68e23d 100644
--- a/src/core/persistence/engine-graduation.ts
+++ b/src/core/persistence/engine-graduation.ts
@@ -27,6 +27,7 @@ import { liveServeOwner } from '../exclusive-fix.ts';
import { opError, type OperationError } from '../ops/contract.ts';
import { acquireKernelLockOnly, inspectLockHolder, PgliteBusyError, peekLock, releaseLock, type LockHandle } from '../pglite-lock.ts';
import { localHostId } from './identity.ts';
+import { readManagedMode } from './managed-mode.ts';
import { quiesceAutopilot } from '../../commands/migrate-engine.ts';
import { LATEST_VERSION } from '../migrate.ts';
import {
@@ -882,8 +883,7 @@ async function stepVerify(run: Run): Promise<void> {
runId: run.m.runId, expectFence: true,
runDoctor: async () => {
phase(run, 'doctor');
- const [brain] = await run.source!.executeRaw<{ enabled: boolean }>('SELECT enabled FROM persistence_brain WHERE singleton = 1');
- const doctor = await run.deps.runTargetDoctor(run.m.runId, run.m.targetUrls!.main, brain?.enabled === true);
+ const doctor = await run.deps.runTargetDoctor(run.m.runId, run.m.targetUrls!.main, await readManagedMode(run.source!));
exempted = doctor.exempted;
return doctor.failing;
},
@@ -905,11 +905,11 @@ async function stepVerify(run: Run): Promise<void> {
async function stepCutover(run: Run): Promise<void> {
phase(run, 'cutover');
await run.deps.copySequences({ source: run.source!, target: run.main! }, { runId: run.m.runId });
- const [brain] = await run.source!.executeRaw<{ enabled: boolean }>('SELECT enabled FROM persistence_brain WHERE singleton = 1');
+ const sourceEnabled = await readManagedMode(run.source!);
const [seq] = await run.source!.executeRaw<{ s: string }>('SELECT COALESCE(max(sequence), 0)::text AS s FROM persistence_requests');
const row = await readGraduationRow(run.source!);
if (row?.state !== 'cutover') await withSourceWritable(run.source!, tx => setSourceState(tx, run.m.runId, 'cutover', { cutoverSequence: seq?.s ?? '0' }));
- if (run.m.state !== 'cutover') advance(run, 'cutover', { sourceEnabled: brain?.enabled === true, cutoverSequence: seq?.s ?? '0' });
+ if (run.m.state !== 'cutover') advance(run, 'cutover', { sourceEnabled, cutoverSequence: seq?.s ?? '0' });
await boundary(run, 'source_cutover');
const source = run.source!;
run.lock = await source.closeRetainingLock();
diff --git a/src/core/persistence/filesystem-guard.ts b/src/core/persistence/filesystem-guard.ts
index d5cfc69333..86f0636ec9 100644
--- a/src/core/persistence/filesystem-guard.ts
+++ b/src/core/persistence/filesystem-guard.ts
@@ -3,6 +3,7 @@ import { AsyncLocalStorage } from 'node:async_hooks';
import { isAbsolute, relative, resolve, sep } from 'node:path';
import { OperationError } from '../ops/contract.ts';
import type { SqlEngine } from './model.ts';
+import { readPersistenceBrain } from './managed-mode.ts';
import { canonicalFilesystemPath, managedRootMarkerFor, recordManagedRoots, registeredManagedRootRecords, type ManagedRootRecord } from './root-registry.ts';
interface FileCapability { roots: string[]; active: boolean; }
@@ -23,9 +24,7 @@ function encloses(root: string, path: string): boolean {
}
export async function refreshManagedFilesystemRoots(engine: SqlEngine, databasePath = datastorePaths.get(engine), signal?: AbortSignal): Promise<void> {
// Mode and epoch come from one snapshot, so roots are never recorded under the epoch of a concurrent deactivation.
- const [brain] = await engine.executeRaw<{ brain_id: string; enabled: boolean; mode_epoch: string | null }>(
- "SELECT brain_id,enabled,to_jsonb(persistence_brain)->>'mode_epoch' AS mode_epoch FROM persistence_brain WHERE singleton=1", undefined, { signal });
- if (!brain) return;
+ const brain = await readPersistenceBrain(engine, { signal });
const roots = brain.enabled ? await engine.executeRaw<ManagedRootRecord>(`SELECT DISTINCT ON (local_path) * FROM (
SELECT h.local_path,s.source_id,s.source_incarnation,s.worktree_id,s.topology_generation
FROM persistence_host_bindings h JOIN persistence_source_bindings s ON s.worktree_id=h.worktree_id WHERE h.host_id=$1::uuid
diff --git a/src/core/persistence/graduation-verify.ts b/src/core/persistence/graduation-verify.ts
index 80956d3fea..b517e2deac 100644
--- a/src/core/persistence/graduation-verify.ts
+++ b/src/core/persistence/graduation-verify.ts
@@ -10,6 +10,7 @@ import type { BrainEngine } from '../engine.ts';
import { OperationError } from '../ops/contract.ts';
import { admitWriteInTransaction, type WriteAdmission } from './journal.ts';
import type { Principal, WriteAuthority } from './model.ts';
+import { readManagedMode } from './managed-mode.ts';
import type {
GraduationEngines, Inventory, InventoryEntry, ReplayProbeResult, TableReceipt, VerifyFailure, VerifyResult,
} from './engine-graduation.types.ts';
@@ -271,8 +272,7 @@ async function chooseReplay(e: GraduationEngines, ctx: VerifyContext): Promise<R
if (!ctx.replayCallerIntent) return { status: 'not_available', reason: 'no_caller_input' };
requestId = newest.request_id;
}
- const [brain] = await e.source.executeRaw<{ enabled: unknown }>('SELECT enabled FROM persistence_brain WHERE singleton=1');
- const sourceEnabled = brain ? brain.enabled === true || brain.enabled === 't' : undefined;
+ const sourceEnabled = await readManagedMode(e.source);
return replayProbe(e.target, requestId, ctx.replayCallerIntent, { sourceEnabled, runId: ctx.runId });
}
diff --git a/src/core/persistence/maintenance.ts b/src/core/persistence/maintenance.ts
index 3a46050892..879bdbe606 100644
--- a/src/core/persistence/maintenance.ts
+++ b/src/core/persistence/maintenance.ts
@@ -6,6 +6,7 @@ import { assertManagedFilesystemWrite } from './filesystem-guard.ts';
import { opError } from '../ops/contract.ts';
import type { Action } from '../agent-output.ts';
import type { SqlEngine } from './model.ts';
+import { readManagedMode } from './ownership.ts';
import { DEFAULT_TARGET_URL_ENV, planArgv } from './graduation-errors.ts';
// Every facts-family bulk writer now publishes through the coordinator on a
@@ -53,8 +54,7 @@ function engineMigrationFix(m: EngineMigrationSide, why: string): Action {
/** Refuse unsupported multi-stage writers before providers, files or git change. */
export async function assertUnmanagedCanonicalWriter(engine: SqlEngine, operation: string, opts: { migration?: EngineMigrationSide } = {}): Promise<void> {
- const rows = await engine.executeRaw<{ enabled: boolean }>('SELECT enabled FROM persistence_brain WHERE singleton=1');
- if (!rows?.[0]?.enabled) return;
+ if (!await readManagedMode(engine)) return;
const message = `${operation} cannot mutate a managed brain through the legacy writer.`;
const why = 'This brain is managed: every write goes through its writer coordinator, which the legacy writer bypasses.';
if (opts.migration) {
diff --git a/src/core/persistence/managed-mode.ts b/src/core/persistence/managed-mode.ts
new file mode 100644
index 0000000000..620b4b5f89
--- /dev/null
+++ b/src/core/persistence/managed-mode.ts
@@ -0,0 +1,69 @@
+/**
+ * #6482: the one managed-mode reader. The schema seeds exactly one `persistence_brain` row with a boolean
+ * `enabled` (`schema.ts`), so a read that returns anything else is an impossible state, not a mode: every
+ * reader refuses `storage_error` instead of treating the brain as unmanaged. A leaf module so that
+ * `filesystem-guard.ts` and the other modules `ownership.ts` imports can use it without a cycle;
+ * `ownership.ts` re-exports it.
+ */
+import { OperationError, opError } from '../ops/contract.ts';
+import { readFix } from '../ops/op-fix.ts';
+import type { SqlEngine } from './model.ts';
+
+/** The plain statement. `group-publish.ts` memoizes this exact text for a group's preparation, so every plain reader sends it unchanged. */
+export const MANAGED_MODE_SQL = 'SELECT enabled FROM persistence_brain WHERE singleton=1';
+/** The columns the metadata-bearing mode readers need; the later-migration columns through `to_jsonb` so an older row still answers. */
+const PERSISTENCE_BRAIN_SQL = `SELECT brain_id,enabled,to_jsonb(persistence_brain)->>'mode_epoch' AS mode_epoch,
+ (to_jsonb(persistence_brain)->>'skill_bundles_enabled')::boolean AS skill_bundles_enabled,
+ (to_jsonb(persistence_brain)->>'writer_protocol_floor')::int AS writer_protocol_floor FROM persistence_brain WHERE singleton=1`;
+export interface ManagedModeReadOptions {
+ /** `share` / `update` append `FOR SHARE` / `FOR UPDATE`: callers that serialize on the singleton keep their lock. */
+ lock?: 'share' | 'update';
+ signal?: AbortSignal;
+ /** Names the caller in the refusal (`<subject> requires exactly one known boolean persistence state.`) and what it did not do. */
+ refusal?: ManagedModeRefusalContext;
+}
+export interface ManagedModeRefusalContext { subject?: string; consequence?: string }
+export interface PersistenceBrainRow { brain_id: string; enabled: boolean; mode_epoch: string | null; skill_bundles_enabled: boolean | null; writer_protocol_floor: number | null }
+/**
+ * The persistence state the schema seeds (`schema.ts`: one row, `enabled` boolean NOT NULL). Anything else is an
+ * impossible read, not a mode: refusing is the only answer that cannot route a managed brain through the
+ * unmanaged writer (#6482). Shared by every mode reader; the message and fix are `automaticSyncPull`'s.
+ */
+export function unknownManagedModeRefusal(rows: ReadonlyArray<unknown>, context: ManagedModeRefusalContext = {}): OperationError {
+ const shape = rows.length === 0 ? 'missing' : rows.length > 1 ? 'duplicated' : 'not a boolean';
+ return opError('storage_error', `${context.subject ?? 'This operation'} requires exactly one known boolean persistence state.`,
+ 'Run the read-only probe in fix on the brain host and fix the persistence state it reports, then run the same command again; nothing was written.', {
+ why: `The persistence_brain singleton is ${shape} (${rows.length} row(s)), so gbrain cannot tell whether this brain is managed; `
+ + `${context.consequence ?? 'it refuses rather than route a managed brain through the unmanaged writer'}.`,
+ detail: 'persistence_mode_unknown',
+ fix: { ...readFix('Shows the brain\'s persistence mode and each source\'s writer binding without changing anything.',
+ { argv: ['gbrain', 'sources', 'writer', 'status', '--probe', '--json'] }), verify: { argv: ['gbrain', 'doctor', '--json'] } },
+ });
+}
+/** `enabled` of the one well-formed row, or the refusal above. Only a literal `false` selects unmanaged behaviour. */
+export function managedModeFromRows<T extends { enabled: unknown }>(rows: ReadonlyArray<T | null | undefined>, context?: ManagedModeRefusalContext): T & { enabled: boolean } {
+ const [row] = rows;
+ if (rows.length !== 1 || !row || typeof row.enabled !== 'boolean') throw unknownManagedModeRefusal(rows, context);
+ return row as T & { enabled: boolean };
+}
+/** Whether the brain is managed: `true` or `false` from a well-formed singleton, `storage_error` otherwise; a query error propagates. */
+export async function readManagedMode(engine: SqlEngine, opts: ManagedModeReadOptions = {}): Promise<boolean> {
+ const sql = opts.lock ? `${MANAGED_MODE_SQL} FOR ${opts.lock.toUpperCase()}` : MANAGED_MODE_SQL;
+ const rows = await engine.executeRaw<{ enabled: unknown }>(sql, undefined, opts.signal ? { signal: opts.signal } : undefined);
+ return managedModeFromRows(rows, opts.refusal).enabled;
+}
+/**
+ * Read-only inspection for the diagnostics that *report* the persistence state (`writer status`, the fix the refusal
+ * names; doctor): the well-formed row, or null with the reason the strict readers refuse. Never used to route a write.
+ */
+export async function inspectPersistenceBrain(engine: SqlEngine): Promise<{ row: PersistenceBrainRow | null; problem: string | null }> {
+ const rows = await engine.executeRaw<Omit<PersistenceBrainRow, 'enabled'> & { enabled: unknown }>(PERSISTENCE_BRAIN_SQL);
+ try { return { row: managedModeFromRows(rows), problem: null }; }
+ catch (error) { return { row: null, problem: (error as { why?: string }).why ?? String(error) }; }
+}
+/** The singleton with its identity and epoch, under the same contract as `readManagedMode`. */
+export async function readPersistenceBrain(engine: SqlEngine, opts: ManagedModeReadOptions = {}): Promise<PersistenceBrainRow> {
+ const sql = opts.lock ? `${PERSISTENCE_BRAIN_SQL} FOR ${opts.lock.toUpperCase()}` : PERSISTENCE_BRAIN_SQL;
+ const rows = await engine.executeRaw<Omit<PersistenceBrainRow, 'enabled'> & { enabled: unknown }>(sql, undefined, opts.signal ? { signal: opts.signal } : undefined);
+ return managedModeFromRows(rows, opts.refusal);
+}
diff --git a/src/core/persistence/onboarding.ts b/src/core/persistence/onboarding.ts
index 66a2f25b36..2d6971a286 100644
--- a/src/core/persistence/onboarding.ts
+++ b/src/core/persistence/onboarding.ts
@@ -2,7 +2,7 @@ import { existsSync, readFileSync } from 'node:fs';
import { dirname, join } from 'node:path';
import type { BrainEngine } from '../engine.ts';
import { existingLocalHostId, persistenceHome } from './identity.ts';
-import { containsPath, getWorktreeBinding } from './ownership.ts';
+import { containsPath, getWorktreeBinding, readManagedMode } from './ownership.ts';
import { assertPhysicalRoot } from './physical-root.ts';
import { inspectLegacyWriterLocks } from './legacy-locks.ts';
import { UNSUPPORTED_MANAGED_BULK_WRITERS } from './maintenance.ts';
@@ -26,7 +26,7 @@ export function containerPathPreflight(paths: Record<string, string>, mountinfo?
}
export async function writerOnboardingPreflight(engine: BrainEngine, sourceId?: string) {
- const [brain] = await engine.executeRaw<{ enabled: boolean }>('SELECT enabled FROM persistence_brain WHERE singleton=1');
+ const managed = await readManagedMode(engine);
const rows = await engine.executeRaw<{ id: string; local_path: string | null; incarnation: string; kind: string | null }>(
"SELECT id,local_path,incarnation,config->>'kind' AS kind FROM sources WHERE NOT archived AND ($1::text IS NULL OR id=$1) ORDER BY id", [sourceId ?? null]);
const fallback = await engine.getConfig('sync.repo_path'), host = existingLocalHostId();
@@ -35,7 +35,7 @@ export async function writerOnboardingPreflight(engine: BrainEngine, sourceId?:
for (const row of rows) {
const binding = await getWorktreeBinding(engine, row.id, host), configured = row.local_path || (row.id === 'default' ? fallback : null);
const connector = isConnectorSourceKind(row.kind);
- let state = !binding ? connector ? 'connector_database' : configured && writeThrough ? 'claim_required' : 'database_only' : !brain.enabled ? 'activation_required' : 'ready';
+ let state = !binding ? connector ? 'connector_database' : configured && writeThrough ? 'claim_required' : 'database_only' : !managed ? 'activation_required' : 'ready';
let physicalError: string | undefined;
if (binding && (binding.source_incarnation !== row.incarnation || binding.state !== 'active')) state = 'recovery_required';
if (binding && binding.owner_host_id !== host) state = 'owner_host_required';
diff --git a/src/core/persistence/ownership.ts b/src/core/persistence/ownership.ts
index 194311f9a1..4e2f1c1c5d 100644
--- a/src/core/persistence/ownership.ts
+++ b/src/core/persistence/ownership.ts
@@ -5,6 +5,7 @@ import { pipelined } from '../page-state/transactions.ts';
import type { BrainEngine } from '../engine.ts';
import { OperationError, opError } from '../ops/contract.ts';
import { readFix } from '../ops/op-fix.ts';
+import { readManagedMode } from './managed-mode.ts';
import type { Action } from '../agent-output.ts';
import { discoverGitRoot } from '../sync-git.ts';
import { cliOptsToProgressOptions, getCliOptions } from '../cli-options.ts';
@@ -46,9 +47,10 @@ export function containsPath(root: string, path: string): boolean {
const rel = relative(root, path);
return !isAbsolute(rel) && rel !== '..' && !rel.startsWith(`..${sep}`);
}
+export { MANAGED_MODE_SQL, managedModeFromRows, readManagedMode, readPersistenceBrain, unknownManagedModeRefusal,
+ type ManagedModeReadOptions, type ManagedModeRefusalContext, type PersistenceBrainRow } from './managed-mode.ts';
export async function managedPersistenceEnabled(engine: SqlEngine): Promise<boolean> {
- const [row] = await engine.executeRaw<{ enabled: boolean }>('SELECT enabled FROM persistence_brain WHERE singleton=1');
- return row?.enabled === true;
+ return readManagedMode(engine);
}
/**
* #6331: the verify-step doctor of an engine graduation runs on the fenced target before cutover sets
diff --git a/src/core/persistence/pre-activation-release.ts b/src/core/persistence/pre-activation-release.ts
index d365085148..629849eb56 100644
--- a/src/core/persistence/pre-activation-release.ts
+++ b/src/core/persistence/pre-activation-release.ts
@@ -17,7 +17,7 @@ import { randomUUID } from 'node:crypto';
import type { BrainEngine } from '../engine.ts';
import { opError, OperationError } from '../ops/contract.ts';
import { readFix } from '../ops/op-fix.ts';
-import { acquireWorktree, getWorktreeBinding } from './ownership.ts';
+import { acquireWorktree, getWorktreeBinding, readPersistenceBrain } from './ownership.ts';
import { currentVerifiedLocalWriter, existingLocalHostId, registerLocalWriter } from './identity.ts';
import type { NativeLockHandle } from './native-lock.ts';
import { assertWriterAdminState } from './admin-intent.ts';
@@ -70,10 +70,10 @@ export async function releasePreActivationClaims(engine: BrainEngine, opts: { ex
}
return await engine.transaction(async tx => {
await tx.executeRaw("SELECT set_config('lock_timeout','5000ms',true),set_config('synchronous_commit','on',true)");
- const [brain] = await tx.executeRaw<{ brain_id: string; enabled: boolean; mode_epoch: string }>('SELECT brain_id, enabled, mode_epoch::text FROM persistence_brain WHERE singleton=1 FOR UPDATE');
+ const brain = await readPersistenceBrain(tx, { lock: 'update' });
await assertWriterAdminState(tx, opts.expectedState);
await assertWriterAdminUnlocked(tx);
- if (!brain || brain.enabled) throw opError('writer_admin_state_changed', 'Managed persistence was activated concurrently; no claim was released.',
+ if (brain.enabled) throw opError('writer_admin_state_changed', 'Managed persistence was activated concurrently; no claim was released.',
'Another process activated managed persistence while this release ran, so the claims now belong to the managed writer. Review the brain-wide deactivation preview before deciding anything else.',
{ fix: readFix('Previews the brain-wide deactivation and its blockers; changes nothing.', { argv: ['gbrain', 'sources', 'writer', 'deactivate', '--dry-run', '--json'] }) });
await tx.executeRaw('SELECT id FROM persistence_worktrees ORDER BY id FOR UPDATE');
diff --git a/src/core/persistence/protocol.ts b/src/core/persistence/protocol.ts
index 5398564648..4280a20e32 100644
--- a/src/core/persistence/protocol.ts
+++ b/src/core/persistence/protocol.ts
@@ -1,5 +1,6 @@
import type { SqlEngine, WriteRequest } from './model.ts';
import { opError, OperationError } from '../ops/contract.ts';
+import { readPersistenceBrain } from './managed-mode.ts';
const declared = new WeakSet<object>();
/**
@@ -49,9 +50,8 @@ export function assertMutationProtocol(row: Pick<WriteRequest, 'target_kind' | '
}
export async function assertSharedSkillPersistence(engine: SqlEngine, sourceId?: string): Promise<void> {
- const [brain] = await engine.executeRaw<{ enabled: boolean; skill_bundles_enabled: boolean; writer_protocol_floor: number }>(
- 'SELECT enabled,skill_bundles_enabled,writer_protocol_floor FROM persistence_brain WHERE singleton=1');
- if (!brain?.enabled || !brain.skill_bundles_enabled || brain.writer_protocol_floor !== 2) {
+ const brain = await readPersistenceBrain(engine);
+ if (!brain.enabled || !brain.skill_bundles_enabled || brain.writer_protocol_floor !== 2) {
throw new OperationError('writer_not_quiesced', 'Shared skill publication requires an activated protocol-2 canonical owner.',
'Stop older writers and direct-file skill servers, then activate shared skill persistence on the canonical host.');
}
diff --git a/src/core/persistence/sync-administration.ts b/src/core/persistence/sync-administration.ts
index 3bd0d2d573..87feddbabd 100644
--- a/src/core/persistence/sync-administration.ts
+++ b/src/core/persistence/sync-administration.ts
@@ -6,6 +6,7 @@ import { submissionAuthority } from './authority.ts';
import type { OperationContext } from '../ops/contract.ts';
import { validateSyncWireParams } from './sync-wire.ts';
import { explicitSyncProcessing } from './sync-authority.ts';
+import { readManagedMode } from './managed-mode.ts';
import { trustedCliRequired } from '../ops/op-fix.ts';
/** Private CLI transport: wire fields can never manufacture a trust lane. */
@@ -26,8 +27,7 @@ export async function runAuthenticatedSyncSlice(engine: BrainEngine, params: Rec
const unregister=engine.registerBeforeDisconnect(async()=>{controller.abort();await work?.catch(()=>{});});
try {
work=(async()=>{
- const [brain]=await engine.executeRaw<{enabled:boolean}>('SELECT enabled FROM persistence_brain WHERE singleton=1');
- if(!brain?.enabled) {
+ if(!await readManagedMode(engine)) {
const {performSync}=await import('../../commands/sync.ts');
// Delegation bypasses runSync's inline embedding cost/config gate.
// Preserve import-only publication; the owner drains accepted embeds.
diff --git a/src/core/persistence/sync-authority.ts b/src/core/persistence/sync-authority.ts
index 6d3cfa76ae..3474207341 100644
--- a/src/core/persistence/sync-authority.ts
+++ b/src/core/persistence/sync-authority.ts
@@ -11,6 +11,7 @@ import { throwIfAborted } from '../abort-check.ts';
import { authorizePageVisibility } from './page-visibility.ts';
import { submissionAuthority, authorizeWrite } from './authority.ts';
import { currentVerifiedLocalWriter, registerLocalWriter } from './identity.ts';
+import { readManagedMode } from './managed-mode.ts';
import type { WriteAuthority } from './model.ts';
import { writerAdminState } from './admin-intent.ts';
@@ -44,9 +45,9 @@ export function assertSyncDispatchActive(): void {
throwIfAborted(currentJobSignal());
}
export async function resolveSyncPersistenceMode(engine: BrainEngine, opts: SyncOpts): Promise<boolean> {
- const [brain] = await engine.executeRaw<{ enabled: boolean }>('SELECT enabled FROM persistence_brain WHERE singleton=1');
+ const managed = await readManagedMode(engine);
assertSyncDispatchActive();
- if (brain?.enabled || opts.signal?.aborted) return brain?.enabled === true;
+ if (managed || opts.signal?.aborted) return managed;
const [source] = await engine.executeRaw<{ claimed: boolean }>(`SELECT
EXISTS(SELECT 1 FROM persistence_source_bindings WHERE source_id=s.id AND source_incarnation=s.incarnation) AS claimed
FROM sources s WHERE s.id=$1`, [opts.sourceId ?? 'default']);
@@ -71,8 +72,7 @@ async function preActivationClaimRefusal(engine: BrainEngine, sourceId: string):
verify: { argv: ['gbrain', 'sources', 'status', sourceId, '--json'] }, docs: 'docs/architecture/topologies.md#deactivate-runbook' } });
}
export async function assertManagedSyncActive(engine: BrainEngine, lock = false): Promise<void> {
- const [brain] = await engine.executeRaw<{ enabled: boolean }>(`SELECT enabled FROM persistence_brain WHERE singleton=1${lock ? ' FOR SHARE' : ''}`);
- if (!brain?.enabled) throw new OperationError('writer_coordinator_required', 'Sync cannot publish through an inactive persistence coordinator.',
+ if (!await readManagedMode(engine, lock ? { lock: 'share' } : {})) throw new OperationError('writer_coordinator_required', 'Sync cannot publish through an inactive persistence coordinator.',
'Stop older writers and review gbrain sources writer status, then explicitly activate persistence before retrying. Claiming a source alone does not exclude running legacy writers.');
}
export async function managedSyncAuthority(engine: BrainEngine, sourceId: string, incarnation: string, repoPath: string): Promise<SyncAuthority> {
diff --git a/src/core/serve-sync-runner.ts b/src/core/serve-sync-runner.ts
index d80fe8b124..7d421e9ef9 100644
--- a/src/core/serve-sync-runner.ts
+++ b/src/core/serve-sync-runner.ts
@@ -57,6 +57,7 @@
import { randomUUID } from 'node:crypto';
import { withLegacySyncDelegation } from './persistence/sync-authority.ts';
import { verifyLocalWriter, withVerifiedLocalRegistration } from './persistence/identity.ts';
+import { readManagedMode } from './persistence/managed-mode.ts';
import { OperationError } from './ops/contract.ts';
import { trustedCliRequired } from './ops/op-fix.ts';
import { withHumanLineSink } from './console-prefix.ts';
@@ -329,8 +330,7 @@ async function startVerifiedDelegatedSync(
await withVerifiedLocalRegistration(engine, registration, () => withHumanLineSink(push, async () => {
const { performSync } = await import('../commands/sync.ts');
const sourceId = await resolveJobSource(engine, job);
- const [brain] = await engine.executeRaw<{ enabled: boolean }>('SELECT enabled FROM persistence_brain WHERE singleton=1');
- const managed = brain?.enabled === true;
+ const managed = await readManagedMode(engine);
log(
`start job=${job.id} source=${sourceId ?? 'default'} writer=${verified.principal.id} managed=${managed} ` +
`opts=${JSON.stringify({ ...options, timeoutSeconds: undefined })} deadline=${options.timeoutSeconds}s`,
diff --git a/src/core/shared-skills/migration.ts b/src/core/shared-skills/migration.ts
index 520d4c06db..8821ab0a8c 100644
--- a/src/core/shared-skills/migration.ts
+++ b/src/core/shared-skills/migration.ts
@@ -4,7 +4,7 @@ import { join, resolve } from 'node:path';
import { isThinClient } from '../config.ts';
import { opError, OperationError, type OperationContext } from '../ops/contract.ts';
import { readFix } from '../ops/op-fix.ts';
-import { getWorktreeBinding } from '../persistence/ownership.ts';
+import { getWorktreeBinding, readPersistenceBrain } from '../persistence/ownership.ts';
import { checkedContentRoot, inventorySkillpack, sameInventory, type PackInventory } from './setup-files.ts';
import { contentSetupKey, installPackagedSharedSkills, setupSharedBrainContent, type SharedContentReceipt } from './setup.ts';
import type { DatabaseContentExportReceipt } from './migration-export.ts';
@@ -97,13 +97,8 @@ export async function runSharedSkillsMigration(ctx: OperationContext, options: {
report.pending_actions.push('Canonical-content migration belongs on the host. Reconnect this client after upgrading its adapter; no host repository or local grants were created.');
return report;
}
- const [brain] = await ctx.engine.executeRaw<{ brain_id: string; enabled: boolean; skill_bundles_enabled: boolean }>(
- 'SELECT brain_id,enabled,skill_bundles_enabled FROM persistence_brain WHERE singleton=1');
- if (!brain) {
- throw opError('writer_not_initialized', 'Apply the shared-skills schema before migrating content.',
- 'This brain has no persistence identity yet, so the shared-skills schema is not applied. Preview the pending migrations with the command in fix, then apply them.',
- { fix: readFix('Lists the pending schema migrations without applying them.', { argv: ['gbrain', 'apply-migrations', '--dry-run', '--json'] }) });
- }
+ // #6482: the shared fail-closed read; a missing singleton is `storage_error` with the writer-status probe, never "unmanaged".
+ const brain = await readPersistenceBrain(ctx.engine);
report.brain_id = brain.brain_id;
const publication = await legacyPublication(ctx);
const limits = await readInventoryLimits(ctx.engine);
diff --git a/src/core/shared-skills/setup.ts b/src/core/shared-skills/setup.ts
index 7e38f96404..80f19c5cbe 100644
--- a/src/core/shared-skills/setup.ts
+++ b/src/core/shared-skills/setup.ts
@@ -4,7 +4,7 @@ import { spawnSync } from 'node:child_process';
import { gbrainPath, isThinClient } from '../config.ts';
import { opError, type OperationContext } from '../ops/contract.ts';
import { readFix } from '../ops/op-fix.ts';
-import { claimWorktree, getWorktreeBinding } from '../persistence/ownership.ts';
+import { claimWorktree, getWorktreeBinding, readPersistenceBrain } from '../persistence/ownership.ts';
import { activateSharedSkillPersistence } from '../persistence/skill-activation.ts';
import { checkedContentRoot } from './setup-files.ts';
import { DEFAULT_SHARED_PACK_ID, packagedSharedSkillPolicy, packagedSharedSkills } from './setup-bundle.ts';
@@ -65,12 +65,12 @@ export async function setupSharedBrainContent(ctx: OperationContext, options: Sh
return receipt;
}
const sourceId = options.sourceId ?? ctx.sourceId;
- const [brain] = await ctx.engine.executeRaw<{ brain_id: string; enabled: boolean; skill_bundles_enabled: boolean }>('SELECT brain_id,enabled,skill_bundles_enabled FROM persistence_brain WHERE singleton=1');
+ const brain = await readPersistenceBrain(ctx.engine);
const [source] = await ctx.engine.executeRaw<{ id: string; incarnation: string; local_path: string | null }>(
'SELECT id,incarnation,local_path FROM sources WHERE id=$1 AND NOT archived', [sourceId]);
- if (!brain || !source) {
- throw opError('source_changed', 'Content setup requires the persistent brain identity and an active selected source.',
- `Source ${sourceId} is archived or not registered, or this brain has no persistence identity yet. Check the registered sources, then run gbrain init again for an active one.`,
+ if (!source) {
+ throw opError('source_changed', 'Content setup requires an active selected source.',
+ `Source ${sourceId} is archived or not registered. Check the registered sources, then run gbrain init again for an active one.`,
{ fix: readFix('Lists the registered sources and whether each is archived.', { argv: ['gbrain', 'sources', 'list', '--json'] }) });
}
receipt.brain_id = brain.brain_id;
diff --git a/src/core/trust/backfill.ts b/src/core/trust/backfill.ts
index fc21865c95..1fcf544edf 100644
--- a/src/core/trust/backfill.ts
+++ b/src/core/trust/backfill.ts
@@ -41,6 +41,7 @@ import { opError } from '../ops/contract.ts';
import { CONNECTOR_SOURCE_KINDS } from '../persistence/connector-identity.ts';
import { withCoordinatedWrite, withTrustBackfill } from '../persistence/context.ts';
import { maintenanceAttribution } from '../persistence/attribution.ts';
+import { readManagedMode } from '../persistence/managed-mode.ts';
import { frontmatterTrustCapsSql } from './channel.ts';
import { claimedSourceSql, legacyRowSql, notConnectorSourceSql, readLegacyCeilings, type LegacyCeilings } from './claim-state.ts';
import { TRUST_BACKFILL_COMPLETED_KEY, type TrustTable } from './schema.ts';
@@ -305,7 +306,7 @@ export async function runTrustBackfill(engine: BrainEngine, opts: TrustBackfillO
});
}
const { forTable, signals } = classifier(cols, [], await readLegacyCeilings(engine).catch(() => null));
- const [brain] = await engine.executeRaw<{ enabled: boolean }>('SELECT enabled FROM persistence_brain WHERE singleton = 1');
+ const managedBrain = await readManagedMode(engine);
const attribution = await maintenanceAttribution(engine);
const scoped = opts.sources !== undefined;
const op = scoped ? CLAIM_CHECKPOINT_OP : CHECKPOINT_OP;
@@ -327,7 +328,7 @@ export async function runTrustBackfill(engine: BrainEngine, opts: TrustBackfillO
`WITH b AS (SELECT x.id, ${trustTierFromRankSql(rule)} AS tier FROM ${from} WHERE x.id = ANY($1::bigint[]))
UPDATE ${table} t SET trust_tier = b.tier, write_origin = COALESCE(t.write_origin, $2::text::jsonb)
FROM b WHERE t.id = b.id AND t.trust_tier = 'unknown' AND b.tier <> 'unknown' RETURNING t.id`, [ids, origin])).length);
- updated += await engine.transaction(tx => brain?.enabled && sources.length
+ updated += await engine.transaction(tx => managedBrain && sources.length
? withCoordinatedWrite(tx, sources, () => apply(tx), attribution)
: apply(tx));
after = ids[ids.length - 1]!;
diff --git a/src/eval/longmemeval/harness.ts b/src/eval/longmemeval/harness.ts
index 074c7db0f9..ca3a4a3dc9 100644
--- a/src/eval/longmemeval/harness.ts
+++ b/src/eval/longmemeval/harness.ts
@@ -32,6 +32,8 @@ const PRESERVE_TABLES: ReadonlySet<string> = new Set([
'subagent_rate_leases',
// System One eval arms insert calibrations once per brain (configureDecideBrain); empty otherwise.
'decide_calibrations',
+ // The brain's identity and persistence-mode singleton (#6482): a brain without exactly one row refuses every write.
+ 'persistence_brain',
]);
export async function createBenchmarkBrain(): Promise<PGLiteEngine> {
diff --git a/test/cycle-phase-deadline.test.ts b/test/cycle-phase-deadline.test.ts
index 89884fb4a4..df71623990 100644
--- a/test/cycle-phase-deadline.test.ts
+++ b/test/cycle-phase-deadline.test.ts
@@ -46,6 +46,7 @@ function proposeEngine(pageCount: number): BrainEngine {
kind: 'pglite',
async executeRaw<T>(sql: string): Promise<T[]> {
if (sql.includes(PAGE_SQL_MARKER)) return pages as T[];
+ if (sql.includes('FROM persistence_brain')) return [{ enabled: false } as unknown as T]; // #6482: the strict mode reader needs one well-formed unmanaged row.
return [] as T[];
},
async getConfig() { return null; },
@@ -151,6 +152,7 @@ describe('phases consume deadlineAtMs (red on master: option was ignored)', () =
},
async executeRaw<T>(sql: string): Promise<T[]> {
if (sql.includes('INSERT')) inserts.push(sql);
+ if (sql.includes('FROM persistence_brain')) return [{ enabled: false } as unknown as T]; // #6482: the strict mode reader needs one well-formed unmanaged row.
return [] as T[];
},
async getConfig() { return null; },
diff --git a/test/destructive-guard.test.ts b/test/destructive-guard.test.ts
index c3820ee9ac..14471a7516 100644
--- a/test/destructive-guard.test.ts
+++ b/test/destructive-guard.test.ts
@@ -549,6 +549,7 @@ describe('soft-delete + restore lifecycle (column-based v0.26.5)', () => {
test('gbrain#4115 — a NON-FK error re-raises instead of reading as blocked (review gap G8)', async () => {
const stub = {
async executeRaw(sql: string): Promise<Array<{ id: string }>> {
+ if (sql.includes('FROM persistence_brain')) return [{ enabled: false } as never]; // #6482: one well-formed unmanaged row
if (sql.trimStart().startsWith('SELECT')) return [{ id: 'boom' }];
const err = new Error('canceling statement due to statement timeout') as Error & { code: string };
err.code = '57014'; // query_canceled — NOT the FK class
@@ -562,6 +563,7 @@ describe('soft-delete + restore lifecycle (column-based v0.26.5)', () => {
const stub = {
async executeRaw(sql: string): Promise<Array<{ id: string }>> {
if (sql.includes('archive_expires_at IS NULL')) return []; // #5452 unverified-archive listing: none here
+ if (sql.includes('FROM persistence_brain')) return [{ enabled: false } as never]; // #6482: one well-formed unmanaged row
if (sql.trimStart().startsWith('SELECT')) return [{ id: 'restored-mid-sweep' }];
return []; // per-id DELETE re-checks the expiry predicate → 0 rows
},
@@ -778,7 +780,7 @@ describe('FK-RESTRICT lifecycle (clientsReferencingSource + purge skip)', () =>
const purgeStub = {
executeRaw: async (sql: string) => {
if (sql.includes('oauth_clients')) sawOauthQuery = true;
- return [];
+ return sql.includes('FROM persistence_brain') ? [{ enabled: false }] : []; // #6482: one well-formed unmanaged row
},
} as any;
expect(await purgeExpiredSources(purgeStub)).toEqual({ purged: [], blocked: [] });
@@ -865,6 +867,7 @@ describe('purgeExpiredSources — clone cleanup containment', () => {
function purgeStubFor(id: string, localPath: string) {
return {
executeRaw: async (sql: string) => {
+ if (sql.includes('FROM persistence_brain')) return [{ enabled: false }]; // #6482: one well-formed unmanaged row
if (sql.trimStart().startsWith('SELECT')) {
return [{ id, config: { kind: 'github', gh_managed: true }, local_path: localPath }];
}
diff --git a/test/embed.serial.test.ts b/test/embed.serial.test.ts
index 54597a1102..25ad3fbc5a 100644
--- a/test/embed.serial.test.ts
+++ b/test/embed.serial.test.ts
@@ -939,8 +939,8 @@ describe('#3374 — transient network retry branch', () => {
if (prop === 'putPage') {
return async (slug: string, page: any) => { pageStore.set(slug, page); };
}
- // Like a real engine, executeRaw always resolves to a row array.
- if (prop === 'executeRaw') return () => Promise.resolve([]);
+ // Like a real engine, executeRaw always resolves to a row array (#6482: one well-formed unmanaged mode row).
+ if (prop === 'executeRaw') return (sql?: unknown) => Promise.resolve(String(sql).includes('FROM persistence_brain') ? [{ enabled: false }] : []);
return () => Promise.resolve(null);
},
});
diff --git a/test/extract-facts-guard-rollup.test.ts b/test/extract-facts-guard-rollup.test.ts
index 7a48e3b052..2ec756b0ec 100644
--- a/test/extract-facts-guard-rollup.test.ts
+++ b/test/extract-facts-guard-rollup.test.ts
@@ -25,6 +25,7 @@ function mkEngine(legacyCount: number): { calls: CapturedCall[]; engine: BrainEn
async executeRaw(sql: string, params: unknown[] = []) {
calls.push({ sql: sql.trim().replace(/\s+/g, ' '), params });
if (/COUNT\(\*\) AS n/.test(sql)) return [{ n: String(legacyCount) }];
+ if (sql.includes('FROM persistence_brain')) return [{ enabled: false }]; // #6482: the strict mode reader needs one well-formed unmanaged row.
return [];
},
async getAllSlugs() { return []; },
diff --git a/test/grade-takes-ensemble.test.ts b/test/grade-takes-ensemble.test.ts
index bf0a3056b9..2394f03641 100644
--- a/test/grade-takes-ensemble.test.ts
+++ b/test/grade-takes-ensemble.test.ts
@@ -53,6 +53,7 @@ function buildMockEngine(opts: { takes: Take[] }): {
},
async executeRaw<T>(sql: string, params?: unknown[]): Promise<T[]> {
captured.push({ sql, params: params ?? [] });
+ if (sql.includes('FROM persistence_brain')) return [{ enabled: false } as unknown as T]; // #6482: the strict mode reader needs one well-formed unmanaged row.
if (sql.includes('SELECT verdict, confidence, applied FROM take_grade_cache')) return [];
return [];
},
diff --git a/test/grade-takes.test.ts b/test/grade-takes.test.ts
index 1a8d38b46e..cfed64de6f 100644
--- a/test/grade-takes.test.ts
+++ b/test/grade-takes.test.ts
@@ -60,6 +60,7 @@ function buildMockEngine(opts: {
},
async executeRaw<T>(sql: string, params?: unknown[]): Promise<T[]> {
captured.push({ sql, params: params ?? [] });
+ if (sql.includes('FROM persistence_brain')) return [{ enabled: false } as unknown as T]; // #6482: the strict mode reader needs one well-formed unmanaged row.
if (sql.includes('SELECT verdict, confidence, applied FROM take_grade_cache')) {
const [takeId, pv, model, sig] = params ?? [];
const key = `${takeId}|${pv}|${model}|${sig}`;
diff --git a/test/helpers/embed-projection-mock.ts b/test/helpers/embed-projection-mock.ts
index 59e2f838b0..684557641f 100644
--- a/test/helpers/embed-projection-mock.ts
+++ b/test/helpers/embed-projection-mock.ts
@@ -29,6 +29,7 @@ export function mockEmbedProjectionEngine(overrides: Partial<Record<string, any>
overrides.executeRaw = async (sql: string, params?: unknown[]) => sql.startsWith('SELECT page_kind FROM pages WHERE id=')
? [{ page_kind: pageKinds.get(Number(params?.[0])) ?? 'markdown' }]
: sql === 'SELECT archived FROM sources WHERE id=$1' ? [{ archived: false }]
+ : sql.includes('FROM persistence_brain') ? [{ enabled: false }]
: executeRaw(sql, params);
const calls: { method: string; args: any[] }[] = [];
const track = (method: string) => (...args: any[]) => {
diff --git a/test/import-abort-error.test.ts b/test/import-abort-error.test.ts
index f8a698386f..5d2f7c0c5b 100644
--- a/test/import-abort-error.test.ts
+++ b/test/import-abort-error.test.ts
@@ -21,7 +21,7 @@ import type { BrainEngine } from '../src/core/engine.ts';
// empty sets.
const engineStub = {
kind: 'pglite',
- executeRaw: async () => [],
+ executeRaw: async (sql: string) => sql.includes('FROM persistence_brain') ? [{ enabled: false }] : [], // #6482: the strict mode reader needs one well-formed unmanaged row.
getConfig: async () => null,
} as unknown as BrainEngine;
@@ -71,7 +71,7 @@ test('unreadable import target → typed abort', async () => {
const answering = (match: string, rows: unknown[] | Error): BrainEngine => ({
...engineStub,
executeRaw: async (sql: string) => {
- if (!sql.includes(match)) return [];
+ if (!sql.includes(match)) return sql.includes('FROM persistence_brain') ? [{ enabled: false }] : [];
if (rows instanceof Error) throw rows;
return rows;
},
diff --git a/test/import-connection-budget.serial.test.ts b/test/import-connection-budget.serial.test.ts
index ad413a219f..d2e7d8c2a9 100644
--- a/test/import-connection-budget.serial.test.ts
+++ b/test/import-connection-budget.serial.test.ts
@@ -86,7 +86,7 @@ beforeEach(() => {
function fakeEngine(kind: 'postgres' | 'pglite'): BrainEngine {
return {
kind,
- executeRaw: async () => [],
+ executeRaw: async (sql: string) => sql.includes('FROM persistence_brain') ? [{ enabled: false }] : [], // #6482: one well-formed unmanaged row
getConfig: async () => null,
} as unknown as BrainEngine;
}
diff --git a/test/import-file.test.ts b/test/import-file.test.ts
index ad43552dcd..1756da1fae 100644
--- a/test/import-file.test.ts
+++ b/test/import-file.test.ts
@@ -76,7 +76,8 @@ function mockEngine(overrides: Partial<Record<string, any>> = {}): BrainEngine {
// transaction: just call the fn with the same engine (no real DB transaction in tests)
if (prop === 'transaction') return async (fn: (tx: BrainEngine) => Promise<any>) => fn(engine);
// Like a real engine, executeRaw always resolves to a row array.
- if (prop === 'executeRaw' && !overrides.executeRaw) return (...args: any[]) => { calls.push({ method: prop, args }); return Promise.resolve([]); };
+ // #6482: the strict mode reader needs one well-formed unmanaged row.
+ if (prop === 'executeRaw' && !overrides.executeRaw) return (...args: any[]) => { calls.push({ method: prop, args }); return Promise.resolve(String(args[0]).includes('FROM persistence_brain') ? [{ enabled: false }] : []); };
return track(prop);
},
});
@@ -521,7 +522,7 @@ describe('importFile — CJK wave (v0.32.7)', () => {
},
executeRaw: async (sql: string) => {
if (isVersionStamp(sql)) expect(replacementCompleted).toBe(true);
- return [];
+ return sql.includes('FROM persistence_brain') ? [{ enabled: false }] : [];
},
});
}
diff --git a/test/import-screen.test.ts b/test/import-screen.test.ts
index c88994d9b9..8734bff7b3 100644
--- a/test/import-screen.test.ts
+++ b/test/import-screen.test.ts
@@ -28,7 +28,8 @@ function mockEngine(): BrainEngine {
if (prop === 'getPage') return (slug: string) => Promise.resolve(pages.get(slug) ?? null);
if (prop === 'putPage') return async (slug: string, page: unknown) => { pages.set(slug, page); return page; };
if (prop === 'transaction') return async (fn: (tx: BrainEngine) => Promise<unknown>) => fn(engine);
- return () => Promise.resolve(prop === 'executeRaw' ? [] : null);
+ // #6482: the strict mode reader needs one well-formed unmanaged row.
+ return (sql?: unknown) => Promise.resolve(prop === 'executeRaw' ? (String(sql).includes('FROM persistence_brain') ? [{ enabled: false }] : []) : null);
},
}) as unknown as BrainEngine;
return engine;
diff --git a/test/import-yaml-frontmatter.test.ts b/test/import-yaml-frontmatter.test.ts
index fe3e194f2d..727f218f66 100644
--- a/test/import-yaml-frontmatter.test.ts
+++ b/test/import-yaml-frontmatter.test.ts
@@ -31,8 +31,8 @@ function mockEngine(): BrainEngine {
if (prop === 'transaction') return async (fn: (tx: BrainEngine) => Promise<any>) => fn(engine);
return (...args: any[]) => {
calls.push({ method: String(prop), args });
- // Like a real engine, executeRaw always resolves to a row array.
- return Promise.resolve(prop === 'executeRaw' ? [] : null);
+ // Like a real engine, executeRaw always resolves to a row array. // #6482: the strict mode reader needs one well-formed unmanaged row.
+ return Promise.resolve(prop === 'executeRaw' ? (String(args[0]).includes('FROM persistence_brain') ? [{ enabled: false }] : []) : null);
};
},
});
diff --git a/test/lint-shared-engine.test.ts b/test/lint-shared-engine.test.ts
index e311f183a5..05ad83f429 100644
--- a/test/lint-shared-engine.test.ts
+++ b/test/lint-shared-engine.test.ts
@@ -36,7 +36,7 @@ describe('runLintCore engine reuse (issue #1678)', () => {
kind: 'postgres' as const,
// Model the shared engine's source-root lookup and lock bookkeeping;
// neither operation opens another pool or changes the reuse counters.
- executeRaw: async () => [],
+ executeRaw: async (sql: string) => sql.includes('FROM persistence_brain') ? [{ enabled: false }] : [], // #6482: the strict mode reader needs one well-formed unmanaged row.
sql: async (parts: TemplateStringsArray, ...params: unknown[]) => {
const statement = parts.join('?');
if (statement.includes('INSERT INTO gbrain_cycle_locks')) return [{ id: params[0], fence: 'test-fence' }];
diff --git a/test/persistence-mode-fail-closed-6482.test.ts b/test/persistence-mode-fail-closed-6482.test.ts
new file mode 100644
index 0000000000..4c23b8277d
--- /dev/null
+++ b/test/persistence-mode-fail-closed-6482.test.ts
@@ -0,0 +1,153 @@
+/**
+ * #6482 (fix wave 15 P4.1): a `persistence_brain` read that returns no row,
+ * two rows or a non-boolean `enabled` is an impossible state, not a mode. Every
+ * mode reader goes through `readManagedMode` / `readPersistenceBrain` in
+ * `persistence/ownership.ts`, which refuses `storage_error` (the
+ * `automaticSyncPull` contract) instead of treating the brain as unmanaged.
+ *
+ * Fails on master: `managedPersistenceEnabled` returns false for `[]` and
+ * `[{}]`, `assertUnmanagedCanonicalWriter` grants the legacy writer on the same
+ * shapes, and `withConnectorSync` / `beginConnectorSync` take the unmanaged
+ * path (and write the attempt checkpoint) on an empty read.
+ */
+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { resetPgliteState } from './helpers/reset-pglite.ts';
+import type { BrainEngine } from '../src/core/engine.ts';
+import type { SqlEngine } from '../src/core/persistence/model.ts';
+import { managedPersistenceEnabled, readManagedMode, readPersistenceBrain } from '../src/core/persistence/ownership.ts';
+import { inspectPersistenceBrain } from '../src/core/persistence/managed-mode.ts';
+import { readWriterDiagnostics } from '../src/core/persistence/diagnostics.ts';
+import { assertUnmanagedCanonicalWriter } from '../src/core/persistence/maintenance.ts';
+import { beginConnectorSync, withConnectorSync } from '../src/core/persistence/connector-sync.ts';
+import { renderCliError } from '../src/core/agent-output.ts';
+
+const MALFORMED: ReadonlyArray<readonly [string, readonly unknown[]]> = [
+ ['missing', []], ['empty row', [{}]], ['null row', [null]], ['string enabled', [{ enabled: 'yes' }]], ['null enabled', [{ enabled: null }]],
+ ['numeric enabled', [{ enabled: 1 }]], ['duplicated', [{ enabled: false }, { enabled: true }]],
+];
+
+function fake(rows: readonly unknown[] | Error, seen: string[] = []): SqlEngine {
+ return { executeRaw: async (sql: string) => { seen.push(sql); if (rows instanceof Error) throw rows; return rows as unknown[]; } } as unknown as SqlEngine;
+}
+
+describe('readManagedMode', () => {
+ test('a well-formed row answers; only literal false selects unmanaged', async () => {
+ expect(await readManagedMode(fake([{ enabled: false }]))).toBe(false);
+ expect(await readManagedMode(fake([{ enabled: true }]))).toBe(true);
+ expect(await managedPersistenceEnabled(fake([{ enabled: false }]))).toBe(false);
+ expect(await managedPersistenceEnabled(fake([{ enabled: true }]))).toBe(true);
+ expect(await readPersistenceBrain(fake([{ brain_id: 'b', enabled: true, mode_epoch: '3' }]))).toMatchObject({ brain_id: 'b', enabled: true, mode_epoch: '3' });
+ });
+
+ for (const [label, rows] of MALFORMED) {
+ test(`${label} persistence metadata refuses storage_error from every shared reader`, async () => {
+ await expect(readManagedMode(fake(rows))).rejects.toMatchObject({ code: 'storage_error', detail: 'persistence_mode_unknown' });
+ await expect(managedPersistenceEnabled(fake(rows))).rejects.toMatchObject({ code: 'storage_error' });
+ await expect(readPersistenceBrain(fake(rows))).rejects.toMatchObject({ code: 'storage_error' });
+ await expect(assertUnmanagedCanonicalWriter(fake(rows), 'probe')).rejects.toMatchObject({ code: 'storage_error' });
+ });
+ }
+
+ test('a query error propagates as itself, never as a mode', async () => {
+ const boom = new Error('synthetic metadata unavailable');
+ await expect(readManagedMode(fake(boom))).rejects.toBe(boom);
+ await expect(managedPersistenceEnabled(fake(boom))).rejects.toBe(boom);
+ await expect(assertUnmanagedCanonicalWriter(fake(boom), 'probe')).rejects.toBe(boom);
+ });
+
+ test('the lock option keeps FOR SHARE / FOR UPDATE on the statement; the plain text is the memoized one', async () => {
+ const seen: string[] = [];
+ await readManagedMode(fake([{ enabled: true }], seen));
+ await readManagedMode(fake([{ enabled: true }], seen), { lock: 'share' });
+ await readManagedMode(fake([{ enabled: true }], seen), { lock: 'update' });
+ await readPersistenceBrain(fake([{ brain_id: 'b', enabled: false, mode_epoch: null }], seen), { lock: 'update' });
+ expect(seen[0]).toBe('SELECT enabled FROM persistence_brain WHERE singleton=1');
+ expect(seen[1]).toBe('SELECT enabled FROM persistence_brain WHERE singleton=1 FOR SHARE');
+ expect(seen[2]).toBe('SELECT enabled FROM persistence_brain WHERE singleton=1 FOR UPDATE');
+ expect(seen[3]).toMatch(/^SELECT brain_id,enabled,[\s\S]*FROM persistence_brain WHERE singleton=1 FOR UPDATE$/);
+ });
+
+ test('the refusal renders the agent contract with the read-only probe and a doctor verify', async () => {
+ const error = await readManagedMode(fake([])).catch((e: unknown) => e);
+ const env = JSON.parse(renderCliError(error, { json: true, command: 'sync', tty: false }).stdout!);
+ expect(env.code).toBe('storage_error');
+ expect(env.why).toContain('persistence_brain singleton is missing');
+ expect(env.fix).toMatchObject({ next: 'run', command: 'gbrain sources writer status --probe --json', consent: [], actor: 'agent', verify: { argv: ['gbrain', 'doctor', '--json'] } });
+ const dup = await readManagedMode(fake([{ enabled: true }, { enabled: true }])).catch((e: unknown) => e) as { why: string };
+ expect(dup.why).toContain('duplicated (2 row(s))');
+ });
+
+ test('the probe the refusal names (writer status) reports a malformed singleton instead of refusing on it', async () => {
+ for (const [, rows] of MALFORMED) {
+ const inspected = await inspectPersistenceBrain(fake(rows));
+ expect(inspected.row).toBeNull();
+ expect(inspected.problem).toContain('persistence_brain singleton is');
+ }
+ expect(await inspectPersistenceBrain(fake([{ brain_id: 'b', enabled: false, mode_epoch: '1', skill_bundles_enabled: null, writer_protocol_floor: null }])))
+ .toEqual({ row: { brain_id: 'b', enabled: false, mode_epoch: '1', skill_bundles_enabled: null, writer_protocol_floor: null }, problem: null });
+ const diagnostics = await readWriterDiagnostics({ ...fake([]), kind: 'pglite' } as unknown as BrainEngine);
+ expect(diagnostics).toMatchObject({ enabled: false, brain_id: null });
+ expect((diagnostics as { persistence_mode_problem?: string }).persistence_mode_problem).toContain('missing (0 row(s))');
+ });
+});
+
+describe('connector entry paths on an impossible read', () => {
+ let engine: PGLiteEngine;
+ beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+ }, 120_000);
+ afterAll(async () => { await engine.disconnect(); });
+ beforeEach(async () => { await resetPgliteState(engine); });
+
+ /** The real engine, except that the mode read answers `rows`; every statement after the mode read is recorded. */
+ function misreading(rows: readonly unknown[]) {
+ const after: string[] = [];
+ let misread = false;
+ const executeRaw = async (sql: string, params?: unknown[], opts?: unknown) => {
+ if (misread) after.push(sql);
+ if (sql.includes('FROM persistence_brain')) { misread = true; return rows as unknown[]; }
+ return (engine.executeRaw as (s: string, p?: unknown[], o?: unknown) => Promise<unknown[]>).call(engine, sql, params, opts);
+ };
+ const transaction = async () => { after.push('BEGIN'); throw new Error('a transaction was opened after the impossible read'); };
+ const wrapped = new Proxy(engine, { get(target, prop) {
+ if (prop === 'executeRaw') return executeRaw;
+ if (prop === 'transaction') return transaction;
+ const value = Reflect.get(target, prop);
+ return typeof value === 'function' ? value.bind(target) : value;
+ } }) as unknown as BrainEngine;
+ return { wrapped, after };
+ }
+ const mutations = (after: string[]) => after.filter(sql => /^\s*(INSERT|UPDATE|DELETE|BEGIN)/i.test(sql));
+ const checkpoints = () => engine.executeRaw<{ n: number }>('SELECT COUNT(*)::int AS n FROM op_checkpoints').then(r => r[0].n);
+
+ for (const [label, rows] of [['missing', []], ['empty row', [{}]], ['duplicated', [{ enabled: false }, { enabled: false }]]] as const) {
+ test(`withConnectorSync refuses on a ${label} read with zero downstream writes`, async () => {
+ await engine.executeRaw("INSERT INTO sources (id, name, config) VALUES ('gh-6482', 'gh-6482', '{\"kind\":\"github\"}'::jsonb)");
+ const before = await checkpoints();
+ const { wrapped, after } = misreading(rows);
+ let worked = false;
+ await expect(withConnectorSync(wrapped, 'gh-6482', 'github', {}, {}, async () => { worked = true; return 'synced'; }))
+ .rejects.toMatchObject({ code: 'storage_error', detail: 'persistence_mode_unknown' });
+ expect(worked).toBe(false);
+ expect(mutations(after)).toEqual([]);
+ expect(await checkpoints()).toBe(before);
+ });
+
+ test(`beginConnectorSync refuses on a ${label} read instead of answering "unmanaged"`, async () => {
+ const { wrapped, after } = misreading(rows);
+ await expect(beginConnectorSync(wrapped, 'gh-6482', 'github', {}, {})).rejects.toMatchObject({ code: 'storage_error' });
+ expect(mutations(after)).toEqual([]);
+ });
+ }
+
+ test('a well-formed unmanaged row still takes the classic path and records the attempt', async () => {
+ await engine.executeRaw("INSERT INTO sources (id, name, config) VALUES ('gh-6482', 'gh-6482', '{\"kind\":\"github\"}'::jsonb)");
+ const before = await checkpoints();
+ expect(await withConnectorSync(engine, 'gh-6482', 'github', {}, {}, async session => session === null ? 'classic' : 'managed')).toBe('classic');
+ expect(await beginConnectorSync(engine, 'gh-6482', 'github', {}, {})).toBeNull();
+ expect(await checkpoints()).toBe(before + 1);
+ });
+});
diff --git a/test/persistence-mode-reader-guard.test.ts b/test/persistence-mode-reader-guard.test.ts
new file mode 100644
index 0000000000..77e719ed79
--- /dev/null
+++ b/test/persistence-mode-reader-guard.test.ts
@@ -0,0 +1,73 @@
+/**
+ * #6482 (fix wave 15 P4.1) guard: `persistence_brain.enabled` is read through
+ * `readManagedMode` / `readPersistenceBrain` (`src/core/persistence/managed-mode.ts`,
+ * re-exported by `ownership.ts`) and nowhere else. A raw `SELECT … enabled … FROM
+ * persistence_brain` in product code is a mode reader that can fail open again
+ * (an empty or malformed read routed a managed brain through the unmanaged
+ * writer); route it through the shared predicate, with `{ lock }` when the
+ * caller serialized on the row. Non-test `src/` only; generated blobs and DDL
+ * (trigger bodies, migrations) are schema, not readers, and are listed below.
+ */
+import { describe, expect, test } from 'bun:test';
+import { readdirSync, readFileSync, statSync } from 'node:fs';
+import { join, relative } from 'node:path';
+
+const ROOT = join(import.meta.dir, '..');
+const SRC = join(ROOT, 'src');
+
+/** Files allowed to carry the raw statement, each with the reason it is not a mode reader. */
+const ALLOWED: Record<string, string> = {
+ 'src/core/persistence/managed-mode.ts': 'the one reader',
+ 'src/core/persistence/writer-guard-schema.ts': 'DDL: the managed-writer trigger body runs in the database',
+ 'src/core/shared-skills/persistence-schema.ts': 'DDL: shared-skill trigger bodies',
+ 'src/core/persistence/graduation-target.ts': 'target seed census (bool_and(NOT enabled) over an expected-empty target), not a mode read',
+ 'src/core/persistence/admin-intent.ts': 'the writer-admin state digest hashes the whole row inside jsonb_build_object; it routes nothing',
+};
+const GENERATED = /\.generated\.ts$|^src\/core\/schema-migrations\//;
+
+function* walk(dir: string): Generator<string> {
+ for (const entry of readdirSync(dir)) {
+ const path = join(dir, entry);
+ if (statSync(path).isDirectory()) yield* walk(path);
+ else if (path.endsWith('.ts')) yield path;
+ }
+}
+
+/** Every `SELECT … FROM persistence_brain …` statement that names `enabled` (not `skill_bundles_enabled`) in its columns or its WHERE clause. */
+function rawModeReads(source: string): string[] {
+ const flat = source.replace(/\s+/g, ' ');
+ const hits: string[] = [];
+ const re = /SELECT\b((?:(?!\bFROM\b|\bSELECT\b).)*?)\bFROM\s+persistence_brain\b([^;'"`]{0,80})/gi;
+ for (const match of flat.matchAll(re)) if (/(?<!\w)(?:\w+\.)?enabled\b/i.test(match[1] + match[2])) hits.push(match[0]);
+ return hits;
+}
+
+describe('persistence mode readers (#6482)', () => {
+ test('no product file outside managed-mode.ts selects persistence_brain.enabled', () => {
+ const offenders: string[] = [];
+ for (const path of walk(SRC)) {
+ const rel = relative(ROOT, path).split('\\').join('/');
+ if (GENERATED.test(rel) || rel in ALLOWED) continue;
+ const hits = rawModeReads(readFileSync(path, 'utf8'));
+ if (hits.length) offenders.push(`${rel}: ${hits[0].slice(0, 120)}`);
+ }
+ expect(offenders).toEqual([]);
+ });
+
+ test('the allow-list only names files that still need it', () => {
+ for (const rel of Object.keys(ALLOWED)) {
+ expect(rawModeReads(readFileSync(join(ROOT, rel), 'utf8')).length, `${rel} no longer carries a raw read; drop it from ALLOWED`).toBeGreaterThan(0);
+ }
+ });
+
+ test('the matcher sees every reader shape this guard replaced', () => {
+ expect(rawModeReads("engine.executeRaw('SELECT enabled FROM persistence_brain WHERE singleton=1')")).toHaveLength(1);
+ expect(rawModeReads("tx.executeRaw('SELECT enabled FROM persistence_brain WHERE singleton=1 FOR SHARE')")).toHaveLength(1);
+ expect(rawModeReads("`SELECT brain_id, enabled, mode_epoch,\n (to_jsonb(persistence_brain)->>'x')::int AS y\n FROM persistence_brain WHERE singleton=1${lock}`")).toHaveLength(1);
+ expect(rawModeReads("\"SELECT brain_id,enabled,to_jsonb(persistence_brain)->>'mode_epoch' AS mode_epoch FROM persistence_brain WHERE singleton=1\"")).toHaveLength(1);
+ expect(rawModeReads("`WHERE NOT COALESCE((SELECT enabled FROM persistence_brain WHERE singleton=1), false)`")).toHaveLength(1);
+ expect(rawModeReads("'SELECT skill_bundles_enabled FROM persistence_brain WHERE singleton=1'")).toHaveLength(0);
+ expect(rawModeReads("'SELECT brain_id FROM persistence_brain WHERE singleton=1'")).toHaveLength(0);
+ expect(rawModeReads("'SELECT singleton FROM persistence_brain WHERE singleton=1 FOR UPDATE'")).toHaveLength(0);
+ });
+});
diff --git a/test/propose-takes-config-max-tokens.test.ts b/test/propose-takes-config-max-tokens.test.ts
index 1a1c2f632b..9a0fe21093 100644
--- a/test/propose-takes-config-max-tokens.test.ts
+++ b/test/propose-takes-config-max-tokens.test.ts
@@ -128,6 +128,7 @@ function buildMockEngine(config: Record<string, string>): BrainEngine {
return config[key] ?? null;
},
async executeRaw<T>(sql: string): Promise<T[]> {
+ if (sql.includes('FROM persistence_brain')) return [{ enabled: false } as unknown as T]; // #6482: the strict mode reader needs one well-formed unmanaged row.
if (sql.includes('SELECT slug, source_id, compiled_truth')) {
return [{
slug: 'wiki/page-0',
diff --git a/test/propose-takes-served-model.test.ts b/test/propose-takes-served-model.test.ts
index a007a6c8ce..23f32e4edf 100644
--- a/test/propose-takes-served-model.test.ts
+++ b/test/propose-takes-served-model.test.ts
@@ -78,6 +78,7 @@ function buildMockEngine(): { engine: BrainEngine; captured: CapturedSql[] } {
kind: 'pglite',
async executeRaw<T>(sql: string, params?: unknown[]): Promise<T[]> {
captured.push({ sql, params: params ?? [] });
+ if (sql.includes('FROM persistence_brain')) return [{ enabled: false } as unknown as T]; // #6482: the strict mode reader needs one well-formed unmanaged row.
if (sql.includes('SELECT slug, source_id, compiled_truth')) {
return [{
slug: 'wiki/one-page',
diff --git a/test/propose-takes-truncation.test.ts b/test/propose-takes-truncation.test.ts
index 9d81af3b43..687ae659d8 100644
--- a/test/propose-takes-truncation.test.ts
+++ b/test/propose-takes-truncation.test.ts
@@ -249,6 +249,7 @@ function buildMockEngine(pageCount: number): { engine: BrainEngine; captured: Ca
kind: 'pglite',
async executeRaw<T>(sql: string, params?: unknown[]): Promise<T[]> {
captured.push({ sql, params: params ?? [] });
+ if (sql.includes('FROM persistence_brain')) return [{ enabled: false } as unknown as T]; // #6482: the strict mode reader needs one well-formed unmanaged row.
if (sql.includes('SELECT slug, source_id, compiled_truth')) {
return Array.from({ length: pageCount }, (_, i) => ({
slug: `wiki/page-${i}`,
diff --git a/test/propose-takes.test.ts b/test/propose-takes.test.ts
index 53f145ce01..abaf721fd3 100644
--- a/test/propose-takes.test.ts
+++ b/test/propose-takes.test.ts
@@ -60,6 +60,7 @@ function buildMockEngine(opts: {
},
async executeRaw<T>(sql: string, params?: unknown[]): Promise<T[]> {
captured.push({ sql, params: params ?? [] });
+ if (sql.includes('FROM persistence_brain')) return [{ enabled: false } as unknown as T]; // #6482: the strict mode reader needs one well-formed unmanaged row.
// Narrow candidate-page projection (replaces listPages in the phase).
if (sql.includes('SELECT slug, source_id, compiled_truth')) {
return opts.pages.map((p) => ({
diff --git a/test/source-boundary-mutation-errors.test.ts b/test/source-boundary-mutation-errors.test.ts
index c91ef13eb5..fe03f05110 100644
--- a/test/source-boundary-mutation-errors.test.ts
+++ b/test/source-boundary-mutation-errors.test.ts
@@ -308,9 +308,9 @@ describe('mutation-time deletion race reclassification (#4109)', () => {
},
// DB-only brain: no source local_path / repo_path, so the timeline
// write-through takes its handled:false path and the op falls through
- // to the insert.
- async executeRaw() {
- return [];
+ // to the insert. #6482: the strict mode reader needs one well-formed unmanaged row.
+ async executeRaw(sql: string) {
+ return sql.includes('FROM persistence_brain') ? [{ enabled: false }] : [];
},
async getConfig() {
return null;
@@ -374,7 +374,7 @@ describe('mutation-time deletion race reclassification (#4109)', () => {
async addLink() {
throw new PageMissingError('addLink', 'to', 'topics/race-restored', WRITE_SRC);
},
- async executeRaw() { return []; }, // explicitly unmanaged fixture
+ async executeRaw(sql: string) { return sql.includes('FROM persistence_brain') ? [{ enabled: false }] : []; }, // explicitly unmanaged fixture (#6482: one well-formed row)
} as unknown as BrainEngine;
const result = await dispatchToolCall(eng, 'add_link', {
from: 'topics/race-from',
diff --git a/test/sources.test.ts b/test/sources.test.ts
index fbe9d3d147..eaff313ea1 100644
--- a/test/sources.test.ts
+++ b/test/sources.test.ts
@@ -34,6 +34,7 @@ function makeStub(rowsByPattern: Record<string, unknown[]> = {}): {
for (const [pattern, rows] of Object.entries(rowsByPattern)) {
if (sql.includes(pattern)) return rows as never;
}
+ if (sql.includes('FROM persistence_brain')) return [{ enabled: false }] as never; // #6482: the strict mode reader needs one well-formed unmanaged row.
return [] as never;
};
diff --git a/test/takes-extract-json.test.ts b/test/takes-extract-json.test.ts
index 1d823b612f..2c50f0fccd 100644
--- a/test/takes-extract-json.test.ts
+++ b/test/takes-extract-json.test.ts
@@ -16,6 +16,7 @@ const engine = {
getConfig: async (key: string) => key === 'takes.bootstrap_enabled' ? 'true' : null,
executeRaw: async (sql: string, params: unknown[] = []) => {
queries.push({ sql, params });
+ if (sql.includes('FROM persistence_brain')) return [{ enabled: false }]; // #6482: the strict mode reader needs one well-formed unmanaged row.
return [];
},
} as unknown as BrainEngine;
@@ -127,7 +128,7 @@ describe('takes extract --before cursor validation (#5059)', () => {
getConfig: async (key: string) => key === 'takes.bootstrap_enabled' ? 'true' : null,
executeRaw: async (sql: string) => sql.includes('FROM pages')
? [{ id: 9, slug: 'concepts/short', source_id: 'default', type: 'concept', compiled_truth: 'too short', updated_at: new Date('2030-01-02T03:04:05.123Z'), resume_at: '2030-01-02 03:04:05.123456+00,9' }]
- : [],
+ : sql.includes('FROM persistence_brain') ? [{ enabled: false }] : [],
} as unknown as BrainEngine;
const stdout = await captureStdout(() => runTakes(pageEngine, ['extract', '--from-pages', '--dry-run']));
expect(stdout).toContain("next: --before '2030-01-02 03:04:05.123456+00,9'");