Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(persistence): activate database-only brains with rooted unbound sources; never auto-claim them on a flip (#6449)
garrytana2b56ff2ba0d
diff --git a/docs/architecture/topologies.md b/docs/architecture/topologies.mdindex 71d49e9c10..4a09ca44ff 100644--- a/docs/architecture/topologies.md+++ b/docs/architecture/topologies.md@@ -441,8 +441,21 @@ substitute the new value and retry. Dry runs do not grant permission to apply.Activation additionally requires every older writer and maintenance process onevery host to be upgraded and stopped, filesystem sources to have their intended-owners, and outstanding locks and recovery to be resolved. Preview activation-with `--confirm-quiesced --dry-run`, then, only when approved:+owners, and outstanding locks and recovery to be resolved. On a brain whose+`sync.write_through` is `false` (a database-only brain), a rooted source with no+owner needs none: `writer status` already reports it `database_only`, and+activation lists it under `database_only_sources` and goes ahead (#6449). Page+writes to it publish to the database only (`write_through.skipped:+disabled_by_config`), `gbrain sync` on it refuses `owner_unavailable` naming the+claim, and turning `sync.write_through` back on does not claim it, not even on+PGLite (activation records the listed sources in+`persistence.database_only_sources`; deactivation clears it): the next write+refuses with `detail: unbound_source` and the `writer claim` to run (preview+with `--dry-run`), or stays database-only under+`persistence.unbound_write=database_only`. With `sync.write_through` on, the+same source refuses activation with `writer_registration_required`, and the+suggestion names that claim and the database-only alternative. Preview+activation with `--confirm-quiesced --dry-run`, then, only when approved:```bashgbrain sources writer activate --brain host --confirm-quiesced \diff --git a/docs/guides/write-refusals.md b/docs/guides/write-refusals.mdindex f74f767096..242c169fd5 100644--- a/docs/guides/write-refusals.md+++ b/docs/guides/write-refusals.md@@ -479,8 +479,12 @@ A source with a checkout path (`local_path`, or `sync.repo_path` for the`default` source) normally publishes every page write to a markdown file inthat checkout, through the source's canonical owner. PGLite claims that ownerautomatically on the first write. Postgres does not, because several hosts can-share one Postgres brain and only one of them may own the files. Until someone-binds the source, page writes to it refuse with+share one Postgres brain and only one of them may own the files. Neither does+PGLite for a source `writer activate` listed under `database_only_sources`+(a rooted source with no owner on a brain whose `sync.write_through` was off,+#6449; the list is the config key `persistence.database_only_sources`, which+deactivation clears): turning the setting back on never starts an unreviewed+claim there. Until someone binds the source, page writes to it refuse with`owner_unavailable` and `detail: unbound_source`. The refusal is aconfiguration state, not a transient one: it renders `retryable: false` and a`fix` with `next: ask_user`, so an agent never retries it.diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex 93fc686e47..4aa2119c65 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -442,6 +442,8 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText }{ since: '0.60.175.0', text: 'A published page file now always carries the page\'s own `type`, `title` and tags from the database columns. A legacy row whose stored frontmatter also held a `type` or `title` that disagreed with the columns used to render the stored value (and stored `tags` rendered when the page had none); the next write of such a page now renders the columns and drops the stale keys, so the file\'s header can change once. Nested keys of the same names (`metadata.title`) and the `slug:` stamp for slugs the path cannot derive are unchanged.' },// Fix wave 15 G2 (GBRA-79, #6501); `since` is a placeholder equal to the branch's VERSION until the integrator sets the merge-slot stamp.{ since: '0.60.175.0', text: 'A managed checkout\'s persisted directory birth stamp now matches the live directory when the two are within 1 µs, instead of only when they are byte-identical (#6501: on APFS a freshly created root reports a birth time tens of nanoseconds apart between the process that stamped it and later processes, which left every write to that root refused `recovery_required`). The owner token, brain, worktree, root, inode and device still have to match exactly; a damaged or zero stamp still refuses; the in-process file target check, the staging identity and the transfer prepare/accept comparison stay exact. When the inode or birth time moved beyond that while everything else matches (a checkout restored or recreated at its recorded path), the refusal now carries detail `physical_root_directory_changed` and names the exit: `gbrain sources writer transfer prepare/accept <source> --self-transfer --confirm-relocated-root` (`writer status --json` prints it filled in). The tolerance covers the reported drift; it was not reproduced on APFS here, so #6501 stays open until a reporter confirms on this build.' },+ // Fix wave 15 G2 (GBRA-79, #6449); `since` is a placeholder equal to the branch's VERSION until the integrator sets the merge-slot stamp.+ { since: '0.60.175.0', text: '`gbrain sources writer activate` no longer refuses `writer_registration_required` for a source that has a checkout path but no canonical owner when the brain\'s `sync.write_through` is `false` (#6449): `writer status` already reported that source `database_only`, and activation now agrees, listing it under `database_only_sources` and leaving it unbound. Page writes to it stay database-only (`disabled_by_config`), and turning `sync.write_through` back on does not claim it automatically on a PGLite brain (activation records the listed sources in `persistence.database_only_sources`; deactivation clears it): the next write refuses `owner_unavailable` with `detail: unbound_source` and the `gbrain sources writer claim` to run (or publishes database-only under `persistence.unbound_write=database_only`), the same as on Postgres. With `sync.write_through` on, the activation refusal and the `owner_unavailable` that `gbrain sync` gives such a source now name the claim (preview with `--dry-run`) instead of a generic inspection hint.' },];/** The newest disclosed change's release: the notice id moves only when a release adds rows. */diff --git a/src/core/persistence/activation.ts b/src/core/persistence/activation.tsindex ba7ecadf7e..f489a6f1fd 100644--- a/src/core/persistence/activation.ts+++ b/src/core/persistence/activation.ts@@ -16,6 +16,8 @@ import { deleteLockRowExact } from '../db-lock.ts';import { catalogueError } from '../error-catalogue.ts';import { isConnectorSourceKind } from './connector-identity.ts';import { gitDurabilityState } from './git-durability-policy.ts';+import { writeThroughConfigured } from './switches.ts';+import { DATABASE_ONLY_SOURCES_KEY, unboundBindCommand } from './unbound-source.ts';export interface ActivationReport {enabled: boolean;@@ -31,6 +33,14 @@ export interface ActivationReport {* until `gbrain sources writer git-durability <source> --enable` runs.*/git_durability?: Array<{ source_id: string; state: 'on' | 'off' | 'unknown'; enable_command: string | null }>;+ /**+ * #6449: rooted, non-connector sources with no canonical owner on a brain whose `sync.write_through` is off. They are+ * database-only (page writes publish to the database with `databaseOnlyReason: disabled_by_config`, `writer status`+ * reports `database_only`), so activation lists them instead of refusing and records the list in+ * `persistence.database_only_sources` (a PGLite write to one never runs the automatic first-write claim); claiming one+ * later is a deliberate `writer claim`, and `gbrain sync` on one refuses `owner_unavailable` naming that claim.+ */+ database_only_sources?: string[];/** #5514: `activated: false` with `enabled: true` says why, so a no-op is not read as a silent failure. */reason?: 'already_enabled';why?: string;@@ -67,13 +77,26 @@ function sourcePathMissing(source: SourceRoot, claimedRoot: string | null): Opererror.detail = 'source_path_missing';return error;}-async function validatedBindings(engine: BrainEngine, sources: SourceRoot[], hostId: string | null, lock = false): Promise<WorktreeBinding[]> {+interface ValidatedSources { bindings: WorktreeBinding[]; databaseOnly: string[] }+/** #6449: a rooted source with no owner on a write_through=true brain; the claim is the fix, database-only mode the alternative. */+function unboundRootedSource(source: SourceRoot): OperationError {+ return opError('writer_registration_required', `Source '${source.id}' needs an active canonical owner before activation.`,+ `Source '${source.id}' has a checkout path (${source.root}) but no canonical owner, and sync.write_through is on, so activation stopped and nothing changed. `+ + `Either bind it on the brain host (ask the user first; preview with gbrain sources writer claim ${source.id} --path ${source.root} --dry-run --json, then ${unboundBindCommand(source.id, source.root)}), `+ + `or make the brain database-only with gbrain config set sync.write_through false, after which activation lists the source under database_only_sources and page writes publish to the database only. ${WRITER_INSPECTION_HINT}`,+ { fix: writerStatusFix(`Shows source ${source.id}'s binding state (database_only, claim_required) and admin_state, read-only.`, source.id) });+}+async function validatedBindings(engine: BrainEngine, sources: SourceRoot[], hostId: string | null, writeThrough: boolean, lock = false): Promise<ValidatedSources> {const bindings: WorktreeBinding[] = [];+ const databaseOnly: string[] = [];for (const source of sources) {let binding = await getWorktreeBinding(engine, source.id, hostId);if ((!source.root || source.connector) && !binding) continue;if (!binding && !source.connector && !existsSync(resolve(source.root!))) throw sourcePathMissing(source, null);- if (binding && lock) {+ // #6449: onboarding already reports this source database_only; activation agrees instead of demanding a claim.+ if (!binding && !writeThrough) { databaseOnly.push(source.id); continue; }+ if (!binding) throw unboundRootedSource(source);+ if (lock) {await engine.executeRaw('SELECT id FROM persistence_worktrees WHERE id=$1::uuid FOR SHARE', [binding.worktree_id]);binding = await getWorktreeBinding(engine, source.id, hostId);}@@ -99,7 +122,7 @@ async function validatedBindings(engine: BrainEngine, sources: SourceRoot[], hos}bindings.push(binding);}- return bindings;+ return { bindings, databaseOnly };}/** Explicit coordinated-upgrade boundary. Refusal records become durable before enabled does. */@@ -126,7 +149,9 @@ export async function activatePersistence(engine: BrainEngine, opts: { confirmQu}const hostId = opts.dryRun ? existingLocalHostId() : localHostId();const sources = await configuredSources(engine);- const initial = await validatedBindings(engine, sources, hostId);+ const writeThrough = writeThroughConfigured(await engine.getConfig('sync.write_through'));+ const { bindings: initial, databaseOnly } = await validatedBindings(engine, sources, hostId, writeThrough);+ const databaseOnlyListing = databaseOnly.length ? { database_only_sources: databaseOnly } : {};let driftAudit: ActivationReport['drift_audit'];if (opts.dryRun) {const { auditCanonicalSource } = await import('./reconcile-audit.ts');@@ -158,10 +183,11 @@ export async function activatePersistence(engine: BrainEngine, opts: { confirmQuawait assertWriterAdminUnlocked(tx);if (current?.enabled) 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 currentWriteThrough = writeThroughConfigured(await tx.getConfig('sync.write_through'));+ const { bindings, databaseOnly: currentDatabaseOnly } = await validatedBindings(tx, currentSources, hostId, currentWriteThrough, true);const identity = (rows: WorktreeBinding[]) => JSON.stringify(rows.map(row => [row.source_id,row.source_incarnation,row.worktree_id,row.owner_host_id,String(row.owner_epoch),String(row.topology_generation),row.relative_path,row.local_path,row.coordination_path]));- if (identity(bindings) !== identity(initial) || JSON.stringify(currentSources) !== JSON.stringify(sources)) {+ if (identity(bindings) !== identity(initial) || JSON.stringify(currentSources) !== JSON.stringify(sources) || JSON.stringify(currentDatabaseOnly) !== JSON.stringify(databaseOnly)) {throw opError('source_changed', 'Source ownership changed during activation; inspect writer status and retry.','Sources or their owners changed while activation ran, so it rolled back and nothing was activated. Inspect the writer status, then rerun gbrain sources writer activate --confirm-quiesced --dry-run before activating again.',{ fix: writerStatusFix('Shows the current sources, owners and registrations, read-only.') });@@ -174,17 +200,20 @@ export async function activatePersistence(engine: BrainEngine, opts: { confirmQuif (legacyLocks.some(row => !opts.cleanupDeadLocalLocks || row.liveness !== 'dead_eligible')) throw quiescence();if ((await tx.executeRaw(`SELECT id FROM persistence_requests WHERE state IN ('queued','running','recovering') OR recovery IS NOT NULL LIMIT 1`)).length|| (await tx.executeRaw('SELECT id FROM persistence_effects WHERE recovery IS NOT NULL LIMIT 1')).length) throw await notQuiescedError(tx, quiescence().message, { queuedEffects: false });- if (opts.dryRun) return { enabled: false, activated: false, filesystem_sources: bindings.length, native_lock: native, legacy_locks: legacyLocks, drift_audit: driftAudit, git_durability: gitDurabilityListing(bindings) };+ if (opts.dryRun) return { enabled: false, activated: false, filesystem_sources: bindings.length, native_lock: native, legacy_locks: legacyLocks, drift_audit: driftAudit, git_durability: gitDurabilityListing(bindings), ...databaseOnlyListing };for (const row of legacyLocks) {if (!(await deleteLockRowExact(tx, row.id, row.holder_pid, row.acquisition_token)).deleted) throw quiescence();}await registerLocalWriter(tx, 'cli');await registerLocalWriter(tx, 'stdio');await tx.executeRaw('UPDATE persistence_brain SET enabled=true,activated_at=COALESCE(activated_at,now()),mode_epoch=mode_epoch+1 WHERE singleton=1');+ // #6449: the sources accepted without an owner; a PGLite write to one of them never runs the automatic first-write claim.+ if (currentDatabaseOnly.length) await tx.setConfig(DATABASE_ONLY_SOURCES_KEY, JSON.stringify(currentDatabaseOnly));+ else await tx.unsetConfig(DATABASE_ONLY_SOURCES_KEY);// Any fsync/marker failure rolls back enabled=true. A conservative stale// refusal record after rollback is safe and cannot grant writer authority.await refreshManagedFilesystemRoots(tx, managedFilesystemDatastorePath(engine));- return { enabled: true, activated: true, filesystem_sources: bindings.length, native_lock: native, legacy_locks: legacyLocks, git_durability: gitDurabilityListing(bindings) };+ return { enabled: true, activated: true, filesystem_sources: bindings.length, native_lock: native, legacy_locks: legacyLocks, git_durability: gitDurabilityListing(bindings), ...databaseOnlyListing };});} finally { for (const lock of locks.reverse()) await lock.release(); }}diff --git a/src/core/persistence/deactivation.ts b/src/core/persistence/deactivation.tsindex 5aeabb242b..591f0f8b17 100644--- a/src/core/persistence/deactivation.ts+++ b/src/core/persistence/deactivation.ts@@ -23,6 +23,7 @@* committed deactivation; a newer or unknown one is kept and reported pending.*/import { randomUUID } from 'node:crypto';+import { DATABASE_ONLY_SOURCES_KEY } from './unbound-source.ts';import { existsSync, lstatSync, readFileSync, readdirSync, unlinkSync } from 'node:fs';import { dirname, join, resolve } from 'node:path';import type { BrainEngine } from '../engine.ts';@@ -273,6 +274,7 @@ export async function deactivatePersistence(engine: BrainEngine, opts: { dryRun?await tx.executeRaw("UPDATE persistence_worktrees SET state='retired' WHERE state<>'retired'");await tx.executeRaw('DELETE FROM persistence_source_bindings');await tx.executeRaw('DELETE FROM persistence_host_bindings');+ await tx.unsetConfig(DATABASE_ONLY_SOURCES_KEY);const sourceRoots = (await tx.executeRaw<{ local_path: string }>('SELECT local_path FROM sources WHERE local_path IS NOT NULL')).map(r => r.local_path);const outcome = { brain_id: current.brain_id, retired_mode_epoch: Number(current.mode_epoch), mode_epoch: Number(epoch.mode_epoch),worktrees: retired.worktrees, source_roots: sourceRoots };diff --git a/src/core/persistence/onboarding.ts b/src/core/persistence/onboarding.tsindex 66a2f25b36..2fdceb7588 100644--- a/src/core/persistence/onboarding.ts+++ b/src/core/persistence/onboarding.ts@@ -7,6 +7,7 @@ import { assertPhysicalRoot } from './physical-root.ts';import { inspectLegacyWriterLocks } from './legacy-locks.ts';import { UNSUPPORTED_MANAGED_BULK_WRITERS } from './maintenance.ts';import { isConnectorSourceKind } from './connector-identity.ts';+import { writeThroughConfigured } from './switches.ts';export function containerPathPreflight(paths: Record<string, string>, mountinfo?: string, container?: boolean) {if (container === undefined) container = existsSync('/.dockerenv') || existsSync('/run/.containerenv');@@ -30,7 +31,7 @@ export async function writerOnboardingPreflight(engine: BrainEngine, sourceId?: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();- const writeThrough = !/^(false|0|off|no)$/i.test(await engine.getConfig('sync.write_through') ?? 'true');+ const writeThrough = writeThroughConfigured(await engine.getConfig('sync.write_through'));const sources = [];for (const row of rows) {const binding = await getWorktreeBinding(engine, row.id, host), configured = row.local_path || (row.id === 'default' ? fallback : null);diff --git a/src/core/persistence/page-mutations.ts b/src/core/persistence/page-mutations.tsindex 6d8cd13b62..b10fb59671 100644--- a/src/core/persistence/page-mutations.ts+++ b/src/core/persistence/page-mutations.ts@@ -30,7 +30,7 @@ import { assertPurgeParams } from './purge-params.ts';import type { Principal, WriteRequest } from './model.ts';import { normalizeSubagentPageInput, undeclaredPageTypeWarning, type PageTypeWarning } from './page-input.ts';import { assertKnowledgePublicationAllowed } from '../shared-skills/knowledge-guard.ts';-import { isUnboundSourcePage, readUnboundWritePolicy, unboundSourceError } from './unbound-source.ts';+import { isUnboundSourcePage, readDatabaseOnlyActivatedSources, readUnboundWritePolicy, unboundSourceError } from './unbound-source.ts';import { colonSlugWindowsRefusal, isWindowsColonTarget } from './native-file-target.ts';import { publishesDatabaseOnly } from './page-prepare.ts';import { cachedPreadmitBrain, dropPreadmitCache, preadmitReads, preadmitRecheckFailed } from './preadmit-cache.ts';@@ -363,7 +363,10 @@ export async function preparePageAdmission(ctx: OperationContext,// (connector_database): a page write never claims it or refuses as unbound.if (writeThrough && root && !binding && isConnectorSourceKind(source.kind)) authority.databaseOnlyReason = 'connector_database';else if (writeThrough && root && !binding) {- if (ctx.engine.kind === 'pglite') binding = await claimWorktree(ctx.engine, sourceId, root, undefined, undefined, { automatic: true });+ // #6449: a source activation listed database-only (sync.write_through was off) is never claimed by a flip of that+ // setting: the write refuses with the claim named (or stays database-only under persistence.unbound_write), as on Postgres.+ const databaseOnlyActivated = ctx.engine.kind === 'pglite' && (await readDatabaseOnlyActivatedSources(ctx.engine)).includes(sourceId);+ if (ctx.engine.kind === 'pglite' && !databaseOnlyActivated) binding = await claimWorktree(ctx.engine, sourceId, root, undefined, undefined, { automatic: true });else {// #5393: the opt-in covers every page mutation whose target has no// recorded canonical file; a revert is also judged on the version it writes.diff --git a/src/core/persistence/switches.ts b/src/core/persistence/switches.tsindex 5caf8bb11a..f4e22bf08a 100644--- a/src/core/persistence/switches.ts+++ b/src/core/persistence/switches.ts@@ -34,6 +34,10 @@ export type WriteSwitches = Record<WriteSwitch, boolean>;export const WRITE_SWITCH_KEYS: readonly string[] = Object.values(WRITE_SWITCHES).map(s => s.key);export const SWITCH_TTL_MS = 5000;+/** `sync.write_through` as the write path and onboarding read it: on unless explicitly off (#6449 shares the predicate with activation). */+export function writeThroughConfigured(value: string | null | undefined): boolean {+ return !/^(false|0|off|no)$/i.test(value ?? 'true');+}const off = (value: string | null | undefined) => typeof value === 'string' && /^(0|false)$/i.test(value.trim());const on = (value: string | null | undefined) => typeof value === 'string' && /^(1|true)$/i.test(value.trim());/** One snapshot read: the switches plus the #6278 preparation budgets (preparation-budget.ts), so a claim never reads config on its own. */diff --git a/src/core/persistence/sync-discovery.ts b/src/core/persistence/sync-discovery.tsindex c0faaa55b1..cb5783798b 100644--- a/src/core/persistence/sync-discovery.ts+++ b/src/core/persistence/sync-discovery.ts@@ -12,6 +12,7 @@ import { isSyncable, isCodeFilePath, isImageFilePath, matchesAnyGlob, resolveSluimport { resolveSlugRootMode } from '../sync-anchor.ts';import { isWriteTargetContained } from '../path-confine.ts';import { getWorktreeBinding, type WorktreeBinding } from './ownership.ts';+import { unboundBindCommand } from './unbound-source.ts';import { localHostId } from './identity.ts';import { sha256 } from './digest.ts';import { isWindowsColonTarget } from './native-file-target.ts';@@ -155,8 +156,13 @@ export async function resolveManagedSyncContext(engine: BrainEngine, opts: SyncOconst binding = await getWorktreeBinding(engine, sourceId);if (!source || source.archived || !binding || binding.source_incarnation !== source.incarnation ||binding.owner_host_id !== localHostId() || binding.state !== 'active' || !binding.local_path) {+ // #6449: a rooted source with no owner at all is the database-only one activation listed; the exit is a deliberate claim.+ const unbound = source && !source.archived && !binding && source.local_path && source.config?.kind == null;throw opError('owner_unavailable', 'Sync must run on the active registered worktree owner.',- `Source ${sourceId} is archived, re-registered, or not bound to an active worktree owned by this host. Run its sync on the owner host that gbrain sources writer status --source ${sourceId} --json names; do not claim or transfer the source to make this host the owner.`,+ unbound+ ? `Source ${sourceId} has a checkout path (${source.local_path}) but no canonical owner, so it is database-only and there is no checkout to sync; nothing changed. `+ + `To make this host its owner (a brain-wide change: ask the user first), preview with gbrain sources writer claim ${sourceId} --path ${source.local_path} --dry-run --json, then ${unboundBindCommand(sourceId, source.local_path)}; afterwards run gbrain sync --no-pull --source ${sourceId}.`+ : `Source ${sourceId} is archived, re-registered, or not bound to an active worktree owned by this host. Run its sync on the owner host that gbrain sources writer status --source ${sourceId} --json names; do not claim or transfer the source to make this host the owner.`,{ fix: { argv: ['gbrain', 'sources', 'writer', 'status', '--source', sourceId, '--json'], consent: [], actor: 'agent', requires_exclusive: false,why: 'Shows the owning host, binding state and incarnation of the source.' } });}diff --git a/src/core/persistence/unbound-source.ts b/src/core/persistence/unbound-source.tsindex d13248860d..83dacd26ad 100644--- a/src/core/persistence/unbound-source.ts+++ b/src/core/persistence/unbound-source.ts@@ -3,8 +3,9 @@ import { opError, OperationError } from '../ops/contract.ts';import type { SqlEngine, WriteRequest } from './model.ts';/**- * #5254: a Postgres page write to a filesystem source with no canonical owner.- * Refused by default; `persistence.unbound_write=database_only` lets every+ * #5254: a Postgres page write to a filesystem source with no canonical owner+ * (#6449: also a PGLite write to a source activation listed database-only,+ * where the automatic first-write claim is off). Refused by default; `persistence.unbound_write=database_only` lets every* page mutation (#5393) write a page with no recorded canonical file to the* database only. Those pages* carry `pages.database_only_reason='unbound_source'` so writes and sync after@@ -19,6 +20,21 @@ export const CONNECTOR_BOUND_HINT = 'Nothing was written. Read the page again anexport const CONNECTOR_BOUND_MESSAGE = 'The connector source gained a canonical owner after this database-only write was accepted.';export const UNBOUND_COLLISION_MESSAGE = 'A database-only page written while its source was unbound already uses this slug.';+/**+ * #6449: the rooted sources `writer activate` accepted without an owner because+ * `sync.write_through` was off (activation.ts writes the list, deactivation+ * clears it). A PGLite page write to one of them never runs the automatic+ * first-write claim, so turning `sync.write_through` back on refuses with the+ * claim named instead of starting to publish files into an unreviewed checkout.+ */+export const DATABASE_ONLY_SOURCES_KEY = 'persistence.database_only_sources';+export async function readDatabaseOnlyActivatedSources(engine: Pick<BrainEngine, 'getConfig'>): Promise<string[]> {+ try {+ const parsed: unknown = JSON.parse(await engine.getConfig(DATABASE_ONLY_SOURCES_KEY) ?? '[]');+ return Array.isArray(parsed) ? parsed.filter((id): id is string => typeof id === 'string') : [];+ } catch { return []; }+}+export function parseUnboundWriteValue(value: string): UnboundWritePolicy {if ((UNBOUND_WRITE_VALUES as readonly string[]).includes(value)) return value as UnboundWritePolicy;throw opError('invalid_params', `${UNBOUND_WRITE_KEY} must be one of: ${UNBOUND_WRITE_VALUES.join(', ')} (got '${value}').`,diff --git a/test/activation-unbound-rooted-6449.test.ts b/test/activation-unbound-rooted-6449.test.tsnew file mode 100644index 0000000000..c869d06741--- /dev/null+++ b/test/activation-unbound-rooted-6449.test.ts@@ -0,0 +1,149 @@+/**+ * #6449: a brain with `sync.write_through=false` is database-only, and `writer+ * status` already reports a rooted source with no canonical owner as+ * `database_only`. Activation disagreed: the same source was refused+ * `writer_registration_required`, so a database-only brain could not enter+ * managed mode without inventing a checkout owner per source.+ *+ * Fix: activation lists such a source under `database_only_sources` and goes+ * ahead; with write_through on, the refusal names the `writer claim`+ * (preview first) and the database-only alternative. [R6] pins the flip:+ * after a database-only activation, turning `sync.write_through` back on must+ * not start an unreviewed first-write claim on the still-unbound source+ * (activation records the listed sources in `persistence.database_only_sources`+ * and the PGLite auto-claim skips them; deactivation clears the list); the+ * write refuses with the claim named, or stays database-only under+ * `persistence.unbound_write`, and no file is ever written. Managed `sync` on+ * that source names the claim too.+ *+ * Contributed by @uncfreak1255-code (diagnosis, #5737).+ */+import { afterAll, beforeAll, expect, test } from 'bun:test';+import { randomUUID } from 'node:crypto';+import { existsSync, mkdirSync, mkdtempSync, readdirSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import type { BrainEngine } from '../src/core/engine.ts';+import type { OperationContext } from '../src/core/operations.ts';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { activatePersistence } from '../src/core/persistence/activation.ts';+import { writerOnboardingPreflight } from '../src/core/persistence/onboarding.ts';+import { managedPersistenceEnabled } from '../src/core/persistence/ownership.ts';+import { submitPageMutation } from '../src/core/persistence/page-mutations.ts';+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';+import { resolveManagedSyncContext } from '../src/core/persistence/sync-discovery.ts';+import { deactivatePersistence } from '../src/core/persistence/deactivation.ts';+import { DATABASE_ONLY_SOURCES_KEY } from '../src/core/persistence/unbound-source.ts';+import { withEnv } from './helpers/with-env.ts';+import { testBackends } from './helpers/test-backends.ts';+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';++const logger = { info() {}, warn() {}, error() {} };+const backends = testBackends();+const engines: BrainEngine[] = [];+const dataDir = mkdtempSync(join(tmpdir(), 'gbrain-6449-db-'));+let closePostgres: (() => Promise<void>) | undefined;++beforeAll(async () => {+ if (backends.includes('pglite')) {+ const engine = new PGLiteEngine();+ await engine.connect({ database_path: dataDir }); await engine.initSchema(); engines.push(engine);+ }+ if (backends.includes('postgres')) {+ const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL!);+ engines.push(pg.engine); closePostgres = pg.close;+ }+}, 120_000);+afterAll(async () => {+ for (const engine of engines) { await disposePersistenceConsumer(engine); await engine.disconnect(); }+ await closePostgres?.(); rmSync(dataDir, { recursive: true, force: true });+});++type Outcome = { state: string; code?: string; detail?: string; suggestion?: string; write_through?: { skipped?: string } };+const outcome = (promise: Promise<unknown>): Promise<Outcome> => promise.then(+ receipt => receipt as Outcome,+ (error: { code?: string; detail?: string; suggestion?: string }) => ({ state: 'refused', code: error.code, detail: error.detail, suggestion: error.suggestion }));++test('a rooted unbound source activates database-only when write_through is off; the flip never starts writing files', async () => {+ for (const engine of engines) await databaseOnlyActivation(engine);+}, 240_000);++async function databaseOnlyActivation(engine: BrainEngine): Promise<void> {+ const dir = mkdtempSync(join(tmpdir(), 'gbrain-6449-'));+ const root = join(dir, 'vault'); mkdirSync(root);+ const sourceId = `vault-${randomUUID().slice(0, 8)}`;+ try {+ await withEnv({ GBRAIN_HOME: join(dir, 'home'), DATABASE_URL: engine.kind === 'postgres' ? process.env.DATABASE_URL : undefined, GBRAIN_DATABASE_URL: undefined }, async () => {+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');+ await engine.executeRaw('INSERT INTO sources(id,name,local_path) VALUES($1,$1,$2)', [sourceId, root]);+ const bindings = async () => engine.executeRaw('SELECT source_id FROM persistence_source_bindings WHERE source_id=$1', [sourceId]);+ const sourceStatus = async () => (await writerOnboardingPreflight(engine)).sources.find(s => s.source_id === sourceId)?.state;+ // Managed mode fences every recorded source path from unmanaged writers with its `.gbrain-managed` marker (filesystem-guard.ts); that+ // marker is the only thing that may ever appear under a database-only root. No page file does.+ const filesUnderRoot = () => readdirSync(root).filter(name => name !== '.gbrain-managed');++ // write_through on: the refusal stands, and now names the claim (preview first) and the database-only alternative.+ await engine.setConfig('sync.write_through', 'true');+ expect(await sourceStatus()).toBe('claim_required');+ const refused = await outcome(activatePersistence(engine, { confirmQuiesced: true, dryRun: true }));+ expect(refused).toMatchObject({ state: 'refused', code: 'writer_registration_required' });+ expect(refused.suggestion).toContain(`gbrain sources writer claim ${sourceId} --path ${root} --dry-run --json`);+ expect(refused.suggestion).toContain('gbrain config set sync.write_through false');+ expect(await managedPersistenceEnabled(engine)).toBe(false);++ // write_through off: status says database_only and activation now agrees (before the fix: writer_registration_required).+ await engine.setConfig('sync.write_through', 'false');+ expect(await sourceStatus()).toBe('database_only');+ expect(await activatePersistence(engine, { confirmQuiesced: true, dryRun: true }))+ .toMatchObject({ enabled: false, activated: false, filesystem_sources: 0, database_only_sources: [sourceId] });+ expect(await managedPersistenceEnabled(engine)).toBe(false);+ expect(await activatePersistence(engine, { confirmQuiesced: true }))+ .toMatchObject({ enabled: true, activated: true, filesystem_sources: 0, database_only_sources: [sourceId] });+ expect(await managedPersistenceEnabled(engine)).toBe(true);+ expect(await bindings()).toEqual([]);+ expect(JSON.parse((await engine.getConfig(DATABASE_ONLY_SOURCES_KEY))!)).toEqual([sourceId]);++ // A page write lands database-only with the explicit reason; nothing is written under the root.+ const ctx = { engine, sourceId, remote: false, config: { engine: engine.kind, embedding_disabled: true } as never, dryRun: false, logger } as OperationContext;+ const put = (slug: string, content: string) => outcome(submitPageMutation(ctx, { operation: 'put_page', params: { slug, request_id: randomUUID(), content } }));+ const content = (body: string) => `---\ntype: note\ntitle: Database Only Note\n---\n# Database Only Note\n\n${body}\n`;+ expect(await put('notes/database-only', content('Stored while write_through is off.'))).toMatchObject({ state: 'committed', write_through: { skipped: 'disabled_by_config' } });+ expect(filesUnderRoot()).toEqual([]);++ // [R6] The flip: write_through back on must not auto-claim the source activation accepted database-only.+ await engine.setConfig('sync.write_through', 'true');+ expect(await sourceStatus()).toBe('claim_required');+ const flipped = await put('notes/after-flip', content('Written after the flip.'));+ expect(flipped).toMatchObject({ state: 'refused', code: 'owner_unavailable', detail: 'unbound_source' });+ expect(flipped.suggestion).toContain(`gbrain sources writer claim ${sourceId}`);+ expect(await bindings()).toEqual([]);+ expect(filesUnderRoot()).toEqual([]);+ expect(await engine.executeRaw('SELECT slug FROM pages WHERE source_id=$1 AND slug=$2', [sourceId, 'notes/after-flip'])).toEqual([]);++ // The documented alternative keeps the source database-only under the opt-in; still no claim and no file.+ await engine.setConfig('persistence.unbound_write', 'database_only');+ expect(await put('notes/after-flip', content('Written after the flip.'))).toMatchObject({ state: 'committed', write_through: { skipped: 'unbound_source' } });+ await engine.setConfig('persistence.unbound_write', 'refuse');+ expect(await bindings()).toEqual([]);+ expect(filesUnderRoot()).toEqual([]);++ // Managed sync on the unbound source refuses as before, and the hint names the claim instead of forbidding it.+ const sync = await outcome(resolveManagedSyncContext(engine, { sourceId, noPull: true } as never));+ expect(sync).toMatchObject({ state: 'refused', code: 'owner_unavailable' });+ expect(sync.suggestion).toContain(`gbrain sources writer claim ${sourceId} --path ${root} --dry-run --json`);+ expect(sync.suggestion).not.toContain('do not claim');+ expect(existsSync(root)).toBe(true);++ // Deactivation clears the list; back in classic mode the ordinary PGLite first-write claim applies again.+ await engine.setConfig('sync.write_through', 'false');+ await engine.executeRaw("DELETE FROM persistence_effects WHERE state='queued'");+ expect(await deactivatePersistence(engine, { requestId: randomUUID() })).toMatchObject({ mode: 'classic', deactivated: true });+ expect(await engine.getConfig(DATABASE_ONLY_SOURCES_KEY)).toBeNull();+ });+ } finally {+ await disposePersistenceConsumer(engine);+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');+ await engine.executeRaw('DELETE FROM pages WHERE source_id=$1', [sourceId]).catch(() => {});+ rmSync(dir, { recursive: true, force: true });+ }+}diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txtindex d1c35735ae..099b0250d2 100644--- a/test/postgres-unit-arms.txt+++ b/test/postgres-unit-arms.txt@@ -11,6 +11,7 @@# file is a one-line edit: insert its path in sorted order. Shards balance# other Postgres lane runs. The unit, serial and slow lanes unset# themselves from scripts/postgres-arm-weights.json.+test/activation-unbound-rooted-6449.test.tstest/alias-source-cascade-5094.test.tstest/attribution-backfill-history.test.tstest/behavior-change-notice.test.ts