Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix: pre-landing review fixes
garrytanf2cb416273ca
diff --git a/.gstack/pregate.json b/.gstack/pregate.jsonindex 3c7ddcf9b5..513b89c3f6 100644--- a/.gstack/pregate.json+++ b/.gstack/pregate.json@@ -34,6 +34,19 @@".github/workflows/ci-health.yml": ["test/scripts/ci-cost-ledger.test.ts","test/scripts/ci-health-report.test.ts"+ ],+ ".claude-plugin/plugin.json": [+ "test/codex-plugin-manifest.test.ts",+ "test/mcp-registration.test.ts"+ ],+ ".codex-plugin/plugin.json": [+ "test/codex-plugin-manifest.test.ts"+ ],+ "plugin-variants/*/.claude-plugin/plugin.json": [+ "test/codex-plugin-manifest.test.ts"+ ],+ "plugin-variants/*/.codex-plugin/plugin.json": [+ "test/codex-plugin-manifest.test.ts"]},"guards": [diff --git a/src/commands/serve.ts b/src/commands/serve.tsindex 0803aeeeaf..ab46b08286 100644--- a/src/commands/serve.ts+++ b/src/commands/serve.ts@@ -13,7 +13,7 @@ import { redirectStdoutLoggingToStderr } from '../core/console-prefix.ts';import { startFactsDrainScheduler, type FactsDrainScheduler, type FactsDrainSchedulerOpts } from '../core/facts/drain-scheduler.ts';import { startMovementWatch, type MovementWatch } from '../core/persistence/sync-movement.ts';import { startServeHeadWatcher } from '../core/serve-head-watcher.ts';-import { isReadOnlyServeArgs } from '../core/direct-pool-profile.ts';+import { isReadOnlyServeArgs, readOnlyServeSkipsResidentDuties } from '../core/direct-pool-profile.ts';import { onForwardProgress } from '../core/forward-progress.ts';import { foregroundWindow } from '../core/foreground-activity.ts';import { graduationHandoffRequested, writeServeGraduationEnvelope } from '../core/persistence/graduation-serve-guard.ts';@@ -854,7 +854,7 @@ function installStdioLifecycle(// it can never hold the process open. Cleared in beginShutdown. Kill// switch: GBRAIN_SWEEP=0 (seam: opts.sweepEnabled). Chunk-level stdin// 'data' granularity is sufficient — same rationale as armIdle below.- const sweepEnabled = !isReadOnlyServeArgs(args) && (opts.sweepEnabled ?? (process.env.GBRAIN_SWEEP !== '0')); // #7599: no sweep in a read-only serve+ const sweepEnabled = !readOnlyServeSkipsResidentDuties(isReadOnlyServeArgs(args), engine.kind) && (opts.sweepEnabled ?? (process.env.GBRAIN_SWEEP !== '0')); // #7599: no sweep in a read-only Postgres serveif (sweepEnabled) {const runIdleSweep = opts.sweep ?? (async (e: BrainEngine) => {// #4409: the runner loads lazily here too — the sweep fires after@@ -912,7 +912,7 @@ function installStdioLifecycle(}// Automatic facts drain (Lane D) and the #6317 movement watch: see installResidentTickers.- factsDrain = isReadOnlyServeArgs(args) ? null : installResidentTickers(engine, opts, deps, () => shuttingDown); // #7599: nor its resident tickers+ factsDrain = readOnlyServeSkipsResidentDuties(isReadOnlyServeArgs(args), engine.kind) ? null : installResidentTickers(engine, opts, deps, () => shuttingDown); // #7599: nor its resident tickers// Optional idle-timeout safety net. Default OFF; opt-in via// `--stdio-idle-timeout <seconds>`. The flag is for the rare case wherediff --git a/src/core/direct-pool-profile.ts b/src/core/direct-pool-profile.tsindex d0069efe48..5ec826ef4e 100644--- a/src/core/direct-pool-profile.ts+++ b/src/core/direct-pool-profile.ts@@ -2,8 +2,8 @@* How much of the direct (session) lane this process may hold. The CLI sets it* once per command; every other caller (embedders, tests) stays resident.* - resident: daemons (serve, jobs, autopilot, sync --watch) keep the full pool; a stdio- * `serve --access read-only` is one_shot instead (#7599): harnesses run one per session, and it- * starts no persistence consumer, takes no notifier lease and runs no sweep.+ * `serve --access read-only` is one_shot instead (#7599): harnesses run one per session, and on Postgres+ * it starts no persistence consumer, takes no notifier lease and runs no sweep.* - short_lived: a command that owns a consumer or takes a lease gets one connection.* - one_shot: a command that takes no lease routes nothing through the direct* pool; schema DDL still uses one connection for its session advisory lock@@ -21,12 +21,18 @@ const SHORT_LIVED_COMMANDS = new Set(['sync', 'mcp', 'dream', 'cycle', 'sources'let processProfile: DirectPoolProfile = 'resident';-/** `serve ... --access read-only`: a stdio serve that runs no resident write duty (#7599). */+/** `serve ... --access read-only`: a stdio serve that runs no resident write duty on Postgres (#7599). */export function isReadOnlyServeArgs(args: readonly string[]): boolean {const at = args.indexOf('--access');return at >= 0 && args[at + 1] === 'read-only';}+/**+ * Whether a serve skips the resident write duties (#7599): a read-only stdio serve on Postgres. A PGLite serve holds the+ * brain's only engine handle, so the CLI's reads, writes and syncs go through it, and a read-only one keeps those duties.+ */+export const readOnlyServeSkipsResidentDuties = (readOnly: boolean, engineKind: string): boolean => readOnly && engineKind !== 'pglite';+export function directPoolProfileForCommand(command: string, args: readonly string[]): DirectPoolProfile {if (command === 'serve' && isReadOnlyServeArgs(args)) return 'one_shot';if (RESIDENT_COMMANDS.has(command) || (command === 'sync' && args.includes('--watch'))) return 'resident';diff --git a/src/core/persistence/sync-blocked.ts b/src/core/persistence/sync-blocked.tsindex e26f09c5c6..a84558a58b 100644--- a/src/core/persistence/sync-blocked.ts+++ b/src/core/persistence/sync-blocked.ts@@ -18,7 +18,7 @@*/import type { BrainEngine } from '../engine.ts';import { readManagedSyncFailures } from './sync-failures.ts';-import { passFingerprint } from './sync-pass-row.ts';+import { ABANDONED_REPORT_STREAK, passFingerprint } from './sync-pass-row.ts';import { passFailureKeys } from './sync-cursor-key.ts';import type { ManagedSyncFailure } from './sync-failures.ts';@@ -57,8 +57,8 @@ export async function readBlockedManagedSyncs(engine: BrainEngine, sourceIds?: s// #7596: an open pass no recorded stop explains, whose drain lease no process renews: its process was killed or crashed.const open = readings.filter(reading => reading.row.value.telemetry.outcome === 'open' && !listed.some(blocked => blocked.source_id === reading.source_id));if (!open.length) return listed;- const [{ inspectLock, isLockHolderLive, syncLockId }, { DRAIN_LEASE_TTL_MINUTES }, { abandonedPasses }, { ABANDONED_REPORT_STREAK }] = await Promise.all([- import('../db-lock.ts'), import('./sync-lease.ts'), import('./sync-pass-status.ts'), import('./sync-pass-row.ts')]);+ const [{ inspectLock, isLockHolderLive, syncLockId }, { DRAIN_LEASE_TTL_MINUTES }, { abandonedPasses }] = await Promise.all([+ import('../db-lock.ts'), import('./sync-lease.ts'), import('./sync-pass-status.ts')]);const now = Date.now();for (const { source_id, row } of open) {const lock = await inspectLock(engine, syncLockId(source_id)).catch(() => undefined);diff --git a/src/core/persistence/sync-lease.ts b/src/core/persistence/sync-lease.tsindex 3f35dba61b..bb9de1159d 100644--- a/src/core/persistence/sync-lease.ts+++ b/src/core/persistence/sync-lease.ts@@ -36,7 +36,7 @@ import { AsyncLocalStorage } from 'node:async_hooks';import type { BrainEngine } from '../engine.ts';import type { SyncResult } from '../../commands/sync.ts';import type { Action } from '../agent-output.ts';-import { fenceLockRow, inspectLock, LockStolenError, LockUnavailableError, resolveStealGraceSeconds, syncLockId, withRefreshingLock } from '../db-lock.ts';+import { fenceLockRow, inspectLock, isLockHolderLive, LockStolenError, LockUnavailableError, syncLockId, withRefreshingLock } from '../db-lock.ts';import { currentRunDeadline, lastForwardProgressAt, noteCommittedProgress, noteForwardProgress } from '../forward-progress.ts';import { faultPoint } from './fault-points.ts';import { MANAGED_SYNC_PASS_OP } from './sync-pass-row.ts';@@ -122,14 +122,23 @@ const iso = (value: Date | null | undefined) => value ? value.toISOString() : nu/** The live holder of a source's drain lease (kind and id from the row this module writes beside the lock), or null. */export async function readDrainHolder(engine: BrainEngine, sourceId: string): Promise<DrainHolder | null> {+ return (await readDrainLease(engine, sourceId))?.holder ?? null;+}++/**+ * #7596: the holder of the source's drain lease and whether it still renews it, by `isLockHolderLive` at the drain TTL (the+ * rule doctor's `managed_sync_blocked` reads too). A killed holder's lock row stays until a takeover breaks it, but its renewals stop.+ */+export async function readDrainLease(engine: BrainEngine, sourceId: string): Promise<{ holder: DrainHolder; live: boolean } | null> {const snap = await inspectLock(engine, syncLockId(sourceId));if (!snap) return null;const [row] = await engine.executeRaw<{ meta: { kind?: DrainHolderKind; id?: string | null; version?: string } | string | null }>("SELECT data->'drain_lease_beacon' AS meta FROM minion_jobs WHERE queue=$1 AND lock_token=$2", [LEASE_BEACON_QUEUE, snap.acquisition_token]).catch(() => []);const meta = typeof row?.meta === 'string' ? JSON.parse(row.meta) : row?.meta ?? null;- return { kind: meta?.kind ?? 'unknown', id: meta?.id ?? null, host: snap.holder_host, pid: snap.holder_pid,+ const holder: DrainHolder = { kind: meta?.kind ?? 'unknown', id: meta?.id ?? null, host: snap.holder_host, pid: snap.holder_pid,started_at: iso(snap.acquired_at), last_heartbeat_at: iso(snap.last_refreshed_at), version: meta?.version ?? null,progress: await holderProgress(engine, sourceId, snap.acquired_at).catch(() => null) };+ return { holder, live: isLockHolderLive(snap, DRAIN_LEASE_TTL_MINUTES) };}/**@@ -160,15 +169,6 @@ export function holderStalled(holder: DrainHolder | null, now = Date.now()): booreturn now - since >= HOLDER_STALL_MS;}-/**- * #7596: whether a holder still renews the drain lease, by `isLockHolderLive`'s rule at the drain TTL (an unexpired TTL, or a- * renewal inside the steal grace). A killed holder's lock row stays until a takeover breaks it, but its renewals stop.- */-export function drainHolderLive(holder: DrainHolder | null, now = Date.now()): boolean {- const beat = holder?.last_heartbeat_at ?? holder?.started_at;- return !!beat && now - Date.parse(beat) < Math.max(DRAIN_LEASE_TTL_MINUTES * 60_000, resolveStealGraceSeconds(DRAIN_LEASE_TTL_MINUTES) * 1000);-}-/** What a remote caller may see of a holder: its kind and times, never its host, pid or job id. */export const publicDrainHolder = (holder: DrainHolder | null): DrainHolder | null => holder && { ...holder, id: null, host: null, pid: null };const redacted = publicDrainHolder;diff --git a/src/core/persistence/sync-movement.ts b/src/core/persistence/sync-movement.tsindex 1d1d13ab01..565dc092b6 100644--- a/src/core/persistence/sync-movement.ts+++ b/src/core/persistence/sync-movement.ts@@ -49,6 +49,7 @@ import { readManagedSyncBacklog, type ManagedSyncBacklog } from './sync-drain.tsimport { claimStateOf, type ClaimState } from './claim-phase.ts';import { readPreparationPolicy } from './switches.ts';import { listHostConsumers } from './consumer-heartbeat.ts';+import type { DrainHolder } from './sync-lease.ts';export type MovementState = 'moving' | 'held' | 'parked' | 'not_moving' | 'nothing_pending' | 'unknown';/** #6781: why a source's movement is `unknown`; `error` is the failed read's message, bounded. */@@ -120,10 +121,11 @@ interface HoldRow { count: number | string | null; stalled: number | string | nu/*** #6706: the id of the active `sync` Minions job with a live lock that is draining `sourceId`, or null. Never rejects.* #6712 PR 1: a job drains under the source's drain lease, so its holder row names the job first; the job-table read- * stays for a job an older gbrain started (it takes no lease).+ * stays for a job an older gbrain started (it takes no lease). #7596 `liveHolder`: the holder a caller already read, null+ * when it read none still renewing the lease (a killed job's lock row names it until a takeover).*/-export async function liveSyncJob(engine: BrainEngine, sourceId: string): Promise<number | null> {- const holder = await (await import('./sync-lease.ts')).readDrainHolder(engine, sourceId).catch(() => null);+export async function liveSyncJob(engine: BrainEngine, sourceId: string, liveHolder?: DrainHolder | null): Promise<number | null> {+ const holder = liveHolder !== undefined ? liveHolder : await (await import('./sync-lease.ts')).readDrainHolder(engine, sourceId).catch(() => null);if (holder?.kind === 'job' && holder.id && /^\d+$/.test(holder.id)) return Number(holder.id);// The lease's beacon row (sync-lease.ts) is for older binaries; this build reads the lease holder above.const [row] = await engine.executeRaw<{ id: number | string }>(`SELECT id FROM minion_jobs WHERE name='sync' AND status='active' AND lock_until > now() AND queue <> 'gbrain-drain-lease'diff --git a/src/core/persistence/sync-pass-status.ts b/src/core/persistence/sync-pass-status.tsindex 185115fd10..869d8a8098 100644--- a/src/core/persistence/sync-pass-status.ts+++ b/src/core/persistence/sync-pass-status.ts@@ -71,7 +71,7 @@ export function abandonedPasses(row: PassRow, now = Date.now(), interrupted?: bo/*** The state the newest pass puts the source in (design §9): never `synced` while it is open or ended unconverged, or while a* writeback its stamp recorded (`converged.writeback`) has a failed or parked Git effect (`writebackFailed`: that request). Null: nothing to add.- * #7596 `interrupted`: no process holds the source's drain lease (`drainHolderLive`), so an open pass is one whose process+ * #7596 `interrupted`: no process holds the source's drain lease (`readDrainLease`), so an open pass is one whose process* stopped without ending it (killed or crashed), not one still running: `pass_interrupted`.*/export function passStatusState(row: PassRow, withheld: DeletesWithheld | null, writebackFailed: string | null = null, now = Date.now(), interrupted?: boolean): ['synced' | 'resumable' | 'blocked', PassStatusReason] | null {diff --git a/src/core/persistence/sync-status.ts b/src/core/persistence/sync-status.tsindex e29b427bbb..1e0b003780 100644--- a/src/core/persistence/sync-status.ts+++ b/src/core/persistence/sync-status.ts@@ -49,7 +49,7 @@ import { SYNC_ADMISSION_SETTING_PARAMS, syncAdmissionEffectParams, syncAdmissionimport type { DeletesWithheld } from './sync-markers.ts';import { listIdentityDowngrades, withIdentityRemedies } from '../sync-identity-downgrades.ts';import { GIT_PUSH_CODES, readGitPushHolds, type GitPushHold } from './git-push-holds.ts';-import { drainHolderLive, holderStalled, readDrainHolder, type DrainHolder } from './sync-lease.ts';+import { holderStalled, readDrainLease, type DrainHolder } from './sync-lease.ts';import { syncLockId } from '../db-lock.ts';export interface SyncStatusHold extends SyncFaultVerdict {@@ -400,9 +400,10 @@ export async function readSyncStatus(engine: BrainEngine, sourceId: string, optsconst withheld = passRow ? source.withheld : null;// #7243: whoever holds the drain lease is the job doing the work, a serve-owned pass included (one primary-key probe rode the source read).// #7596: a holder that stopped renewing it was killed; an open pass with no live holder was interrupted, not running.- const lockHolder = source.drain_lock ? await readDrainHolder(engine, sourceId).catch(() => null) : null;- const holder = drainHolderLive(lockHolder) ? lockHolder : null;- const interrupted = passRow?.value.telemetry.outcome === 'open' && !holder;+ // A lease that could not be read decides nothing (undefined): the pass keeps the quiet-window rule.+ const lease = source.drain_lock ? await readDrainLease(engine, sourceId).catch(() => undefined) : null;+ const holder = lease?.live ? lease.holder : null;+ const interrupted = lease === undefined || passRow?.value.telemetry.outcome !== 'open' ? undefined : !holder;const passState = passRow ? passStatusState(passRow, withheld, source.writeback_failed, Date.now(), interrupted) : null;const resume = !header && passRow ? passResumeArgs(sourceId, passRow) : managedSyncResumeArgs({ sourceId, processingOptions: header?.processingOptions, syncOptions: header?.syncOptions });const human = holds.find(hold => hold.needs_human) ?? (liveError?.needs_human ? liveError : undefined);@@ -412,7 +413,7 @@ export async function readSyncStatus(engine: BrainEngine, sourceId: string, optsconst verify = { argv: ['gbrain', 'sync', 'status', '--source', sourceId, '--json'] };// #6706: a live sync job already drains this cursor; the agent watches it instead of starting a second drainer beside it.const holderJob = holder?.kind === 'job' && holder.id && /^\d+$/.test(holder.id) ? Number(holder.id) : null;- const liveJob = unfinished && !human ? holderJob ?? await (await import('./sync-movement.ts')).liveSyncJob(engine, sourceId) : null;+ const liveJob = unfinished && !human ? holderJob ?? await (await import('./sync-movement.ts')).liveSyncJob(engine, sourceId, lease === undefined ? undefined : holder) : null;const next: Action | null = liveJob !== null? { argv: ['gbrain', 'jobs', 'get', String(liveJob), '--json'], consent: [], actor: 'agent', requires_exclusive: false, verify,why: `Sync job #${liveJob} is draining this cursor (${header!.index}/${header!.total}); it resumes the frozen manifest on its own, so watch it rather than running a second sync beside it.` }@@ -446,7 +447,7 @@ export async function readSyncStatus(engine: BrainEngine, sourceId: string, opts{ stored: source.admission_stored, row_value: source.admission_row_value, set_at: source.admission_set_at, pinned: source.admission_pinned, destructive: source.admission_destructive });const passNext = passRow && passState && passState[1] === stateReason ? passStatusNext(sourceId, passState[1], passRow, resume, source.writeback_failed, interrupted) : null;return { source_id: sourceId, last_commit: source.last_commit, last_sync_at: iso(source.last_sync_at), last_committed_at: iso(committed?.last_committed_at), live: holder ? { ...holder, job_id: holderJob, stalled: holderStalled(holder) } : null,- interrupted: interrupted && passRow && !liveError ? { pass_id: passRow.value.telemetry.pass_id, since: passRow.updated_at, holder: lockHolder } : null, run_id: header?.runId ?? null,+ interrupted: interrupted && passRow ? { pass_id: passRow.value.telemetry.pass_id, since: passRow.updated_at, holder: lease?.holder ?? null } : null, run_id: header?.runId ?? null,cursor: header ? { index: Number(header.index), total: Number(header.total), pinned_target: header.target ?? null, last_advance_at: p ? new Date(p.lastAt).toISOString() : null, done: !!header.done } : null,committed_last_10m: Number(committed?.n ?? 0), ...estimate, live_job_id: liveJob ?? holderJob, holds, identity_downgrades: await withIdentityRemedies(engine, await listIdentityDowngrades(engine, [sourceId])), last_error: lastError, needs_human: !!human, ...(human ? { human_reason: human.human_reason } : {}),needs_human_from: !human ? null : 'path' in human && 'held_since' in human ? { kind: 'hold', path: human.path, slug: human.slug, code: human.code } : { kind: 'last_error', code: human.code },diff --git a/src/mcp/server.ts b/src/mcp/server.tsindex c2497631da..fe6f5c30d0 100644--- a/src/mcp/server.ts+++ b/src/mcp/server.ts@@ -27,6 +27,7 @@ import { readLocalWriter, verifyLocalWriter } from '../core/persistence/identityimport { resolveWritebackConfig, ambientOptsFrom } from '../core/facts/writeback-config.ts';import { isEngineDegraded, onEngineRecovered } from '../core/degraded-marker.ts';import { assertStdioSourceBindable } from './source-preflight.ts';+import { readOnlyServeSkipsResidentDuties } from '../core/direct-pool-profile.ts';/*** Largest JSON-RPC message the stdio server reads (the SDK default is 10 MiB,@@ -319,10 +320,10 @@ function stdioSurfaceSession(}/**- * #7599: a read-only stdio serve runs no resident write duty: no persistence consumer, no delegated sync, nudge or sweep- * kinds, no session-cursor GC and no startup sweep (serve.ts also skips the idle sweep and the resident tickers, the on-commit- * watcher among them). The long-lived serve, worker or autopilot owns them; doctor's commit_notifier and- * two_consumers_on_host say when none runs.+ * #7599: a read-only stdio serve on Postgres runs no resident write duty: no persistence consumer, no delegated sync, nudge or+ * sweep kinds, no session-cursor GC and no startup sweep (serve.ts also skips the idle sweep and the resident tickers, the+ * on-commit watcher among them); only the onboarding cache refresher runs. The long-lived serve, worker or autopilot owns+ * them; doctor's commit_notifier and two_consumers_on_host say when none runs. A PGLite serve keeps them (readOnlyServeSkipsResidentDuties).*/const READ_ONLY_SERVE_NOTE = '[gbrain-serve] read-only: no persistence consumer, on-commit sync or sweep runs here; a read-write serve, jobs work or autopilot owns them.\n';@@ -530,19 +531,18 @@ export async function startMcpServer(engine: BrainEngine, opts: { surface?: McpSlet ipcBinding: { close: () => void } | null = null;let startupSweep: { cancel: () => void } | null = null;const bootEngineDependents = async (): Promise<void> => {- // Retrieval Reflex (#1981, D9=C): the resolve/turn_context/context_pack- // (+ delegated sync/sweep) IPC listener. Wiring shared with `serve --http`- // via bindResolveIpcForServe (#4474) — best-effort; failure to bind never- // blocks the MCP server.+ // Retrieval Reflex (#1981, D9=C): the resolve/turn_context/context_pack (+ delegated sync/sweep) IPC listener. Wiring+ // shared with `serve --http` via bindResolveIpcForServe (#4474) — best-effort; failure to bind never blocks the MCP server.const [{ createPersistenceIpcProvider, residentPersistenceConfig }, { bindResolveIpcForServe }] = await Promise.all([import('../core/persistence/provider.ts'), import('./resolve-ipc-binding.ts')]);bootPhase('source_scope');const { sourceId: ipcSourceId } = await resolveMcpStdioSourceScope(engine);bootPhase('persistence_consumer');- const persistence = session.readOnly ? undefined : await createPersistenceIpcProvider(engine, residentPersistenceConfig(config) ?? { engine: engine.kind });+ const lean = readOnlyServeSkipsResidentDuties(!!session.readOnly, engine.kind);+ const persistence = lean ? undefined : await createPersistenceIpcProvider(engine, residentPersistenceConfig(config) ?? { engine: engine.kind });bootPhase('resolve_ipc_bind');- ipcBinding = await bindResolveIpcForServe(engine, ipcSourceId, persistence, { rememberCallable: () => !session.allowedOps || session.allowedOps.has('remember'), readOnly: session.readOnly });+ ipcBinding = await bindResolveIpcForServe(engine, ipcSourceId, persistence, { rememberCallable: () => !session.allowedOps || session.allowedOps.has('remember'), readOnly: lean });import('../core/onboard/mcp-onboarding.ts').then(m => m.startOnboardingRefresher(engine, { idle: () => _stdioRpcsInFlight === 0 })).catch(() => { /* coaching is best-effort */ });- if (session.readOnly) return void process.stderr.write(READ_ONLY_SERVE_NOTE);+ if (lean) return void process.stderr.write(READ_ONLY_SERVE_NOTE);// v0.45.7 ambient recall: age out stale session cursors once per serve boot (7-day TTL, indexed DELETE). Best-effort — GC failure never blocks serve.gcSessionContextState(engine).catch(() => {});diff --git a/test/e2e/serve-read-only-session-lane-postgres.test.ts b/test/e2e/serve-read-only-session-lane-postgres.test.tsindex 47c7685faf..7dc9b53102 100644--- a/test/e2e/serve-read-only-session-lane-postgres.test.ts+++ b/test/e2e/serve-read-only-session-lane-postgres.test.ts@@ -97,10 +97,12 @@ describe.skipIf(!DATABASE_URL)('#7599 serve --access read-only on the session latest('a read-only serve holds no session-lane connection after startup or after a search, and runs no resident write duty', async () => {const s = await startServe('read-only');+ // gstack-timing-ok: the contract is an absence (no session-lane connection ever opens); a read-write serve opens its 3 within this windowawait Bun.sleep(5_000);expect(await directConnections()).toBe(0);const found = await s.call(2, 'tools/call', { name: 'search', arguments: { query: WORD } });expect(JSON.stringify(found.result)).toContain('notes/alpha-example');+ // gstack-timing-ok: absence again, after a search; a lazily opened session lane would appear within this windowawait Bun.sleep(2_000);expect(await directConnections()).toBe(0);expect(s.log()).toContain('[gbrain-serve] read-only: no persistence consumer, on-commit sync or sweep runs here');@@ -108,11 +110,13 @@ describe.skipIf(!DATABASE_URL)('#7599 serve --access read-only on the session laawait stopServe();}, 120_000);- test('a read-write serve keeps its 3-connection resident direct pool', async () => {- await startServe('full');+ test('a read-write serve keeps its 3-connection resident direct pool and its notifier lease', async () => {+ const s = await startServe('full');let n = 0;for (let i = 0; i < 60 && n < 3; i++) { n = await directConnections(); if (n < 3) await Bun.sleep(500); }expect(n).toBe(3);+ for (let i = 0; i < 60 && !s.log().includes("owner of this host's notifier"); i++) await Bun.sleep(500);+ expect(s.log()).toContain("owner of this host's notifier");await stopServe();}, 120_000);});diff --git a/test/resolve-ipc-binding.test.ts b/test/resolve-ipc-binding.test.tsindex 147193cca1..355dacafd5 100644--- a/test/resolve-ipc-binding.test.ts+++ b/test/resolve-ipc-binding.test.ts@@ -16,7 +16,7 @@ import { join } from 'node:path';import net from 'node:net';import { once } from 'node:events';import { bindResolveIpcForServe } from '../src/mcp/resolve-ipc-binding.ts';-import { resolveSocketPath, socketHasLiveListener } from '../src/core/context/resolve-ipc.ts';+import { readIpcSecret, requestSweepStatus, requestSyncStatus, resolveSocketPath, socketHasLiveListener } from '../src/core/context/resolve-ipc.ts';import type { BrainEngine } from '../src/core/engine.ts';import { withEnv } from './helpers/with-env.ts';import { requestPersistenceCapabilities } from '../src/core/persistence/ipc.ts';@@ -97,6 +97,30 @@ describe('bindResolveIpcForServe (#4474)', () => {});});+ it('#7599: a read-only bind registers no delegated sync or sweep kind; a read-write bind does', async () => {+ const dataDir = join(tmp, 'db');+ mkdirSync(dataDir, { recursive: true });+ mkdirSync(join(tmp, '.gbrain'), { recursive: true });+ writeFileSync(join(tmp, '.gbrain', 'config.json'), JSON.stringify({ engine: 'pglite', database_path: dataDir }));+ await withEnv({ GBRAIN_HOME: tmp, GBRAIN_DATABASE_URL: undefined, DATABASE_URL: undefined, GBRAIN_SERVE_SYNC_IPC: undefined }, async () => {+ for (const readOnly of [true, false]) {+ const binding = await bindResolveIpcForServe({} as unknown as BrainEngine, 'default', undefined, { readOnly });+ try {+ const secret = readIpcSecret(dataDir) ?? '';+ const sync = await requestSyncStatus(binding.socketPath!, { secret, jobId: 'no-such-job' });+ const sweep = await requestSweepStatus(binding.socketPath!, { secret, jobId: 'no-such-job' });+ const want = readOnly ? 'unsupported_kind' : 'unknown_job';+ expect((sync as { error?: string }).error).toBe(want);+ expect((sweep as { error?: string }).error).toBe(want);+ } finally {+ const closed = binding.server ? once(binding.server, 'close') : Promise.resolve();+ binding.close();+ await closed;+ }+ }+ });+ });+it('returns a null binding (not a throw) when the config has no keying material', async () => {mkdirSync(join(tmp, '.gbrain'), { recursive: true });writeFileSync(join(tmp, '.gbrain', 'config.json'), JSON.stringify({ engine: 'pglite' }));diff --git a/test/serve-read-only-pglite-owner-7599.test.ts b/test/serve-read-only-pglite-owner-7599.test.tsnew file mode 100644index 0000000000..ff0a1afa53--- /dev/null+++ b/test/serve-read-only-pglite-owner-7599.test.ts@@ -0,0 +1,52 @@+/**+ * #7599: a read-only stdio serve skips the resident write duties on Postgres. On PGLite the serve holds the brain's only+ * engine handle, so the CLI's reads and writes go through its persistence owner socket; a read-only PGLite serve that+ * skipped them left every CLI command with "The local persistence owner is unavailable". It keeps them.+ *+ * Drives the real CLI subprocess beside a real `gbrain serve --access read-only` holding the PGLite brain.+ */+import { afterAll, beforeAll, expect, test } from 'bun:test';+import { mkdtempSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { Client } from '@modelcontextprotocol/sdk/client/index.js';+import { StdioClientTransport } from '@modelcontextprotocol/sdk/client/stdio.js';+import { runCli, type CliResult } from './helpers/cli-spawn.ts';++const CLI = join(import.meta.dir, '..', 'src', 'cli.ts');+const baseEnv = { GBRAIN_SKIP_STARTUP_HOOKS: '1', GBRAIN_UPDATE_CHECK: '0', GBRAIN_SWEEP: '0', GBRAIN_NON_INTERACTIVE: '1',+ GBRAIN_NO_BANNER: '1', NO_COLOR: '1', NODE_ENV: 'test', GBRAIN_SOURCE: undefined, GBRAIN_BRAIN_ID: undefined };++let home: string;++const gbrain = (args: string[]) => runCli(args, { home, cwd: home, env: baseEnv, timeoutMs: 90_000 });+const ok = (result: CliResult) => {+ expect({ exit: result.exitCode, failure: result.exitCode ? result.stdout + result.stderr : '' }).toEqual({ exit: 0, failure: '' });+ return JSON.parse(result.stdout) as Record<string, any>;+};++beforeAll(async () => {+ home = mkdtempSync(join(tmpdir(), 'gbrain-ro-pglite-7599-'));+ ok(await gbrain(['init', '--pglite', '--no-embedding', '--non-interactive', '--json']));+}, 120_000);++afterAll(() => {+ rmSync(home, { recursive: true, force: true });+});++test('a read-only stdio serve holding a PGLite brain still serves the CLI\'s writes and reads', async () => {+ const env = { PATH: process.env.PATH ?? '/usr/bin:/bin', HOME: home, GBRAIN_HOME: home, GBRAIN_SKIP_STARTUP_HOOKS: '1',+ GBRAIN_UPDATE_CHECK: '0', GBRAIN_SWEEP: '0', NODE_ENV: 'test' };+ const client = new Client({ name: 'ro-pglite-7599', version: '1' }, { capabilities: {} });+ const transport = new StdioClientTransport({ command: process.execPath, args: ['--no-env-file', CLI, 'serve', '--access', 'read-only'], cwd: home, env, stderr: 'pipe' });+ try {+ await client.connect(transport, { signal: AbortSignal.timeout(30_000) });+ const captured = ok(await gbrain(['capture', 'Captured beside a read-only serve.', '--slug', 'inbox/read-only-example-7599', '--json']));+ expect(captured).toMatchObject({ slug: 'inbox/read-only-example-7599' });+ const page = ok(await gbrain(['get', 'inbox/read-only-example-7599', '--json']));+ expect(page).toMatchObject({ slug: 'inbox/read-only-example-7599' });+ } finally {+ await client.close().catch(() => {});+ await transport.close().catch(() => {});+ }+}, 180_000);diff --git a/test/sync-pass-interrupted-7596.test.ts b/test/sync-pass-interrupted-7596.test.tsindex a33db74830..635b552a8b 100644--- a/test/sync-pass-interrupted-7596.test.ts+++ b/test/sync-pass-interrupted-7596.test.ts@@ -5,17 +5,17 @@* Doctor `managed_sync_blocked` listed nothing. An open pass with no process renewing the source's drain lease is now* `pass_interrupted` in status (with `interrupted` naming the pass and the dead holder) and in doctor.*/-import { describe, expect, test } from 'bun:test';+import { describe, expect, spyOn, test } from 'bun:test';import { execFileSync } from 'node:child_process';import { writeFileSync } from 'node:fs';import { hostname } from 'node:os';import { join } from 'node:path';import type { Check } from '../src/commands/doctor.ts';import { managedSyncBlockedEntry } from '../src/commands/doctor/checks/managed-sync-blocked.ts';+import * as dbLock from '../src/core/db-lock.ts';import { syncLockId } from '../src/core/db-lock.ts';import type { BrainEngine } from '../src/core/engine.ts';import { readBlockedManagedSyncs } from '../src/core/persistence/sync-blocked.ts';-import { drainHolderLive, type DrainHolder } from '../src/core/persistence/sync-lease.ts';import { abandonedPasses, passStatusNext, passStatusState } from '../src/core/persistence/sync-pass-status.ts';import { MANAGED_SYNC_PASS_OP, type PassRow } from '../src/core/persistence/sync-pass-row.ts';import { performManagedSync } from '../src/core/persistence/sync-run.ts';@@ -29,16 +29,8 @@ const now = Date.parse('2026-10-25T12:00:00Z');const row = (outcome: string, streak: number | undefined, quietMs: number): PassRow => ({ updated_at: new Date(now - quietMs).toISOString(),value: { source_id: 's', incarnation: 'i', lease_token: 't', obligations: { baseline_commit: null, mismatch: {}, not_converged_streak: 0, faults: {}, ...(streak ? { abandoned_streak: streak } : {}) },telemetry: { pass_id: 'p', target: 'h', started_at: '', ended_at: null, kind: 'full', round: 0, outcome: outcome as never, stop_reason: null, candidates: 0, settled: 0, remaining: 0, counts: {}, duration_ms: null, timings_ms: {} } } });-const holder = (beatAgoMs: number): DrainHolder => ({ kind: 'cli', id: null, host: 'host-a', pid: 4242, started_at: new Date(now - 600_000).toISOString(),- last_heartbeat_at: new Date(now - beatAgoMs).toISOString(), version: null, progress: null });describe('#7596: an open pass with no live drain-lease holder reads interrupted', () => {- test('a holder that stopped renewing the lease is not live', () => {- expect(drainHolderLive(holder(20_000), now)).toBe(true);- expect(drainHolderLive(holder(3 * 60_000), now)).toBe(false);- expect(drainHolderLive(null, now)).toBe(false);- });-test('the first interrupted pass is resumable pass_interrupted and next is the plain sync', () => {const open = row('open', undefined, 10_000);expect(passStatusState(open, null, null, now, true)).toEqual(['resumable', 'pass_interrupted']);@@ -92,6 +84,31 @@ for (const backend of testBackends()) {expect(status.interrupted?.holder).toMatchObject({ pid: 4242 });expect(await blocked()).toEqual([expect.objectContaining({ code: 'pass_interrupted' })]);+ // A lease that cannot be read decides nothing: the fresh open pass reads unfinished, and doctor lists nothing for it.+ const lockRead = spyOn(dbLock, 'inspectLock').mockRejectedValue(new Error('lock read failed'));+ try {+ status = await readSyncStatus(engine, 'default', { detail: false });+ expect(status.reason).toBe('pass_unfinished');+ expect(status.interrupted).toBeNull();+ expect(await blocked()).toEqual([]);+ } finally { lockRead.mockRestore(); }++ // Passes in a row keep stopping that way: status and doctor both read pass_abandoned, with the lock row left or released.+ await engine.executeRaw(`UPDATE op_checkpoints SET completed_keys=jsonb_set(completed_keys,'{0,obligations,abandoned_streak}','1') WHERE op=$1`, [MANAGED_SYNC_PASS_OP]);+ for (const release of [false, true]) {+ if (release) await engine.executeRaw('DELETE FROM gbrain_cycle_locks WHERE id=$1', [syncLockId('default')]);+ status = await readSyncStatus(engine, 'default', { detail: false });+ expect([status.state, status.reason]).toEqual(['blocked', 'pass_abandoned']);+ expect(status.interrupted).toMatchObject({ pass_id });+ expect(await blocked()).toEqual([expect.objectContaining({ code: 'pass_abandoned', run_id: pass_id })]);+ }+ await engine.executeRaw(`UPDATE op_checkpoints SET completed_keys=completed_keys #- '{0,obligations,abandoned_streak}' WHERE op=$1`, [MANAGED_SYNC_PASS_OP]);++ // An interrupted pass stopped for over an hour fails doctor.+ await engine.executeRaw(`UPDATE op_checkpoints SET updated_at=now()-interval '2 hours' WHERE op=$1`, [MANAGED_SYNC_PASS_OP]);+ expect(await doctor()).toMatchObject({ name: 'managed_sync_blocked', status: 'fail' });+ await lockRow(engine, '3 minutes', '-1 minute');+// A holder that renewed the lease just now is a pass still running: not interrupted, not blocked.await lockRow(engine, '1 second', '2 minutes');status = await readSyncStatus(engine, 'default', { detail: false });