Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(persistence): let writer deactivate release a source claimed before activation (#6122)

garrytan6bd0314c960b
diff --git a/docs/architecture/key-files/core-persistence.md b/docs/architecture/key-files/core-persistence.md
index ffadd5611a..98573a4ed8 100644
--- a/docs/architecture/key-files/core-persistence.md
+++ b/docs/architecture/key-files/core-persistence.md
@@ -10,7 +10,8 @@ Connector ingestion, item holds and checkpoint validation continue in [Core Pers
- `src/core/persistence/authority.ts` — durable write authority. `submissionAuthority` records the caller's grant ceiling on every write request (scopes, operations, slug prefixes, delegated namespace and, for a delegated job, its native `subagentId` when a positive safe integer); `authorizeWrite` re-checks it against the CURRENT principal at publication and replay. For a delegated OAuth client the current namespace is the stored `delegated_slug_prefixes` in `prefixes` mode, or only `wiki/agents/<retained subagentId>/*` for the native `job` form (prefixes NULL); anything else allows nothing, and it always intersects the original accepted prefixes, bound tools, scope and source, so a revoked, narrowed or switched grant or a foreign or invalid job id denies (`test/persistence-page-authority.test.ts`, Postgres: `test/e2e/minions-authority-parity.test.ts`).
- `src/core/persistence/activation.ts` — private CLI `sources writer activate --confirm-quiesced` boundary. Verifies native capability and active filesystem bindings, takes root locks before DB waits and rechecks topology under transaction guards before enabling managed writes. Live/young/foreign legacy leases refuse regardless of expiry; only explicitly requested `--cleanup-dead-local-locks` removes exact dead same-host holders, under the lease transaction lock. Dry-run reports candidates without deletion. Registration never silently claims a source. Tests: `test/persistence-activation.test.ts`, `test/persistence-onboarding.test.ts`. Unbound Google/GitHub API sources may activate as reviewed `connector_database` without fabricating a Git root, while bound sources still require canonical physical-root checks. Activation increments `persistence_brain.mode_epoch` (migration 183), which the writer admin-state hash includes. A non-connector source whose recorded `local_path` no longer exists (unclaimed, or claimed by this host) refuses `source_changed` with detail `source_path_missing`, naming the source, the path and the `sources set-path` / `sources remove` exits (the claimed checkout filled in), in `--dry-run` too (#5206, `test/activation-missing-source-path.test.ts`).
-- `src/core/persistence/deactivation.ts` — private CLI `sources writer deactivate` (#5455/#5628), brain-wide and trusted-local. `deactivationBlockers` lists the admin lock, queued/running/recovering requests, recovering topology changes, uncommitted effects, held connector items (managed holds that classic mode would not read) and live `gbrain_cycle_locks` leases, each with its CLI exit; `--dry-run` returns them plus the worktrees that would retire, the kept shared-skill settings and, when clean, `apply_command` bound to the admin state read before the preview. `deactivatePersistence` takes the local native worktree locks, then in one transaction locks `persistence_brain FOR UPDATE`, checks the expected admin state and the admin lock, locks worktrees then sources `FOR UPDATE` (admission's order), rechecks the blockers, sets `enabled=false`, increments `mode_epoch`, retires every worktree, deletes source and host bindings and records a committed `writer_deactivate` topology change (brain id, retired epoch, retired worktree ids and roots, source roots). `cleanupRetiredManagedMarkers` runs on CLI connect, after deactivate and from `writer status`: it removes this brain's registry records, `.gbrain-managed` / Git `gbrain-managed.json`, `.gbrain-owner.json` and reservations only when their `mode_epoch` is a retired one below the current epoch, or, without an epoch, their worktree id (or, for markers without one, their root outside any active binding) is recorded as retired; unknown or newer epochs are kept and reported `pending`, each file is re-read before unlinking and other brains' files are never touched. `root-registry.ts` writes `mode_epoch` into new registry records and managed markers. Tests: `test/persistence-deactivate.test.ts` (PGLite and Postgres), `test/e2e/persistence-deactivate-race.test.ts`.
+- `src/core/persistence/deactivation.ts` — private CLI `sources writer deactivate` (#5455/#5628), brain-wide and trusted-local. `deactivationBlockers` lists the admin lock, queued/running/recovering requests, recovering topology changes, uncommitted effects, held connector items (managed holds that classic mode would not read) and live `gbrain_cycle_locks` leases, each with its CLI exit; `--dry-run` returns them plus the worktrees that would retire, the kept shared-skill settings and, when clean, `apply_command` bound to the admin state read before the preview. `deactivatePersistence` takes the local native worktree locks, then in one transaction locks `persistence_brain FOR UPDATE`, checks the expected admin state and the admin lock, locks worktrees then sources `FOR UPDATE` (admission's order), rechecks the blockers, sets `enabled=false`, increments `mode_epoch`, retires every worktree, deletes source and host bindings and records a committed `writer_deactivate` topology change (brain id, retired epoch, retired worktree ids and roots, source roots). `cleanupRetiredManagedMarkers` runs on CLI connect, after deactivate and from `writer status`: it removes this brain's registry records, `.gbrain-managed` / Git `gbrain-managed.json`, `.gbrain-owner.json` and reservations only when their `mode_epoch` is a retired one below the current epoch, or, without an epoch, their worktree id (or, for markers without one, their root outside any active binding) is recorded as retired; unknown or newer epochs are kept and reported `pending`, each file is re-read before unlinking and other brains' files are never touched. `root-registry.ts` writes `mode_epoch` into new registry records and managed markers. Tests: `test/persistence-deactivate.test.ts` (PGLite and Postgres), `test/e2e/persistence-deactivate-race.test.ts`. #6122: on a brain whose managed persistence was never activated, `--dry-run` reports the real `source_bindings` and each claim as `pre_activation_claims` (and `apply_command` when clean), and the state-bound run releases them through `pre-activation-release.ts`; with no claims a rerun still only cleans retired markers. Tests: `test/persistence-preactivation-claim.test.ts`.
+- `src/core/persistence/pre-activation-release.ts` — #6122: `preActivationClaims` lists the source bindings of a never-activated brain with their roots; `releasePreActivationClaims` (called by `deactivatePersistence` on a disabled brain once `deactivationBlockers` is empty) takes the local worktree locks, then in one transaction checks the admin state, the admin lock and that the brain is still disabled, re-runs the blockers, retires the claimed worktrees, deletes the source and host bindings and records a committed `writer_deactivate` change with `outcome.pre_activation: true`, so `cleanupRetiredManagedMarkers` clears this host's claim markers. It ensures the CLI writer registration first (a never-activated brain may have none). `sync-authority.ts` `resolveSyncPersistenceMode` refuses such a claimed source with an agent-first `writer_coordinator_required`: both choices in the suggestion, `fix` the state-bound release (`consent: ['destructive']`, so `ask_user`, with the dry run as `preview_argv`).
- `src/core/persistence/{admin-lock,blocking-effects,writer-versions}.ts` — `admin-lock.ts` owns the opt-in brain-level writer admin lock: reserved config key `persistence.writer_admin_lock` (`{locked, set_at, host_id, generation}`), written only by local `gbrain sources writer lock|unlock` under the `persistence_brain` row `FOR UPDATE`; lock refuses while a prepared transfer is unaccepted. `assertWriterAdminUnlocked` runs inside the claim, managed claim, activation, shared-skill activation and transfer prepare/accept transactions for every caller (share lock on the brain row) and refuses with `writer_admin_locked`; only the ordinary first-write auto-claim (`claimWorktree(..., { automatic: true })` from page and memory mutations) is exempt. Generic `config set`/`unset`/`unset --pattern` refuse the key; engine migration copies it. It is not a security boundary and older binaries ignore it. `blocking-effects.ts` lists queued, running or recovering effects (`listBlockingEffects`) and builds `writer_not_quiesced` suggestions naming the first blocking request or effect with `gbrain sources writer status <source> --json`. `writer-versions.ts` stamps admitter version/host at admission and consumer version/host/`published_at` only on committed publication (migration 178, cutoff `persistence_brain.writer_version_cutoff` on the database clock); replay and compaction keep stamps. `sources writer status` reports `admin_lock`, `local_host_id`, `blocking_effects` and `writer_versions`; `src/commands/doctor/checks/writer-version.ts` is the seven-day `writer_version` advisory. Tests: `test/persistence-writer-admin-lock.test.ts`, `test/persistence-writer-versions.test.ts`, `test/persistence-blocking-effects.test.ts`, `test/e2e/persistence-writer-{admin-lock,stamps}.test.ts`.
@@ -55,7 +56,7 @@ Connector ingestion, item holds and checkpoint validation continue in [Core Pers
- `src/core/persistence/{schema,model,journal,authority,identity,ownership,coordinator,consumer,service,page-mutations,page-prepare,source-storage,control,context,digest,prepared-import}.ts` — dedicated durable mutation admission and permanent principal-scoped replay IDs, atomic quota reservations, registered canonical worktree ownership, native lock publication, conditional file recovery, and coherent receipt completion. Recovery presence blocks its whole worktree even when the receipt is terminal; admission and publication both enforce the fence. A file write is not claimed while a queued or running withdrawal mirror targets its page (any page, for an untargeted mirror), so the mirror cannot rewrite the file under an accepted request; when file bytes differ from preparation and the page revision also moved, publication reprepares (`revision_conflict`) instead of refusing as `raw_file_changed`, which stays the outcome for changed bytes at an unchanged revision (`test/withdrawal-followup-writes.test.ts`). Migration 159 adds a partial worktree/sequence recovery index so permanent receipt retention does not turn the fence into a history scan. Canonical file preparation honors a recorded source path or contained absolute capture file URI within the registered owner root (relative or host-only `file://` URIs are absent); symlink confinement and coherent snapshot checks still apply. A slug under a `storage.db_only` dir declared in `gbrain.yml` (matched case-insensitively, derive-phase defaults excluded) publishes database-only when a live page's file is absent (the case that otherwise refuses as an uncoordinated removal), with receipt `write_through.skipped: db_only`; new pages, tombstones, missing-file-tolerant callers and present cache files keep the full file treatment and never read `gbrain.yml`. `gbrain.yml` is read from the source root, like doctor, export and backup, not the git root `manageGitignore` uses, which differs for a monorepo-subdir source. `source-storage.ts` caches the parsed file per version and logs an invalid one (unreadable, overlapping tiers, db_only declared in syntax that resolves nothing) once; that missing-file refusal then reports `storage_error`, and the Git effect treats the page as not db_only. The drift guard applies the import rule for a file without an explicit `type:` (the stored type stands) and compares titles trimmed, as the parser reads them; a real drift refuses with `detail: file_database_drift` and a filled `sources reconcile` command; when sync holds the page's file (`sync-holds.ts`), the drift and occupied-path refusals name the hold instead (location-free message from `verb-errors.ts` `heldFileMessage`, mapped back by `heldFileDiagnostic` in receipts and `service.ts`) and its repair, and the page stays read-only for put_page until the file is repaired. The first write that binds an origin in a Git-subdirectory source with no slug-root pin pins the inferred mode in its publication transaction (a concurrent different pin refuses with `revision_conflict`), so later pages cannot flip the inference. A new page captured from a file inside the source (`capture_path`, resolved from the trusted CLI `local_file` in `page-mutations`, only when sync would give that file the capture slug under the source's slug-root mode) publishes to that file when its bytes are exactly the captured input; otherwise capture records `source_uri: cli-file`, never a host path. `acquireWorktree(binding, waitMs, signal, engine)` re-stamps a device-only physical-root change under the native lock (see `physical-root.ts`); without an engine, or when birth time is zero, it refuses with `detail: physical_root_device_changed` and the filled self-transfer commands. Version snapshots retain nullable `is_deleted`: new snapshots restore recorded deletion state atomically with content, tags, files and receipts; legacy NULL preserves current deletion state. Canonical no-op detection compares deletion state as well as content. Page replacement preconditions are checked before no-op detection; providers prepare outside publication transactions; recovery never restores unexpected bytes. Local registrations retain immutable CLI/stdio trust lanes and hashed credentials; accepted authority is intersected with current grants. `limits.ts` reads every `persistence.limits.*` cap and `persistence.receipt_retention_days` (default 30) from the database config table (`JOURNAL_CONFIG_KEYS`, registered for `gbrain config set`; malformed values are rejected at set time). Cumulative defaults (250,000 lifetime IDs and 1.5 GiB receipt bytes per principal, 8 GiB brain receipt bytes) cover 600 admissions a day for a year; each admission reserves at least 16 KiB and a compacted receipt keeps about 4 KiB. A cumulative `queue_capacity` refusal names its key in `detail` and suggests a `gbrain config set` value covering one more year at the recent admission rate (`oneYearCapacity`). Compaction filters out receipts with unfinished effects before its batch limit. `test/persistence-journal.test.ts` exercises real PGLite and optional guarded Postgres admission, cancellation, compaction, conflict and publication recovery; `test/persistence-capacity.test.ts` covers retention, the compaction filter, capacity hints and default sizing. `service.ts` also dispatches operation `decide_proposal` (S9 proposal accept/undo) to `facts/proposal-supersede.ts`. GOOGLE PUBLISH MODE: a page target is a `PageMutationFile` (`MutationFile` plus optional `publishMode`). The Google callers set `publishMode: 0o600` at prepare time from the stored connector (`prepareConnectorMutation` in `connector-sync.ts` when `p.connector === 'google'`, and `prepareGoogleReceiptPatch`); it is never part of the submitted intent, so request ids are unchanged. `publishFile` then creates missing directories with `mkdirPrivate(dirname(path), root)` (0700) instead of `mkdirSync` and opens the stage with `mode ?? publishMode` through `AtomicWriteOpts.mode`, so a rewrite of a legacy 0644 page lands 0600. Restoration keeps restoring the journaled before-mode and opens its stage with it (the post-flush chmod stays), so a restored private page is never staged wider than its mode.
- `src/core/persistence/protocol.ts` — the persistence protocol declaration and the global row-lock order: the `persistence_brain` row, then worktree rows (id order), then source rows (id order), then `persistence_counters`, request rows and page keys. The request and effect protocol triggers (`shared-skills/persistence-schema.ts`) read the brain row FOR SHARE, and worktree claims, topology changes (`lockTopologyRows`, then `settleTopologyRequests` locks the `brain` counter) and activation hold it FOR UPDATE before their worktrees, sources and counters. So `declarePersistenceProtocol` and `declareDurablePersistence` take the brain row FOR SHARE in the same statement as their settings (after `lock_timeout`, a missing row still declares), and every journal transaction declares before any other row lock: admission, publication, recovery, completion, cancellation (`control.ts`), `forget` (`memory-mutations.ts`), connector retry approval, embedding effect retry and settlement, and withdrawal-target upgrades (`effect-targets.ts`). A transaction that needs the brain row FOR UPDATE takes it first and declares after it (`skill-activation.ts`). Before this order, an ordinary write that locked its source and counters before the trigger's brain read inverted against a concurrent claim or topology change and ended in a 1 s `lock_timeout` (or a deadlock), a retry, and writes left pending. Tests: `test/e2e/persistence-publish-lock-order-postgres.test.ts` (paused topology change and a claim/topology race, direct and through PgBouncer), the crash robot's `brain_before_rows` rule (`scripts/persistence/lock-order.ts`, `test/persistence-crash-robot.test.ts`).
-- `src/core/persistence/unbound-source.ts` — #5254 policy for a Postgres page write to a filesystem source (`local_path`, or `sync.repo_path` for `default`) with default write-through and no worktree binding. `submitPageMutation` refuses `owner_unavailable` with `detail: unbound_source`, a `docs` pointer to `write-refusals.md#unbound-sources-on-postgres`, and a hint naming the filled `sources writer status`/`writer claim ... --admin-intent writer_claim --expected-state <admin_state>` bind command (host path only for trusted local callers) and, for `put_page` to a page without `source_path`, `gbrain config set persistence.unbound_write database_only`. That key (`refuse` default, validated by `config set`; any other stored value refuses) lets such a `put_page` admit with `databaseOnlyReason: 'unbound_source'`. Publication rechecks inside its transaction, after `authorizeStoredRequest` share-locks the source row, that the source is still unbound and the page still has no `source_path` (else `owner_unavailable`/`unbound_source`, hint rebuilt from the persisted message by `writeResponse`), then stamps `pages.database_only_reason='unbound_source'` (migration 177). After binding, `prepareFileTarget` keeps a stamped page with no file database-only (receipt `write_through.skipped: unbound_source` with a warning) and managed sync refuses to import a file at its path (`source_changed`, diagnostic reason `unbound_source`). PGLite keeps auto-claiming. Tests: `test/e2e/unbound-source-postgres.test.ts`, `test/persistence-unbound-source.test.ts`.
+- `src/core/persistence/unbound-source.ts` — #5254 policy for a Postgres page write to a filesystem source (`local_path`, or `sync.repo_path` for `default`) with default write-through and no worktree binding. `submitPageMutation` refuses `owner_unavailable` with `detail: unbound_source`, a `docs` pointer to `write-refusals.md#unbound-sources-on-postgres`, and a hint naming the filled `sources writer status`/`writer claim ... --admin-intent writer_claim --expected-state <admin_state>` bind command (host path only for trusted local callers) and, for `put_page` to a page without `source_path`, `gbrain config set persistence.unbound_write database_only`. That key (`refuse` default, validated by `config set`; any other stored value refuses) lets such a `put_page` admit with `databaseOnlyReason: 'unbound_source'`. Publication rechecks inside its transaction, after `authorizeStoredRequest` share-locks the source row, that the source is still unbound and the page still has no `source_path` (else `owner_unavailable`/`unbound_source`, hint rebuilt from the persisted message by `writeResponse`), then stamps `pages.database_only_reason='unbound_source'` (migration 177). After binding, `prepareFileTarget` keeps a stamped page with no file database-only (receipt `write_through.skipped: unbound_source` with a warning) and managed sync refuses to import a file at its path (`source_changed`, diagnostic reason `unbound_source`). PGLite keeps auto-claiming. Tests: `test/e2e/unbound-source-postgres.test.ts`, `test/persistence-unbound-source.test.ts`. #6122: on a brain whose managed persistence is not activated, the hint offers editing the page's file plus `gbrain sync --source <id>` (and `persistence.unbound_write=database_only` where it applies) instead of the claim, and says a claim alone would block classic sync until activation or `gbrain sources writer deactivate`.
- `src/core/persistence/{semantic,semantic-pages}.ts` — revision-bound semantic tag/timeline merges through the journal. Supported merges reprepare against a newer snapshot; exact timeline replay leaves canonical bytes, revision, versions and structured rows unchanged. The public timeline handler resolves durable replay before page-existence preflight, retaining original outcomes after page purge or recreation; fresh writes preserve same-source diagnostics. `page-state/projections.ts` completes sanitized text and page search vectors together, and installs delayed embeddings with UPDATE-only revision/chunk/text/index-context checks. New vectors receive the full provider:model captured before provider execution, and a runtime model switch invalidates the prepared indexing context. Metadata updates preserve the sanitized vector. Tests: `persistence-semantic-pages.test.ts`, `page-projection-concurrency.test.ts`.
diff --git a/docs/architecture/topologies.md b/docs/architecture/topologies.md
index e94f8ccc51..b30b8827cb 100644
--- a/docs/architecture/topologies.md
+++ b/docs/architecture/topologies.md
@@ -548,6 +548,19 @@ is classic. Reactivation is the normal claim and activate runbook above.
**Say to your agent:** *"Switch this brain back to classic mode, but show me the
dry run first."*
+<a id="pre-activation-claims"></a>**A source claimed before activation.** Claiming a source fences classic
+`gbrain sync` of it even while managed persistence was never activated, so sync
+refuses `writer_coordinator_required` (#6122). On such a brain, the dry run
+reports the claims as `pre_activation_claims` (with `source_bindings` counting
+them) and, when nothing blocks, an `apply_command`; running it releases every
+claim: the claimed worktrees are retired, source and host bindings are removed
+and a committed `writer_deactivate` receipt (`outcome.pre_activation: true`) is
+recorded. The brain stays classic and its mode epoch does not change; the next
+`gbrain sync` runs in classic mode, and the source can be claimed again later.
+The CLI writer registration that receipt needs is created if the brain has none
+yet, as activation would. The other choice is to finish the claim and activate
+runbook above.
+
1. Quiesce every writer on every host, as for activation: stop `gbrain serve`,
pause autopilot with `gbrain autopilot pause --reason "writer deactivation"`,
and let queued writes finish.
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index 165a9f3d65..114c7eaa07 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -258,6 +258,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText }
{ since: '0.60.98.0', text: 'Managed sync now holds a file whose facts or takes fence cannot be imported (code `invalid_fence`; `gbrain sources status <id>` names the fence, section and rows) instead of blocking the whole source, and a source such a fence blocked before recovers on its next sync. Coordinated writes refuse such a fence with `invalid_fence` (wire `error` stays `invalid_params`, or `take_row_collision`). `gbrain config set sync.holds fail` keeps fail-closed blocking.' },
{ since: '0.60.99.0', text: 'Fixable facts and takes fences are now rewritten instead of held or refused: managed sync, put_page and the fact and take writers normalize a fence whose meaning is unambiguous (a missing end marker after the table, two-dash takes markers, zero or duplicate row numbers, header aliases, invented kinds and enum synonyms, assistant holders, percent confidences) without changing a claim or an existing row number, and managed sync commits the rewritten file. Results report `fences_normalized`; `gbrain sync --dry-run` lists `would_normalize`. `gbrain config set fences.normalize false` turns it off (such fences are then held or refused).' },
{ since: '0.0.0-wave11', text: 'Doctor\'s new `persistence_write_stall` check warns when a managed write has held its claim longer than `persistence.max_claim_ms` (default 10 minutes) and names the stuck phase; `gbrain sources writer status --json` shows each running request\'s `claim` phase.' },
+ { since: '0.0.0-wave11', text: 'On a brain whose managed persistence was never activated, `gbrain sources writer deactivate` now releases sources claimed before activation (the dry run lists them as `pre_activation_claims`), so classic `gbrain sync` of them works again; `gbrain sources writer deactivate --dry-run --json` previews it.' },
];
/** The newest disclosed change's release: the notice id moves only when a release adds rows. */
diff --git a/src/core/persistence/administration.ts b/src/core/persistence/administration.ts
index cf65fc3a5f..06511a841f 100644
--- a/src/core/persistence/administration.ts
+++ b/src/core/persistence/administration.ts
@@ -270,7 +270,7 @@ export async function runPersistenceAdministration(engine: BrainEngine, operatio
const state = await writerAdminState(engine);
const report = await deactivatePersistence(engine, { dryRun: true });
const unchanged = state === await writerAdminState(engine);
- return { ...report, action: operation, ...(report.mode === 'managed' && report.blockers.length === 0 && unchanged
+ return { ...report, action: operation, ...((report.mode === 'managed' || report.pre_activation_claims?.length) && report.blockers.length === 0 && unchanged
? { apply_command: `gbrain sources writer deactivate --admin-intent writer_deactivate --expected-state ${state}` } : {}) };
}
let expectedState: string | undefined;
diff --git a/src/core/persistence/deactivation.ts b/src/core/persistence/deactivation.ts
index 58dfcb3e71..9cddb93a28 100644
--- a/src/core/persistence/deactivation.ts
+++ b/src/core/persistence/deactivation.ts
@@ -40,6 +40,7 @@ import { lockTopologyPrincipal, topologyPrincipal } from './topology-locks.ts';
import { canonicalFilesystemPath } from './root-registry.ts';
import { carryHoldsToClassicState, holdCarryBlocked, planHoldCarry, type HoldCarry } from '../connectors/item-holds-store.ts';
import { PHYSICAL_ROOT_MARKER, physicalRootReservationPath } from './physical-root-record.ts';
+import { preActivationClaims, releasePreActivationClaims, type PreActivationClaim } from './pre-activation-release.ts';
export const DEACTIVATE_DOCS = 'docs/architecture/topologies.md#deactivate-runbook';
@@ -71,6 +72,8 @@ export interface DeactivationReport {
blockers: DeactivationBlocker[];
/** Held connector items copied (or, on a dry run, to be copied) into each source's classic state file. */
carried_holds?: HoldCarry[];
+ /** #6122: on a never-activated brain, the claimed sources a deactivation releases (dry run) or released. */
+ pre_activation_claims?: PreActivationClaim[];
local_markers?: LocalMarkerReport;
}
@@ -175,9 +178,19 @@ export async function deactivatePersistence(engine: BrainEngine, opts: { dryRun?
const kept = await keptSettings(engine, brain);
const base = { dry_run: opts.dryRun === true, retired_worktrees: topology.worktrees, source_bindings: topology.bindings, kept };
if (!brain.enabled) {
- // A disabled brain has nothing to convert; a rerun only clears this host's retired markers.
- return { ...base, mode: 'classic', deactivated: false, mode_epoch: Number(brain.mode_epoch), retired_worktrees: [], source_bindings: 0, blockers: [],
- ...(opts.dryRun ? {} : { local_markers: await cleanupRetiredManagedMarkers(engine) }) };
+ // #6122: a disabled brain has no managed mode to convert, but sources claimed before activation fence classic sync;
+ // deactivate releases them. Without claims a rerun only clears this host's retired markers.
+ const claims = await preActivationClaims(engine);
+ const classic = { ...base, mode: 'classic' as const, deactivated: false, mode_epoch: Number(brain.mode_epoch) };
+ if (!claims.length) return { ...classic, retired_worktrees: [], blockers: [], ...(opts.dryRun ? {} : { local_markers: await cleanupRetiredManagedMarkers(engine) }) };
+ const blockers = await deactivationBlockers(engine);
+ if (opts.dryRun) return { ...classic, retired_worktrees: [], blockers, pre_activation_claims: claims };
+ if (blockers.length) throw blockedError(blockers);
+ const released = await releasePreActivationClaims(engine, { expectedState: opts.expectedState, requestId: opts.requestId,
+ blocked: async tx => { const inside = await deactivationBlockers(tx); return inside.length ? blockedError(inside) : null; } });
+ const worktrees = [...new Set(released.map(claim => claim.worktree_id))];
+ return { ...classic, retired_worktrees: worktrees.map(id => ({ id, roots: [...new Set(released.filter(c => c.worktree_id === id).flatMap(c => c.roots))] })),
+ blockers: [], pre_activation_claims: released, local_markers: await cleanupRetiredManagedMarkers(engine) };
}
const blockers = await deactivationBlockers(engine);
if (opts.dryRun) {
diff --git a/src/core/persistence/page-mutations.ts b/src/core/persistence/page-mutations.ts
index 8a16eaf9a0..eaaa6ff896 100644
--- a/src/core/persistence/page-mutations.ts
+++ b/src/core/persistence/page-mutations.ts
@@ -17,7 +17,7 @@ import { admitWrite, assertPageRequestIdentity, assertReplayIntent, getWriteRequ
import { submissionAuthority, authorizeStoredRequest } from './authority.ts';
import { currentVerifiedLocalWriter, localHostId, readLocalWriter, registerLocalWriter, withVerifiedLocalRegistration } from './identity.ts';
import type { BrainEngine } from '../engine.ts';
-import { claimWorktree, getWorktreeBinding } from './ownership.ts';
+import { claimWorktree, getWorktreeBinding, managedPersistenceEnabled } from './ownership.ts';
import { parseMutationPrecondition } from './preconditions.ts';
import { assertPurgeParams } from './purge-params.ts';
import type { Principal, WriteRequest } from './model.ts';
@@ -288,7 +288,7 @@ export async function preparePageAdmission(ctx: OperationContext,
&& (await ctx.engine.executeRaw<{ source_path: string | null }>('SELECT source_path FROM page_versions WHERE id=$1 AND page_id=$2',
[p.version_id, snapshot.page.id]))[0]?.source_path);
if (fileBacked || await readUnboundWritePolicy(ctx.engine) !== 'database_only') {
- throw unboundSourceError(sourceId, ctx.remote === false ? root : null, fileBacked ? 'file_backed' : 'database_only_eligible');
+ throw unboundSourceError(sourceId, ctx.remote === false ? root : null, fileBacked ? 'file_backed' : 'database_only_eligible', !await managedPersistenceEnabled(ctx.engine));
}
authority.databaseOnlyReason = 'unbound_source';
}
diff --git a/src/core/persistence/pre-activation-release.ts b/src/core/persistence/pre-activation-release.ts
new file mode 100644
index 0000000000..0fc28d12fc
--- /dev/null
+++ b/src/core/persistence/pre-activation-release.ts
@@ -0,0 +1,97 @@
+/**
+ * #6122: a source claimed on a brain whose managed persistence was never
+ * activated. The claim (a source binding plus its worktree and host binding)
+ * fences classic sync (`sync-authority.ts` refuses `writer_coordinator_required`)
+ * but nothing publishes through it, so `gbrain sources writer deactivate` on
+ * such a brain releases it: once nothing is queued, running or recovering
+ * (the same blockers as a managed deactivation), one transaction marks the
+ * claimed worktrees `retired` (rows kept, as deactivation does), deletes the
+ * source and host bindings and records a committed `writer_deactivate`
+ * topology change (`outcome.pre_activation: true`) naming the worktrees and
+ * roots, so the retired-marker cleanup removes this host's claim markers.
+ * The brain stays classic and its `mode_epoch` does not move. The topology change
+ * needs the administering CLI registration, which a never-activated brain may lack;
+ * it is created (idempotently, as activation would) for the trusted local caller.
+ */
+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 { currentVerifiedLocalWriter, existingLocalHostId, registerLocalWriter } from './identity.ts';
+import type { NativeLockHandle } from './native-lock.ts';
+import { assertWriterAdminState } from './admin-intent.ts';
+import { assertWriterAdminUnlocked } from './admin-lock.ts';
+import { managedFilesystemDatastorePath, refreshManagedFilesystemRoots } from './filesystem-guard.ts';
+import { recordTopologyChange } from './topology-receipts.ts';
+import { lockTopologyPrincipal, topologyPrincipal } from './topology-locks.ts';
+import type { SqlEngine } from './model.ts';
+
+export interface PreActivationClaim { source_id: string; worktree_id: string; roots: string[] }
+
+/** Every source binding of the brain with its worktree's roots. Read-only. */
+export async function preActivationClaims(engine: SqlEngine): Promise<PreActivationClaim[]> {
+ const rows = await engine.executeRaw<{ source_id: string; worktree_id: string; root: string | null }>(`SELECT b.source_id, b.worktree_id::text AS worktree_id, h.local_path AS root
+ FROM persistence_source_bindings b LEFT JOIN persistence_host_bindings h ON h.worktree_id=b.worktree_id ORDER BY b.source_id, h.local_path`);
+ const claims = new Map<string, PreActivationClaim>();
+ for (const row of rows) {
+ const claim = claims.get(row.source_id) ?? { source_id: row.source_id, worktree_id: row.worktree_id, roots: [] };
+ if (row.root && !claim.roots.includes(row.root)) claim.roots.push(row.root);
+ claims.set(row.source_id, claim);
+ }
+ return [...claims.values()];
+}
+
+/**
+ * Releases every pre-activation claim; the caller has checked that the brain is
+ * disabled and that nothing blocks. `blockers` re-runs inside the transaction.
+ */
+export async function releasePreActivationClaims(engine: BrainEngine, opts: { expectedState?: string; requestId?: string;
+ blocked: (tx: BrainEngine) => Promise<OperationError | null> }): Promise<PreActivationClaim[]> {
+ // A never-activated brain may have no CLI writer registration yet (activation creates it); the trusted local
+ // operator running deactivate gets the same one, so the topology change has its administering principal.
+ if (!currentVerifiedLocalWriter()) await registerLocalWriter(engine, 'cli');
+ const principal = await topologyPrincipal(engine);
+ const requestId = opts.requestId ?? randomUUID();
+ const hostId = existingLocalHostId();
+ const locks: NativeLockHandle[] = [];
+ try {
+ // Native worktree locks precede the transaction, as in activation and deactivation.
+ const locked = new Set<string>();
+ for (const claim of await preActivationClaims(engine)) {
+ const binding = await getWorktreeBinding(engine, claim.source_id, hostId);
+ if (!binding || binding.owner_host_id !== hostId || !binding.local_path || locked.has(binding.worktree_id)) continue;
+ locked.add(binding.worktree_id);
+ const lock = await acquireWorktree(binding);
+ if (!lock) throw new OperationError('writer_lock_unavailable', `A local process holds the worktree lock of claimed source '${claim.source_id}'.`,
+ 'Stop the gbrain process on this host that holds it (gbrain serve or autopilot), then rerun deactivate.');
+ locks.push(lock);
+ }
+ 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');
+ 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.',
+ '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');
+ await tx.executeRaw('SELECT id FROM sources ORDER BY id FOR UPDATE');
+ const refused = await opts.blocked(tx);
+ if (refused) throw refused;
+ const claims = await preActivationClaims(tx);
+ if (!claims.length) return [];
+ const worktrees = [...new Set(claims.map(claim => claim.worktree_id))];
+ await tx.executeRaw("UPDATE persistence_worktrees SET state='retired' WHERE id=ANY($1::uuid[]) AND state<>'retired'", [worktrees]);
+ await tx.executeRaw('DELETE FROM persistence_source_bindings');
+ await tx.executeRaw('DELETE FROM persistence_host_bindings WHERE worktree_id=ANY($1::uuid[])', [worktrees]);
+ const retired = worktrees.map(id => ({ id, roots: [...new Set(claims.filter(claim => claim.worktree_id === id).flatMap(claim => claim.roots))] }));
+ await lockTopologyPrincipal(tx, principal);
+ await recordTopologyChange(tx, { principal, requestId, intent: { operation: 'writer_deactivate' }, operation: 'writer_deactivate', sourceId: '*',
+ incarnation: null, worktrees }, { brain_id: brain.brain_id, pre_activation: true, mode_epoch: Number(brain.mode_epoch), worktrees: retired,
+ source_roots: retired.flatMap(worktree => worktree.roots), sources: claims.map(claim => claim.source_id) });
+ await refreshManagedFilesystemRoots(tx, managedFilesystemDatastorePath(engine));
+ return claims;
+ });
+ } finally { for (const lock of locks.reverse()) await lock.release(); }
+}
diff --git a/src/core/persistence/sync-authority.ts b/src/core/persistence/sync-authority.ts
index fde2ab75f7..1ca53dced4 100644
--- a/src/core/persistence/sync-authority.ts
+++ b/src/core/persistence/sync-authority.ts
@@ -12,6 +12,7 @@ import { authorizePageVisibility } from './page-visibility.ts';
import { submissionAuthority, authorizeWrite } from './authority.ts';
import { currentVerifiedLocalWriter, registerLocalWriter } from './identity.ts';
import type { WriteAuthority } from './model.ts';
+import { writerAdminState } from './admin-intent.ts';
const legacyDelegation = new AsyncLocalStorage<boolean>();
/** The bulk sync of one source, which only the brain host's CLI may run. */
@@ -49,12 +50,26 @@ export async function resolveSyncPersistenceMode(engine: BrainEngine, opts: Sync
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']);
- if (source?.claimed) {
- throw new OperationError('writer_coordinator_required', 'Claimed-source sync, including connectors, requires explicit persistence activation.',
- '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.');
- }
+ if (source?.claimed) throw await preActivationClaimRefusal(engine, opts.sourceId ?? 'default');
return false;
}
+/**
+ * #6122: a source claimed while managed persistence was never activated. Classic sync must not run under the
+ * claim and nothing managed publishes it, so the user chooses: release the claim (classic sync resumes) or
+ * activate managed persistence. The fix is the state-bound release, behind ask_user; its preview changes nothing.
+ */
+async function preActivationClaimRefusal(engine: BrainEngine, sourceId: string): Promise<OperationError> {
+ const state = await writerAdminState(engine);
+ return opError('writer_coordinator_required', 'Claimed-source sync, including connectors, requires explicit persistence activation.',
+ `Source ${sourceId} is claimed by a managed writer, but managed persistence was never activated on this brain, so classic sync is fenced and nothing was synced. `
+ + 'This is a topology decision for the user: release the claim so classic sync resumes (the command in fix; preview it first with gbrain sources writer deactivate --dry-run --json), '
+ + 'or stop older writers on every host and activate managed persistence (gbrain sources writer activate --confirm-quiesced --admin-intent writer_activate --expected-state <admin_state>, see docs/architecture/topologies.md).',
+ { fix: { argv: ['gbrain', 'sources', 'writer', 'deactivate', '--admin-intent', 'writer_deactivate', '--expected-state', state],
+ preview_argv: ['gbrain', 'sources', 'writer', 'deactivate', '--dry-run', '--json'], consent: ['destructive'], actor: 'agent', requires_exclusive: false,
+ why: 'Releases every source claimed before activation (bindings removed, worktrees retired, a topology change recorded); the brain stays classic and the next gbrain sync runs in classic mode.',
+ user_message: `Source ${sourceId} was claimed for managed writes, but managed persistence was never turned on, so sync is blocked. Release the claim and go back to classic sync, or turn managed persistence on?`,
+ verify: { argv: ['gbrain', 'sources', 'writer', '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.',
diff --git a/src/core/persistence/unbound-source.ts b/src/core/persistence/unbound-source.ts
index eaf3314ab9..d8e39e6bfb 100644
--- a/src/core/persistence/unbound-source.ts
+++ b/src/core/persistence/unbound-source.ts
@@ -39,10 +39,20 @@ export function unboundBindCommand(sourceId: string, path: string | null): strin
* `path` is filled only for trusted local callers; remote callers get a
* placeholder instead of a host path.
*/
-export function unboundSourceError(sourceId: string, path: string | null, scope: 'database_only_eligible' | 'file_backed'): OperationError {
+export function unboundSourceError(sourceId: string, path: string | null, scope: 'database_only_eligible' | 'file_backed', classic = false): OperationError {
const bind = `bind the source on the brain host: ${unboundBindCommand(sourceId, path)} `
+ '(if an operator has locked writer administration, ask the operator to unlock it first)';
- const suggestion = scope === 'database_only_eligible'
+ // #6122: on a brain whose managed persistence is not activated, a claim alone fences classic sync of the source,
+ // so the working path is the file plus classic sync; claiming is named with that consequence.
+ const edit = `edit the page's file in the checkout${path ? ` (${path})` : ''} and run gbrain sync --source ${sourceId}, which imports it`;
+ const trap = `Managed persistence is not activated on this brain, so claiming the source (gbrain sources writer claim) would block classic sync of ${sourceId} `
+ + 'until managed persistence is activated or the claim is released with gbrain sources writer deactivate.';
+ const suggestion = classic ? scope === 'database_only_eligible'
+ ? `Source '${sourceId}' has a checkout path but no canonical owner. Choose one: ${edit}; or allow database-only writes to unbound sources `
+ + `with gbrain config set ${UNBOUND_WRITE_KEY} database_only (such pages stay database-only). ${trap}`
+ : `Source '${sourceId}' has a checkout path but no canonical owner. To change this page, ${edit}. `
+ + `${UNBOUND_WRITE_KEY}=database_only does not apply: this page came from a canonical file, and a database-only edit would be lost on the next sync. ${trap}`
+ : scope === 'database_only_eligible'
? `Source '${sourceId}' has a checkout path but no canonical owner. Choose one: ${bind}; or allow database-only writes to unbound sources `
+ `with gbrain config set ${UNBOUND_WRITE_KEY} database_only. Pages written that way stay database-only and are not materialized into canonical files after binding.`
: `Source '${sourceId}' has a checkout path but no canonical owner. To write this page, ${bind}. `
diff --git a/test/persistence-preactivation-claim.test.ts b/test/persistence-preactivation-claim.test.ts
new file mode 100644
index 0000000000..57fb70b0a6
--- /dev/null
+++ b/test/persistence-preactivation-claim.test.ts
@@ -0,0 +1,99 @@
+/**
+ * #6122(a): a source claimed on a brain whose managed persistence was never activated fences classic sync,
+ * and `gbrain sources writer deactivate` used to report `source_bindings: 0` and change nothing, leaving no
+ * supported exit. The dry run now lists the claim, the state-bound deactivate releases it (bindings removed,
+ * worktree retired, topology change recorded, brain still classic), the sync refusal names both choices behind
+ * ask_user, and the unbound-source hint on a classic brain no longer sends the agent into the claim.
+ * PGLite always; Postgres too when DATABASE_URL is set.
+ */
+import { describe, expect, test } from 'bun:test';
+import { execFileSync } from 'node:child_process';
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { runPersistenceAdministration } from '../src/core/persistence/administration.ts';
+import { writerAdminState } from '../src/core/persistence/admin-intent.ts';
+import { claimWorktree } from '../src/core/persistence/ownership.ts';
+import { resolveSyncPersistenceMode } from '../src/core/persistence/sync-authority.ts';
+import { unboundSourceError } from '../src/core/persistence/unbound-source.ts';
+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
+import { performSync } from '../src/commands/sync.ts';
+import { isolatedSharedSkillsEngine } from './helpers/shared-skills-engine.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+const admin = (engine: BrainEngine, operation: string, params: Record<string, unknown> = {}) =>
+ runPersistenceAdministration(engine, operation as never, params) as Promise<Record<string, any>>;
+
+async function classicBrainWithClaim(databaseUrl: string | undefined, run: (engine: BrainEngine, root: string) => Promise<void>) {
+ const home = mkdtempSync(join(tmpdir(), 'gbrain-preactivation-'));
+ try {
+ await withEnv({ GBRAIN_HOME: home, DATABASE_URL: undefined, GBRAIN_DATABASE_URL: undefined }, async () => {
+ const { engine, close } = await isolatedSharedSkillsEngine(databaseUrl);
+ try {
+ const root = join(home, 'content'); mkdirSync(join(root, 'notes'), { recursive: true });
+ execFileSync('git', ['-C', root, 'init', '-q']);
+ writeFileSync(join(root, 'notes', 'alice-example.md'), '---\ntitle: Alice Example\n---\nWorks at acme-example.\n');
+ execFileSync('git', ['-C', root, 'add', '.']);
+ execFileSync('git', ['-C', root, '-c', 'user.name=Example', '-c', '[email protected]', 'commit', '-qm', 'notes']);
+ await engine.executeRaw("UPDATE sources SET local_path=$1 WHERE id='default'", [root]);
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
+ await claimWorktree(engine, 'default', root);
+ await run(engine, root);
+ } finally { await disposePersistenceConsumer(engine); await close(); }
+ });
+ } finally { rmSync(home, { recursive: true, force: true }); }
+}
+const bindings = async (engine: BrainEngine) => Number((await engine.executeRaw<{ n: number }>('SELECT count(*)::int AS n FROM persistence_source_bindings'))[0]!.n);
+
+for (const databaseUrl of process.env.DATABASE_URL ? [undefined, process.env.DATABASE_URL] : [undefined]) describe(`#6122 pre-activation claim (${databaseUrl ? 'postgres' : 'pglite'})`, () => {
+ test('the dry run reports the claim, deactivate releases it and classic sync resumes', () => classicBrainWithClaim(databaseUrl, async (engine, root) => {
+ const refusal = await resolveSyncPersistenceMode(engine, { sourceId: 'default' } as never).then(() => null, error => error);
+ expect(refusal).toMatchObject({ code: 'writer_coordinator_required' });
+ expect(refusal.suggestion).toContain('gbrain sources writer activate --confirm-quiesced');
+ const state = await writerAdminState(engine);
+ expect(refusal.fix).toMatchObject({ argv: ['gbrain', 'sources', 'writer', 'deactivate', '--admin-intent', 'writer_deactivate', '--expected-state', state],
+ preview_argv: ['gbrain', 'sources', 'writer', 'deactivate', '--dry-run', '--json'], consent: ['destructive'] });
+ expect(refusal.fix.user_message).toContain('default');
+
+ const dry = await admin(engine, 'writer_deactivate', { dry_run: true });
+ expect(dry).toMatchObject({ mode: 'classic', deactivated: false, source_bindings: 1, blockers: [],
+ pre_activation_claims: [{ source_id: 'default', roots: [expect.any(String)] }],
+ apply_command: `gbrain sources writer deactivate --admin-intent writer_deactivate --expected-state ${state}` });
+ expect(await writerAdminState(engine)).toBe(state);
+ expect(await bindings(engine)).toBe(1);
+
+ const [{ mode_epoch: epochBefore }] = await engine.executeRaw<{ mode_epoch: string }>('SELECT mode_epoch::text FROM persistence_brain WHERE singleton=1');
+ const done = await admin(engine, 'writer_deactivate', { admin_intent: 'writer_deactivate', expected_state: state });
+ expect(done).toMatchObject({ mode: 'classic', pre_activation_claims: [{ source_id: 'default' }], retired_worktrees: [{ id: expect.any(String) }] });
+ expect(await bindings(engine)).toBe(0);
+ const [brain] = await engine.executeRaw<{ enabled: boolean; mode_epoch: string }>('SELECT enabled, mode_epoch::text FROM persistence_brain WHERE singleton=1');
+ expect(brain).toEqual({ enabled: false, mode_epoch: epochBefore });
+ const [change] = await engine.executeRaw<{ state: string; pre: boolean }>(
+ "SELECT state, (outcome->>'pre_activation')::boolean AS pre FROM persistence_topology_changes WHERE operation='writer_deactivate' ORDER BY created_at DESC LIMIT 1");
+ expect(change).toEqual({ state: 'committed', pre: true });
+ expect(await resolveSyncPersistenceMode(engine, { sourceId: 'default' } as never)).toBe(false);
+ const synced = await performSync(engine, { sourceId: 'default', repoPath: root, noPull: true, noEmbed: true, noExtract: true });
+ expect(['first_sync', 'synced']).toContain(synced.status);
+ expect((await engine.getPage('notes/alice-example', { sourceId: 'default' }))?.title).toBe('Alice Example');
+
+ // The source can be claimed again later (the retired worktree does not wedge its root).
+ await claimWorktree(engine, 'default', root);
+ expect(await bindings(engine)).toBe(1);
+ }), 120_000);
+
+ test('a stale expected state refuses and releases nothing', () => classicBrainWithClaim(databaseUrl, async engine => {
+ await expect(admin(engine, 'writer_deactivate', { admin_intent: 'writer_deactivate', expected_state: 'a'.repeat(64) }))
+ .rejects.toMatchObject({ code: 'writer_admin_state_changed' });
+ expect(await bindings(engine)).toBe(1);
+ }), 120_000);
+});
+
+test('the unbound-source hint on a classic brain names the file and classic sync, and what a claim would block', () => {
+ const classic = unboundSourceError('notes-example', '/srv/notes', 'file_backed', true).suggestion!;
+ expect(classic).toContain('gbrain sync --source notes-example');
+ expect(classic).toContain('gbrain sources writer deactivate');
+ expect(classic).not.toContain('gbrain sources writer claim notes-example --path');
+ const managed = unboundSourceError('notes-example', '/srv/notes', 'file_backed').suggestion!;
+ expect(managed).toContain('gbrain sources writer claim notes-example --path /srv/notes');
+});