Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
perf(sync): one routing read per single-source CLI sync before the drain lease (GBRA-133 PR 2b)
garrytan3dee6f9ce10a
diff --git a/docs/architecture/key-files/managed-sync-bookkeeping.md b/docs/architecture/key-files/managed-sync-bookkeeping.mdindex 1c69f1ede8..47f84c2847 100644--- a/docs/architecture/key-files/managed-sync-bookkeeping.md+++ b/docs/architecture/key-files/managed-sync-bookkeeping.md@@ -16,6 +16,7 @@ run, and the supersession of a checkpoint whose cursor another run replaced. The- `src/core/persistence/sync-cursor-key.ts` — #6712 PR 1: one managed cursor per source. `managedCursorKey` is a digest of the source incarnation and, for a company approval only, the company; writer principal, authority and options no longer select a cursor. `resolveManagedCursor` is the one boundary that picks a run's key and folds older keys in crash-safely under the drain lease: the canonical unfinished cursor wins, else the newest older-key unfinished cursor is adopted and finished in place under its own key; every other older cursor has its queued requests cancelled and is retired through `retireManagedSyncOrphan` (reason `superseded_by_adoption`, fenced by `assertDrainLease`). A cursor with a running, recovering or publishing request or a recovery row is retained and the pass waits for that request (`writer_pending`) before it drains anything. A company brain's finished old-key cursors are kept. Pinned by `test/sync-pass-handover-6712.test.ts` (the live pass's handover of an older binary's cursors) and `test/persistence-sync-cursor-strategy-6696.test.ts`.- `src/core/persistence/sync-lease.ts` — #6712 PR 1: the drain lease, one managed drainer per source. `withDrainLease` takes the source's sync lock (`syncLockId`) with a 2-minute TTL renewed every 20 s, so a dead holder's lease lapses inside one cron tick; it is reentrant for the holder (nested passes and the in-process lanes reuse it). The holder record (`managed-sync-lease` checkpoint: kind, id, version, start) plus the lock row give `readDrainHolder` (host, pid, heartbeat, `progress`: commits, last commit, last cursor save). A non-job holder also writes a beacon row in the `gbrain-drain-lease` minion queue (application authority, `max_stalled` 0, renewed with the lease, deleted on release) so an older binary's `liveSyncJob` backs off; downgrades are quiescent (stop serve and crons first). `assertDrainLease` is the fence inside every transaction that admits work, settles or holds an entry, folds a cursor in or swaps the cursor. Following callers (the CLI, a CLI run delegated to a serve) wait for a live holder within their budget (`followStopAt`) and take over when it releases; out of budget, or after losing the lease, they return `leaseHeldResult` (`resumable`, `sync_drain_lease_held`, `next.retry_after_ms` 60 s, `safe_to_loop`); a holder with no progress for `HOLDER_STALL_MS` (5 min) returns `leaseStalledResult` (`blocked`, `drain_stalled`, cause `no_progress`, `stall.lease_holder`). Jobs and the cycle get `SyncLockBusyError` and skip. Pinned by `test/persistence-sync-lease.test.ts`.- `src/core/persistence/sync-idle-skips.ts` — GBRA-133 (PR 2b): the managed no-op fast path. An idle tick (`stampIdlePass`) records on the drain lease (`idleClear`) whether its pin read no hold of the incarnation, a zero hold summary, no `managed-sync-failure` row of the source and no owed tail (`readIdleFacts` rides the pin's round trip). `idleSkips` names the settles that then have nothing to do (`IDLE_SKIPS`: the hold report in `performManagedPass`; settled failures, which also needs no ledger row of the source; the needs-human sweep, the sync tail and both heals in `perform.ts`). The tick, its lease, its pass row and its result are unchanged; the upstream observation, the remember replay and the ghost-page report still run. `GBRAIN_SYNC_IDLE_FAST_PATH=0` runs every settle. Pinned by `test/sync-idle-skips-gbra133.test.ts` (both backends; Postgres twin in `test/e2e/`).+- `src/core/sync-dispatch-read.ts` — GBRA-133 (PR 2b): the routing read of a single-source CLI sync. `withSyncDispatchRead` (`src/commands/sync/run.ts`, never `--all` or `--watch`) answers the source resolver, the company profile, `resolveSyncPersistenceMode`, the content-directory anchor, the managed-flag refusals, the delegation ladder's mode check and `perform.ts`'s connector check from one combined row per source (`syncDispatchRow`: the sources row, the claim, the company receipt and the mode rows). `endSyncDispatchRead` ends the scope for good where the work starts (`performSync` once the route is chosen, `maybeDelegateManagedSyncToServe` before the hand-off), so every read under the drain lease and after a write stays live; outside the scope, or when the combined read fails, each reader runs its own query. Pinned by `test/sync-dispatch-read-gbra133.test.ts` (both backends; Postgres twin in `test/e2e/`).- `src/core/wire-skew.ts` — #6712 PR 1: the one record of wire-skew windows, each a version floor plus a calendar date (`WIRE_SKEW_WINDOWS.explicitProcessing`: floor 0.60.255.0, accepted and ignored until 2026-11-14). The delegation and admin wires read the field name from here, so removing the window is one edit. #6712 PR 2: each window names the hand-offs that accept it (`wires`) and its shape (`accepts`); `retiredWireFields` / `retiredWireNotice` serve both validators. `CONFIG_ROLLBACK_WINDOWS` records the rollback config keys' windows (honored until a date, from a version floor, with the notice that named them).- `src/core/sync-flags.ts` — #6712 PR 2: `SYNC_FLAGS`, every `gbrain sync` flag once, with its route (`forward` / `client` / `refuse`) on the serve and PGLite owner hand-offs; `syncFlagsRouted` and `syncWireFields` derive the ladder's, the IPC validator's and the owner lane's allowlists. A flag the argv parsers read must be listed (`test/sync-flag-table-6712.test.ts`). #6712 PR 3 (L7): `managed: true` marks the ten flags `gbrain sync --help` lists under "Managed brains" (`MANAGED_HELP_FLAGS`, table order; `test/sync-managed-help-l7-6712.test.ts` pins the section and runs doctor's cron recipe through the managed flag validator).- `src/core/sync-config-keys.ts` + `src/commands/doctor/checks/sync-config-keys.ts` — #6712 PR 2: the `sync.*` keys in three kinds: `SYNC_TUNABLE_KEYS`, the rollback keys (windows in `wire-skew.ts`) and `RETIRED_SYNC_KEYS` with their `GBRAIN_SYNC_*` replacements (`retiredSyncSetting` reads one). `effectiveSyncKey` is `config get`'s value-in-effect and origin for a retired or rollback key (its resolvers mirror the readers: `resolveBulkSettings`, `waiverBatchEnabled`, `isFederatedV2Enabled`, the write switches, `planJobDrain`); `syncKeySetNotice` is `config set`'s warning (a retired key writes nothing). Doctor `sync_config_keys` reports a stored retired key as unapplied. Pinned by `test/sync-config-keys-6712.test.ts` and `test/error-registry-retired.test.ts`.diff --git a/src/commands/sync-delegate.ts b/src/commands/sync-delegate.tsindex 1a389ea12f..38ef8a89b9 100644--- a/src/commands/sync-delegate.ts+++ b/src/commands/sync-delegate.ts@@ -544,7 +544,9 @@ export async function maybeDelegateManagedSyncToServe(engine: BrainEngine, args:const sourceId = opts.sourceId ?? 'default';// 1. Only a managed source has the two-consumer problem; classic sync keeps its own path.const { readManagedMode } = await import('../core/persistence/managed-mode.ts');- if (!await readManagedMode(engine)) return own('not_managed');+ const dispatch = await import('../core/sync-dispatch-read.ts');+ const routing = await dispatch.syncDispatchRow(engine, sourceId);+ if (!(routing ? dispatch.dispatchManagedMode(routing) : await readManagedMode(engine))) return own('not_managed');// #6696 C2: a flag the managed source refuses never reaches the serve; the refusal names it before any probe or socket call.const { managedForbiddenFlag, managedSyncFlagRefusal } = await import('../core/persistence/managed-sync-flags.ts');const forbidden = managedForbiddenFlag(opts);@@ -580,6 +582,7 @@ export async function maybeDelegateManagedSyncToServe(engine: BrainEngine, args:return own('no_socket', fallbackLine(pid, 'the running gbrain serve exposes no sync IPC socket (older gbrain, or GBRAIN_SERVE_SYNC_IPC=0 on the serve)', false));}// 5. The hand-off: this CLI's durable writer registration (the one its own consumer would run under).+ dispatch.endSyncDispatchRead();const { registerLocalWriter } = await import('../core/persistence/identity.ts');const local = await registerLocalWriter(engine, 'cli');const registration: SyncStartRegistration = { id: local.id, credential: local.credential, lane: 'cli' };diff --git a/src/commands/sync/managed-no-pull.ts b/src/commands/sync/managed-no-pull.tsindex 259b233b66..7de9fc8a77 100644--- a/src/commands/sync/managed-no-pull.ts+++ b/src/commands/sync/managed-no-pull.ts@@ -1,5 +1,6 @@import type { BrainEngine } from '../../core/engine.ts';import { readManagedMode } from '../../core/persistence/ownership.ts';+import { dispatchManagedMode, syncDispatchRow } from '../../core/sync-dispatch-read.ts';import { managedForbiddenFlag, managedSyncFlagRefusal } from '../../core/persistence/managed-sync-flags.ts';/**@@ -9,7 +10,7 @@ import { managedForbiddenFlag, managedSyncFlagRefusal } from '../../core/persist* with its own error. The library and MCP refusal of an explicit pull stays in `resolveManagedSyncContext`.*/export async function implyManagedNoPull(engine: BrainEngine, flags: { noPull: boolean; dryRun: boolean }, sourceId: string | null): Promise<void> {- if (flags.noPull || flags.dryRun || !await readManagedMode(engine).catch(() => false)) return;+ if (flags.noPull || flags.dryRun || !await routedManagedMode(engine, sourceId).catch(() => false)) return;flags.noPull = true;process.stderr.write(`[sync] managed brain: importing ${sourceId ? `source ${sourceId}'s` : "each source's"} checkout at its local HEAD without git pull (--no-pull is implied); `+ `to fast-forward from the remote first, run gbrain sources refresh ${sourceId ?? '<id>'}\n`);@@ -22,6 +23,12 @@ export async function implyManagedNoPull(engine: BrainEngine, flags: { noPull: b*/export async function refuseManagedForbiddenFlags(engine: BrainEngine, flags: { skipFailed: boolean; includeGitignored: boolean }, args: string[]): Promise<void> {const flag = managedForbiddenFlag(flags);- if (!flag || !await readManagedMode(engine).catch(() => false)) return;+ if (!flag || !await routedManagedMode(engine, args.find((_, i) => args[i - 1] === '--source') ?? null).catch(() => false)) return;throw managedSyncFlagRefusal(flag, args.find((_, i) => args[i - 1] === '--source') ?? null, args);}++/** GBRA-133: the mode from the source's routing row inside a CLI sync's routing scope (sync-dispatch-read.ts), else read. */+async function routedManagedMode(engine: BrainEngine, sourceId: string | null): Promise<boolean> {+ const routing = sourceId ? await syncDispatchRow(engine, sourceId) : undefined;+ return routing ? dispatchManagedMode(routing) : readManagedMode(engine);+}diff --git a/src/commands/sync/perform.ts b/src/commands/sync/perform.tsindex 488d1da400..ef2ccb4d8f 100644--- a/src/commands/sync/perform.ts+++ b/src/commands/sync/perform.ts@@ -12,6 +12,7 @@ import {} from '../../core/minions/source-filesystem.ts';import { currentJobSignal, currentSubmissionAuthority } from '../../core/minions/submission-authority.ts';import { currentCompanyBrainSync, getCompanyBrainProfile } from '../../core/company-brain/profile.ts';+import { endSyncDispatchRead, syncDispatchRow } from '../../core/sync-dispatch-read.ts';import type { BrainEngine } from '../../core/engine.ts';import type { OperationContext } from '../../core/ops/contract.ts';import { refreshProjectionStatistics } from '../../core/search/projection-statistics.ts';@@ -51,11 +52,14 @@ export async function performSync(engine: BrainEngine, opts: SyncOpts): Promise<};const company = !opts.signal?.aborted && opts.sourceId && !currentCompanyBrainSync(opts.sourceId) && await getCompanyBrainProfile(engine, opts.sourceId);assertSyncDispatchActive();+ const mayBeConnector = managed && await mayBeConnectorSource(engine, opts);+ // GBRA-133: the route is chosen; the work reads live (core/sync-dispatch-read.ts).+ endSyncDispatchRead();if (company) {if (opts.signal?.aborted) return finish(await interruptedBeforeWork());return (await import('../../core/company-brain/runtime.ts')).performCompanyBrainSync(engine, opts);}- if (managed) {+ if (mayBeConnector) {const connector = await runConnectorSync(engine, opts, true);if (connector) return connector;}@@ -103,6 +107,17 @@ export async function performSync(engine: BrainEngine, opts: SyncOpts): Promise<}}+/** Whether `runConnectorSync` may sync this source: false only when the routing row shows a source it returns null for. */+async function mayBeConnectorSource(engine: BrainEngine, opts: SyncOpts): Promise<boolean> {+ const routing = opts.sourceId && !opts.githubItem && !opts.resetCheckpoint ? await syncDispatchRow(engine, opts.sourceId) : undefined;+ if (!routing) return true;+ if (routing.id === null) return false;+ try {+ const config = typeof routing.config === 'string' ? JSON.parse(routing.config) : routing.config ?? {};+ return config.kind === 'google' || config.kind === 'github';+ } catch { return true; }+}+/*** The managed branch: the drain (or one pass), its staged stages and the post-sync settles, all under the source's drain* lease (#6712 PR 1, persistence/sync-lease.ts). A plain CLI sync follows a live holder within its budget; every otherdiff --git a/src/commands/sync/run.ts b/src/commands/sync/run.tsindex dbc2d3a7ef..b19a04cb56 100644--- a/src/commands/sync/run.ts+++ b/src/commands/sync/run.ts@@ -110,8 +110,7 @@ export async function runSyncInner(engine: BrainEngine, args: string[]) {const flags = parseSyncFlags(args);noteRetryFailedDeprecated(args);- const { repoPath, dryRun, skipFailed, syncAll, jsonOut, breakLock, forceBreakLock, maxAgeSeconds } = flags;- let { noEmbed } = flags;+ const { syncAll, jsonOut, breakLock, forceBreakLock, maxAgeSeconds } = flags;// v0.41.13.0 (T4 + D1): handle --break-lock / --force-break-lock BEFORE// the sync would otherwise contend on the lock. v3's plan dropped the@@ -119,7 +118,19 @@ export async function runSyncInner(engine: BrainEngine, args: string[]) {// source in one call; runBreakLock now widens to iterate sources when// --all is set and accept maxAgeSeconds for age-gated breaks.if (breakLock || forceBreakLock) return await runSyncBreakLock(engine, args, { syncAll, jsonOut, forceBreakLock, maxAgeSeconds });+ // GBRA-133: one single-source run reads its routing rows once (core/sync-dispatch-read.ts); --all and --watch read live.+ if (syncAll || flags.watch) return runRoutedSync(engine, args, flags);+ const { syncDispatchRow, withSyncDispatchRead } = await import('../../core/sync-dispatch-read.ts');+ return withSyncDispatchRead(engine, () => {+ const explicit = args.find((a, i) => args[i - 1] === '--source');+ if (explicit) void syncDispatchRow(engine, explicit);+ return runRoutedSync(engine, args, flags);+ });+}+async function runRoutedSync(engine: BrainEngine, args: string[], flags: ReturnType<typeof parseSyncFlags>): Promise<void> {+ const { repoPath, dryRun, skipFailed, syncAll, jsonOut } = flags;+ let { noEmbed } = flags;const fanout = parseSyncFanoutFlags(args, syncAll);await refuseManagedForbiddenFlags(engine, flags, args);diff --git a/src/core/company-brain/profile.ts b/src/core/company-brain/profile.tsindex f850dd5be2..c5368e485a 100644--- a/src/core/company-brain/profile.ts+++ b/src/core/company-brain/profile.ts@@ -15,6 +15,7 @@ import type { CompanyBrainPlan, InspectionEntry } from './types.ts';import type { SourceIngestionCheckpoint } from './receipts.ts';import { companyBrainProfile, companyBrainPolicyFingerprint, type CompanyBrainProfile } from './policy.ts';import { maintenanceTransaction } from '../persistence/attribution.ts';+import { syncDispatchRow } from '../sync-dispatch-read.ts';export { companyBrainProfile, type CompanyBrainProfile } from './policy.ts';function statusFix(sourceId: string): Action {@@ -27,7 +28,9 @@ function resumeCommand(sourceId: string): string {export async function getCompanyBrainProfile(engine: BrainEngine, sourceId: string): Promise<CompanyBrainProfile | null> {// The receipt a source without a policy is checked for (of the source's current incarnation) is read beside it.- const [[source], [receipt]] = await Promise.all([engine.executeRaw<{ config: unknown; incarnation: string }>('SELECT config,incarnation FROM sources WHERE id=$1', [sourceId]),+ // GBRA-133: inside a CLI sync's routing scope the source's routing row answers both (sync-dispatch-read.ts).+ const routing = await syncDispatchRow(engine, sourceId);+ const [[source], [receipt]] = routing ? [routing.id === null ? [] : [routing], routing.company_receipt ? [true] : []] : await Promise.all([engine.executeRaw<{ config: unknown; incarnation: string }>('SELECT config,incarnation FROM sources WHERE id=$1', [sourceId]),engine.executeRaw(`SELECT r.id FROM source_ingestion_receipts r JOIN sources s ON s.id=r.source_id AND s.incarnation=r.source_incarnationWHERE r.source_id=$1 AND r.profile='company-brain' LIMIT 1`, [sourceId])]);if (!source) return null;diff --git a/src/core/persistence/sync-authority.ts b/src/core/persistence/sync-authority.tsindex ff493e237c..5041b2aae3 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, withRegisteredLocalWriter } from './identity.ts';import { readManagedMode, readPersistenceBrain } from './managed-mode.ts';+import { dispatchManagedMode, syncDispatchRow } from '../sync-dispatch-read.ts';import type { WriteAuthority } from './model.ts';import { writerAdminState } from './admin-intent.ts';@@ -41,10 +42,12 @@ export function assertSyncDispatchActive(): void {throwIfAborted(currentJobSignal());}export async function resolveSyncPersistenceMode(engine: BrainEngine, opts: SyncOpts): Promise<boolean> {- const managed = await readManagedMode(engine);+ // GBRA-133: inside a CLI sync's routing scope the source's routing row answers the mode and the claim (sync-dispatch-read.ts).+ const routing = await syncDispatchRow(engine, opts.sourceId ?? 'default');+ const managed = routing ? dispatchManagedMode(routing) : await readManagedMode(engine);assertSyncDispatchActive();if (managed || opts.signal?.aborted) return managed;- const [source] = await engine.executeRaw<{ claimed: boolean }>(`SELECT+ const [source] = routing ? [routing.id === null ? undefined : routing] : await engine.executeRaw<{ claimed: boolean }>(`SELECTEXISTS(SELECT 1 FROM persistence_source_bindings WHERE source_id=s.id AND source_incarnation=s.incarnation) AS claimedFROM sources s WHERE s.id=$1`, [opts.sourceId ?? 'default']);if (source?.claimed) throw await preActivationClaimRefusal(engine, opts.sourceId ?? 'default');diff --git a/src/core/source-resolver.ts b/src/core/source-resolver.tsindex fa42afd8b2..23aadb3b1c 100644--- a/src/core/source-resolver.ts+++ b/src/core/source-resolver.ts@@ -14,6 +14,7 @@*/import { readFileSync, lstatSync, type Stats } from 'fs';+import { syncDispatchRow } from './sync-dispatch-read.ts';import { join, dirname, resolve } from 'path';import type { BrainEngine } from './engine.ts';import type { ExplicitReadBinding } from './ops/contract.ts';@@ -627,7 +628,9 @@ export async function assessUnscopedDefaultWrite(}async function assertSourceExists(engine: BrainEngine, id: string): Promise<void> {- const rows = await engine.executeRaw<{ id: string }>(+ // GBRA-133: inside a CLI sync's routing scope the source's routing row answers this (sync-dispatch-read.ts).+ const routing = await syncDispatchRow(engine, id);+ const rows = routing ? (routing.id !== null && routing.archived === false ? [routing] : []) : await engine.executeRaw<{ id: string }>(`SELECT id FROM sources WHERE id = $1 AND archived = false`,[id],);diff --git a/src/core/sync-anchor.ts b/src/core/sync-anchor.tsindex 9735d9d36c..b60d1ea3ff 100644--- a/src/core/sync-anchor.ts+++ b/src/core/sync-anchor.ts@@ -5,6 +5,7 @@ import { withCompanyBrainSource } from './company-brain/profile.ts';* sprint C13-C14) as a pure move.*/import { realpathSync } from 'fs';+import { syncDispatchRow } from './sync-dispatch-read.ts';import { resolve as pathResolve } from 'path';import type { BrainEngine } from './engine.ts';import type { SyncOpts } from '../commands/sync.ts';@@ -24,6 +25,9 @@ export async function readSyncAnchor(which: 'repo_path' | 'last_commit',): Promise<string | null> {if (sourceId) {+ // GBRA-133: inside a CLI sync's routing scope the source's routing row answers the repo path (sync-dispatch-read.ts).+ const routing = which === 'repo_path' ? await syncDispatchRow(engine, sourceId) : undefined;+ if (routing) return routing.local_path;const col = which === 'repo_path' ? 'local_path' : 'last_commit';const rows = await engine.executeRaw<Record<string, string | null>>(`SELECT ${col} AS value FROM sources WHERE id = $1`,diff --git a/src/core/sync-dispatch-read.ts b/src/core/sync-dispatch-read.tsnew file mode 100644index 0000000000..d7cced58b3--- /dev/null+++ b/src/core/sync-dispatch-read.ts@@ -0,0 +1,60 @@+/**+ * GBRA-133 (PR 2b): the rows a single-source CLI sync reads to choose its route before it takes the source's drain lease,+ * in one round trip: the source row (existence, archive state, config, incarnation, local path), whether it is claimed+ * and has a company-brain receipt, and the brain's persistence mode. Before, the source resolver, the company profile+ * (twice), the managed mode (up to three times), the content-directory anchor and the connector check each read their+ * part in turn.+ *+ * The read is scoped to routing (`withSyncDispatchRead` around one CLI run, never --all or --watch). The scope ends for+ * good where the work starts (perform.ts once the route is chosen, sync-delegate.ts before the hand-off to the serve), so+ * every read under the lease (the managed pass reads the mode, the profile and the source rows again) and every read+ * after a write stays live. Outside the scope, after its end, or when the combined read fails, each reader runs its own+ * query as before.+ */+import { AsyncLocalStorage } from 'node:async_hooks';+import type { BrainEngine } from './engine.ts';+import { MANAGED_MODE_SQL, managedModeFromRows } from './persistence/managed-mode.ts';++export interface SyncDispatchRow {+ /** Null when no source has the id. */+ id: string | null; archived: boolean | null; config: unknown; incarnation: string | null; local_path: string | null;+ claimed: boolean; company_receipt: boolean;+ /** `enabled` of every row `MANAGED_MODE_SQL` returns. */+ modes: unknown[];+}++const SQL = `SELECT s.id, s.archived, s.config, s.incarnation::text AS incarnation, s.local_path,+ EXISTS(SELECT 1 FROM persistence_source_bindings b WHERE b.source_id=s.id AND b.source_incarnation=s.incarnation) AS claimed,+ EXISTS(SELECT 1 FROM source_ingestion_receipts r WHERE r.source_id=s.id AND r.source_incarnation=s.incarnation AND r.profile='company-brain') AS company_receipt,+ (SELECT COALESCE(jsonb_agg(m.enabled), '[]'::jsonb) FROM (${MANAGED_MODE_SQL}) m) AS modes+ FROM (SELECT $1::text AS want) w LEFT JOIN sources s ON s.id=w.want`;++const scope = new AsyncLocalStorage<{ engine: object; reads: Map<string, Promise<SyncDispatchRow | undefined>>; ended: boolean }>();++/** Runs `fn` with routing reads of `engine` answered from one shared read per source. */+export function withSyncDispatchRead<T>(engine: object, fn: () => Promise<T>): Promise<T> {+ return scope.run({ engine, reads: new Map(), ended: false }, fn);+}++/** Ends the routing scope for the rest of the run: every later read is live. */+export function endSyncDispatchRead(): void {+ const store = scope.getStore();+ if (store) store.ended = true;+}++/** The source's routing row inside the scope (read once, then shared); undefined outside it or when the read failed. */+export function syncDispatchRow(engine: Pick<BrainEngine, 'executeRaw'>, sourceId: string): Promise<SyncDispatchRow | undefined> | undefined {+ const store = scope.getStore();+ if (!store || store.ended || store.engine !== engine) return undefined;+ let read = store.reads.get(sourceId);+ if (!read) {+ read = engine.executeRaw<SyncDispatchRow>(SQL, [sourceId]).then(rows => rows[0], () => undefined);+ store.reads.set(sourceId, read);+ }+ return read;+}++/** A routing row's persistence mode under `readManagedMode`'s contract: a malformed singleton refuses the same way. */+export function dispatchManagedMode(row: SyncDispatchRow): boolean {+ return managedModeFromRows(row.modes.map(enabled => ({ enabled }))).enabled;+}diff --git a/test/e2e/sync-dispatch-read-gbra133-postgres.test.ts b/test/e2e/sync-dispatch-read-gbra133-postgres.test.tsnew file mode 100644index 0000000000..afaec38ce8--- /dev/null+++ b/test/e2e/sync-dispatch-read-gbra133-postgres.test.ts@@ -0,0 +1,3 @@+import { registerPostgresTests } from '../helpers/test-backends.ts';++await registerPostgresTests(() => import('../sync-dispatch-read-gbra133.test.ts'));diff --git a/test/sync-dispatch-read-gbra133.test.ts b/test/sync-dispatch-read-gbra133.test.tsnew file mode 100644index 0000000000..73372eedc9--- /dev/null+++ b/test/sync-dispatch-read-gbra133.test.ts@@ -0,0 +1,111 @@+/**+ * GBRA-133 (PR 2b): a single-source CLI sync reads the rows that choose its route once, before the drain lease+ * (src/core/sync-dispatch-read.ts): the source resolver, the company profile, the persistence mode, the content-directory+ * anchor and the connector check share one routing row instead of reading the source and the mode in turn. Reads under+ * the lease stay live. Both backends; test/e2e/sync-dispatch-read-gbra133-postgres.test.ts runs the Postgres arm.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { randomUUID } from 'node:crypto';+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 { runSync } from '../src/commands/sync.ts';+import { performSync } from '../src/commands/sync/perform.ts';+import { claimWorktree } from '../src/core/persistence/ownership.ts';+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';+import { MANAGED_MODE_SQL } from '../src/core/persistence/managed-mode.ts';+import { freshBrainFactory } from './helpers/persistence-request-fixture.ts';+import { testBackends } from './helpers/test-backends.ts';+import { withEnv } from './helpers/with-env.ts';+import { endSyncDispatchRead, syncDispatchRow, withSyncDispatchRead } from '../src/core/sync-dispatch-read.ts';++const git = (root: string, ...args: string[]) => execFileSync('git', ['-C', root, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim();++/** The statements the engine's top-level executeRaw sends while `fn` runs, whitespace-normalized. */+async function recordStatements(engine: BrainEngine, fn: () => Promise<unknown>): Promise<string[]> {+ const sent: string[] = [];+ const target = engine as unknown as Record<string, (...args: unknown[]) => Promise<unknown>>;+ const original = target.executeRaw!;+ target.executeRaw = function (this: unknown, ...args: unknown[]) {+ sent.push(String(args[0]).replace(/\s+/g, ' ').trim());+ return original.apply(this, args);+ };+ try { await fn(); return sent; }+ finally { delete target.executeRaw; }+}++/** Each routing read the run sent before it took the drain lease (the lease holder record). */+function routingReads(sent: string[]) {+ const lease = sent.findIndex(sql => sql.startsWith('WITH gone AS (DELETE FROM minion_jobs'));+ const before = lease < 0 ? sent : sent.slice(0, lease), under = lease < 0 ? [] : sent.slice(lease);+ const count = (match: (sql: string) => boolean) => before.filter(match).length;+ return {+ leaseTaken: lease >= 0,+ modeReadLiveUnderLease: under.some(sql => sql.startsWith('SELECT') && sql.endsWith('FROM persistence_brain WHERE singleton=1')),+ resolver: count(sql => sql === 'SELECT id FROM sources WHERE id = $1 AND archived = false'),+ profile: count(sql => sql === 'SELECT config,incarnation FROM sources WHERE id=$1'),+ mode: count(sql => sql === MANAGED_MODE_SQL),+ anchor: count(sql => sql === 'SELECT local_path AS value FROM sources WHERE id = $1'),+ connector: count(sql => sql === 'SELECT local_path,config FROM sources WHERE id=$1'),+ routingRow: count(sql => sql.includes('FROM (SELECT $1::text AS want) w LEFT JOIN sources s')),+ };+}++const databaseUrl = process.env.DATABASE_URL;++for (const kind of testBackends()) {+ describe('GBRA-133 routing reads of a CLI sync (' + kind + ')', () => {+ let factory: Awaited<ReturnType<typeof freshBrainFactory>>;+ let home: string;+ beforeAll(async () => {+ home = mkdtempSync(join(tmpdir(), 'gbrain-dispatch-read-'));+ factory = await freshBrainFactory(kind, databaseUrl);+ }, 120_000);+ afterAll(async () => {+ await factory?.dispose();+ if (home) rmSync(home, { recursive: true, force: true });+ });++ async function managedSource(engine: BrainEngine): Promise<string> {+ const id = 'route-' + randomUUID().slice(0, 12), root = join(home, id);+ mkdirSync(root); git(root, 'init', '-q');+ for (const name of ['alice-example', 'acme-example']) writeFileSync(join(root, name + '.md'), '---\ntitle: ' + name + '\n---\nA durable observation about ' + name + '.\n');+ git(root, 'add', '.'); git(root, '-c', 'user.name=Example', '-c', '[email protected]', 'commit', '-qm', 'seed');+ await disposePersistenceConsumer(engine);+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');+ await engine.executeRaw("INSERT INTO sources(id,name,local_path,config) VALUES($1,$1,$2,'{}')", [id, root]);+ await claimWorktree(engine, id, root);+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');+ await performSync(engine, { sourceId: id, noPull: true, noEmbed: true, noExtract: true, drain: true, drainHolder: { kind: 'cli', id: null } });+ return id;+ }++ test('one routing row answers the resolver, the profile, the mode, the anchor and the connector check before the lease, and the mode stays a live read under it', async () => {+ const engine = await factory.fresh();+ await withEnv({ GBRAIN_HOME: home, DATABASE_URL: undefined, GBRAIN_DATABASE_URL: undefined, OPENAI_API_KEY: undefined, ANTHROPIC_API_KEY: undefined, GBRAIN_SYNC_NO_DELEGATE: '1' }, async () => {+ try {+ const id = await managedSource(engine);+ const sent = await recordStatements(engine, () => runSync(engine, ['--source', id, '--no-pull', '--no-embed']));+ expect(routingReads(sent)).toEqual({ leaseTaken: true, modeReadLiveUnderLease: true, resolver: 0, profile: 0, mode: 0, anchor: 0, connector: 0, routingRow: 1 });+ const [row] = await engine.executeRaw<{ synced: boolean }>('SELECT last_sync_at IS NOT NULL AS synced FROM sources WHERE id=$1', [id]);+ expect(row?.synced).toBe(true);+ } finally { await disposePersistenceConsumer(engine); }+ });+ }, 180_000);++ test('the scope shares one read per source until it ends, and every read after the end is live', async () => {+ const engine = await factory.fresh();+ const sent = await recordStatements(engine, () => withSyncDispatchRead(engine, async () => {+ const [first, again] = await Promise.all([syncDispatchRow(engine, 'default'), syncDispatchRow(engine, 'default')]);+ expect(first).toBe(again);+ expect(first?.id).toBe('default');+ endSyncDispatchRead();+ expect(syncDispatchRow(engine, 'default')).toBeUndefined();+ }));+ expect(sent.filter(sql => sql.includes('LEFT JOIN sources s'))).toHaveLength(1);+ expect(syncDispatchRow(engine, 'default')).toBeUndefined();+ }, 60_000);+ });+}