Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(sync): a source past the cursor bound syncs in stages instead of never (#6349)
time-attack97a8699b9d90
diff --git a/docs/architecture/key-files/persistence-stalls.md b/docs/architecture/key-files/persistence-stalls.mdindex 90f33c478f..7e257996a6 100644--- a/docs/architecture/key-files/persistence-stalls.md+++ b/docs/architecture/key-files/persistence-stalls.md@@ -49,3 +49,4 @@ owner (`owner_wedged_here`), movement surfaces (`data_moving`, doctor- `src/core/postgres-engine/pool-stats.ts` — #6317 (C1, G1): `driverPoolStats(sql)` reads the vendored postgres.js driver's `sql.pool` getter (`vendor/postgres`, patch regenerated) for real `{checked_out, max, waiters}`; `enginePoolStats(engine)` labels the source (`driver` or `tracked_subset` from `pool-gauge.ts`). Filled into the heartbeat row, `writer status` running claims and `getPoolDiagnostics()`.- `src/core/persistence/sync-drain.ts` (#6405, #6423 in-pass governor) + `src/core/persistence/drain-step.ts` — `runDrain` races every pass against a governor that runs with or without `announce`: the pass gets its own `AbortController`, the governor's head read is bounded (`GOVERN_PROBE_MS`, or the window when shorter), and on a stop the pass signal is aborted (the pass's `assertActive` / `stampDrainStep` boundaries throw, so it admits and writes nothing more) and its late result or rejection is dropped. A head claim live in `publishing` past `persistence.publication_ceiling_ms` (default 300000, 60000 to 3600000; `PUBLICATION_CEILING_DEFAULT_MS`) stops `blocked` / `drain_stalled` / `publication_overdue` with `stall.in_pass` and a `next` that says restart (never a promised reclaim); a pass with no commit, no unfinished request and nothing changing for `IN_PASS_NO_PROGRESS_MS` (5 min) stops `no_admission`, an unchanged non-empty head `no_progress` / `owner_missing`; a live preparation is left to its own budget and ceiling. `drain-step.ts` holds the process-local step (`freeze`, `waiver_run`, `admission`, `await_receipt`, stamped in `sync-run.ts`) and the last statement label (`noteDrainSql`, from `waiveNoopRun`). `enterClaimPhase(clock, 'publishing')` stamps `waiting_on: 'publication'`. `drainManagedSync` prints one line when the sync's own pool is a transaction-mode pooler. `sync-waivers.ts` `waiveNoopRun` pipelines at most `WAIVER_PIPELINE_MAX` (64) calls per round trip and sends the next chunk only while the prefix holds. `commands/sync-delegate.ts`: a serve-delegated `no_admission` stop continues once with the CLI's own consumer (`serve_no_admission`); a `publication_overdue` stop is reported as it is. Tests: `test/sync-drain-inpass-stall.test.ts`, `test/sync-drain-no-admission.test.ts`, `test/sync-waivers-chunk.test.ts`.- `src/core/persistence/publication-deadline.ts` (#6288 part 1, #6352; UC2) — what bounds a publish that neither resolves nor rejects. On Postgres the publish transaction is the real bound: `declareDurablePersistence` already sets a transaction-local `statement_timeout` (5 s) and `lock_timeout`, and `bindPublicationTimeouts` (first statement of `publishMutation`'s and `publishGroup`'s transactions, pipelined, no extra round trip) adds a transaction-local `idle_in_transaction_session_timeout` of `persistence.publication_ceiling_ms` (default 300000, 60000 to 3600000; never above the pool's own `GBRAIN_IDLE_TX_TIMEOUT`), so a publisher stuck between statements is ended by the server and commits nothing; both survive a transaction pooler that drops startup parameters. Never set on PGLite: it would enforce the bound, and a transaction it ends wedges the engine's only connection. `boundPublication` (the consumer's single path and `executeClaimedGroup`'s group publish and per-member fallback) settles only with the publish's own outcome, so nothing releases or reports a request or group while its transaction can still commit; at the ceiling the claim stamp reads `waiting_on: publication_deadline`, after `PUBLICATION_GRACE_MS` (30 s) it aborts the publication's signal (passed to `engine.transaction(fn, { signal })` through `publicationTransaction`; an engine without the option ignores it), and after `PUBLICATION_SETTLE_MS` (5 s) more the consumer lists it in `stuck_publications` and reports `restart_required` (its root stays held: restarting the owner is the recovery, never a promised reclaim). The lease keeps renewing, so a reclaim never races a publisher that may still write files. The wave 9 yield between groups is outside any one bound. Tests: `test/persistence-publication-deadline.test.ts` (barriers after the token lock, after the file rename and before commit; the server-side idle end on Postgres; the wiring probe).+- `src/core/persistence/sync-discovery.ts` (#6349 staged catch-up) — when an incremental delta (not `--full`, not company) exceeds the cursor bound (100,000 entries, 16 MiB; `_setCursorBoundForTest` lowers it), `stagedSyncTarget` gallops forward over `git rev-list --first-parent last..HEAD`, verifying every candidate's delta from the last synced commit against the bound (a net delta is not monotone, so no binary search), and discovery reruns pinned at the furthest fitting commit with no working-tree entries, recording `stagedHead`; the cursor carries it and `SyncResult.staged { target, head, stages }` reports it. One commit alone above the bound refuses `request_too_large` naming the commit. `commands/sync/perform.ts` loops a drain stage by stage to HEAD (the drain's one extra HEAD-moved pass is skipped for a staged result). Tests: `test/sync-staged-catchup.test.ts`.diff --git a/docs/guides/troubleshooting.md b/docs/guides/troubleshooting.mdindex 1812789bc5..ca8a0faf91 100644--- a/docs/guides/troubleshooting.md+++ b/docs/guides/troubleshooting.md@@ -27,6 +27,7 @@| [Sync held a file for its facts or takes fence (`Held <path>: invalid_fence …`)](#held-fence-files) | nothing for most holds: the next maintenance run repairs and commits the fence. To see or do it now, preview `gbrain repair fences --source <id>` and run its printed `--apply --expect <hash>`; to pause automatic repair, `gbrain config set fences.repair.enabled false` (ask the user first). A `manual` reason needs the edit the hold names | agent; the apply needs no extra consent | none (model repair spends within the `fences.repair.*` caps; raising them is `paid`, the user's call) | `gbrain doctor --only fence_integrity --json` || A managed catch-up on a live checkout keeps dying (`revision_conflict`, `pinned_git_worktree_conflict`, `page_identity_changed`, `write ECONNABORTED`), or you want an agent to drive the recovery | `gbrain sync status --source <id> --json` (cursor, `committed_last_10m`, each hold and the last error with `class` / `safe_actions` / `needs_human`); when nothing moved and `needs_human` is false, `gbrain sync unblock --source <id> --apply`, then the sync it prints ([runbook](sync-unblock-runbook.md)) | agent; a person only when `needs_human` names a slug | none | `gbrain sync status --source <id> --json` || [Sync held a file with `worktree_dirty`](#worktree-dirty-hold) | commit (or restore) the file, then `gbrain sync unblock --source <id> --apply` and the sync it prints | agent; whoever edits the file commits it | none | `gbrain sources status <id> --json` |+| A managed sync of a source far behind HEAD prints `staged catch-up: synced to <commit>, short of HEAD`, or refuses `request_too_large` with `One commit exceeds the bounded cursor size` | Staging is automatic: `gbrain sync --source <id> --no-pull` takes stage after stage (each the furthest first-parent commit whose delta fits 100,000 entries and 16 MiB) until it reaches HEAD, and a stop resumes at the stored cursor; a scheduled sync takes one stage per run. When one commit alone is above the bound, exclude part of it (`--exclude`, or `gbrain config set sync.exclude`) and rerun; `--full` above the bound still refuses | agent | none | `gbrain sync status --source <id> --json` (cursor target reaches HEAD) || The drain stopped `connection_lost` | check the database and pooler (`gbrain doctor --json`), then rerun the same sync; it resumes at the stored cursor | agent | none | `gbrain sync status --source <id> --json` || [Managed catch-up stuck, or `Held <path>: preparation_stalled`, or the drain stopped `preparation_abandoned` / `preparation_systemic` / `write_capacity`](#catch-up-stuck) | `gbrain sources writer status --source <id> --json` (what the stuck write was doing: step, `waiting_on`, owner, version), fix what it names or upgrade the owner, then `gbrain sources retry-held <id>` and the same sync with its options | agent; a restart or upgrade of the owner after the user agrees | none to inspect; `persistent_install` when the fix restarts a service | `gbrain sources status <id> --json`, then `gbrain doctor --only git_held_files,persistence_write_stall --json` || [The catch-up is parked: `data_moving: false`, doctor `managed_sync_not_moving`, or `gbrain sources writer movement` exited 1](#managed-sync-not-moving) | `gbrain sources status <id> --json` prints the exact writer-status command; run it: `gbrain sources writer status --source <id> --json` ends each running claim in a `claim.next` (`claim_running`: rerun after `retry_after_ms`; `claim_overdue`: `tell_user_to_run`, restart the named owner pid) | agent; the restart after the user agrees | none to inspect; `persistent_install` when the fix restarts a service | `gbrain sources writer movement <id>` (exit 0 when the data moves again), then `gbrain doctor --only managed_sync_not_moving --json` |diff --git a/src/commands/sync.ts b/src/commands/sync.tsindex 90e2cf7283..b6a66c1d91 100644--- a/src/commands/sync.ts+++ b/src/commands/sync.ts@@ -96,6 +96,8 @@ export interface SyncResult {bankedFiles?: number;/** #5984: the managed drain's verdict and the next step for the agent (see sync-drain.ts). */drain?: import('../core/persistence/sync-drain.ts').DrainReport;+ /** #6349: this run synced a staged first-parent commit (`target`) short of `head`, because the delta to HEAD exceeded the cursor bound; `stages` counts the stages a CLI loop took. */+ staged?: { target: string; head: string; stages?: number };/** #6278: the run stopped because too many writes stalled while preparing (one systemic diagnostic instead of a pile of holds). */breaker?: import('../core/persistence/sync-run.ts').ManagedSyncBreaker;/** #5984: managed cursor position (`index` of `total` manifest entries) and its active drain window. */diff --git a/src/commands/sync/perform.ts b/src/commands/sync/perform.tsindex 53edfee7db..2446530967 100644--- a/src/commands/sync/perform.ts+++ b/src/commands/sync/perform.ts@@ -1,4 +1,5 @@/** `performSync`: the library entrypoint (dispatch, filesystem lock, writer lock). */+import { serr } from '../../core/console-prefix.ts';import {assertSyncDispatchActive,resolveSyncPersistenceMode,@@ -57,9 +58,21 @@ export async function performSync(engine: BrainEngine, opts: SyncOpts): Promise<}if (opts.signal?.aborted) return finish(await interruptedBeforeWork());if (managed) {- const result = opts.drain+ let result = opts.drain? await (await import('../../core/persistence/sync-drain.ts')).drainManagedSync(engine, opts, true): await (await import('../../core/persistence/sync-run.ts')).performManagedSync(engine, opts);+ // #6349: a delta past the cursor bound syncs in stages; a drain takes the next stage from where the last one landed+ // until it reaches HEAD (each stage freezes its own bounded manifest, and a stop resumes at the stored cursor).+ while (opts.drain && result.staged && result.drain?.outcome === 'synced' && !opts.dryRun && !opts.signal?.aborted) {+ serr(`[sync] staged catch-up: synced to ${result.staged.target.slice(0, 12)}, short of HEAD ${result.staged.head.slice(0, 12)} (the delta exceeds the cursor bound); taking the next stage.`);+ const next = await (await import('../../core/persistence/sync-drain.ts')).drainManagedSync(engine, opts, true);+ const stages = (result.staged.stages ?? 1) + 1, d = result.drain, n = next.drain;+ result = { ...next, fromCommit: result.fromCommit, added: result.added + next.added, modified: result.modified + next.modified, deleted: result.deleted + next.deleted,+ renamed: result.renamed + next.renamed, chunksCreated: result.chunksCreated + next.chunksCreated,+ ...(next.staged ? { staged: { ...next.staged, stages } } : {}),+ ...(n ? { drain: { ...n, passes: d.passes + n.passes, processed: d.processed + n.processed, written: d.written + n.written, waived: d.waived + n.waived } } : {}) };+ if (!next.staged) serr(`[sync] staged catch-up reached HEAD after ${stages} stages.`);+ }if (!opts.dryRun) await recordUpstreamObservation(engine, opts.sourceId ?? 'default', opts.repoPath);if (!opts.dryRun && ['synced', 'first_sync', 'up_to_date'].includes(result.status)) await clearSettledFailures(engine, opts.sourceId ?? 'default');return result;diff --git a/src/core/persistence/sync-discovery.ts b/src/core/persistence/sync-discovery.tsindex 762b08c214..454d811c4b 100644--- a/src/core/persistence/sync-discovery.ts+++ b/src/core/persistence/sync-discovery.ts@@ -44,7 +44,9 @@ export interface SyncDiscovery { binding: WorktreeBinding; root: string; gitRoot/** #5988: held paths that left the source (now excluded); their holds clear when the run checkpoints. */releasedHolds?: string[];/** #5988: `sources retry-held` paths this discovery consumed (screened as an entry or a candidate, or no longer eligible); cleared with the cursor save. */- retryTaken?: string[]; }+ retryTaken?: string[];+ /** #6349: the checkout's HEAD when the delta to it exceeded the cursor bound and `target` is a staged first-parent commit short of it. */+ stagedHead?: string; }export interface ManagedSyncContext { binding: WorktreeBinding; root: string; gitRoot: string; sourceId: string; incarnation: string;source: { last_commit: string | null; config: Record<string, unknown> }; }/** The persisted `sync.exclude` globs (plus a run's `--exclude`), as discovery matches them against a path relative to the source root. */@@ -175,7 +177,30 @@ export async function resolveManagedSyncContext(engine: BrainEngine, opts: SyncOwhy: 'The sync command routes a connector source to its own coordinator.' } });return { binding, root, gitRoot, sourceId, incarnation: source.incarnation, source };}-export async function discoverManagedSync(engine: BrainEngine, opts: SyncOpts, context?: ManagedSyncContext): Promise<SyncDiscovery> {+/** The cursor bound: entries and serialized bytes one frozen manifest may hold. */+let cursorBound = { entries: 100_000, bytes: 16 * 1024 ** 2 };+/** Test seam: a smaller cursor bound (call with no argument to restore the default). */+export function _setCursorBoundForTest(bound?: { entries: number; bytes: number }): void { cursorBound = bound ?? { entries: 100_000, bytes: 16 * 1024 ** 2 }; }+const manifestFits = (entries: readonly unknown[]) => entries.length <= cursorBound.entries && Buffer.byteLength(JSON.stringify(entries)) <= cursorBound.bytes;++/**+ * #6349: the furthest first-parent commit after `from` whose delta from `from` fits the cursor bound, found by a forward+ * gallop that verifies every candidate it accepts (a net delta from a fixed base is not monotone along history: an add+ * reverted later shrinks it again, so a binary search has no valid predicate). Null when even the first commit does not fit.+ */+export function stagedSyncTarget(gitRoot: string, from: string, target: string, fits: (commit: string) => boolean): { commit: string; first: string } | { oversized: string } {+ const commits = syncGit(gitRoot, ['rev-list', '--first-parent', '--reverse', `${from}..${target}`]).split('\n').map(line => line.trim()).filter(Boolean);+ let good = -1, step = 1;+ while (good < commits.length - 1) {+ const at = Math.min(good + step, commits.length - 1);+ if (fits(commits[at]!)) { good = at; step *= 2; continue; }+ if (step === 1 || at === good + 1) break;+ step = Math.max(1, Math.floor((at - good) / 2));+ }+ return good < 0 ? { oversized: commits[0] ?? target } : { commit: commits[good]!, first: commits[0]! };+}++export async function discoverManagedSync(engine: BrainEngine, opts: SyncOpts, context?: ManagedSyncContext, stage?: { target: string; head: string }): Promise<SyncDiscovery> {const { binding, root, gitRoot, sourceId, incarnation, source } = context ?? await resolveManagedSyncContext(engine, opts);const company = currentCompanyBrainSync(sourceId);const strategy = opts.strategy ?? source.config?.strategy ?? 'markdown';@@ -193,9 +218,10 @@ export async function discoverManagedSync(engine: BrainEngine, opts: SyncOpts, cconst eligible = (path: string) => (!scope || path.startsWith(`${scope}/`)) &&!matchesAnyGlob(scope ? path.slice(scope.length + 1) : path, exclude) && !isReservedSkillBundlePath(sourcePath(path)) &&isSyncable(path, { strategy: strategy as 'markdown', includeHidden });- const target = company?.plan.revision?.commit ?? syncGit(gitRoot, ['rev-parse', 'HEAD']).trim();+ const target = stage?.target ?? company?.plan.revision?.commit ?? syncGit(gitRoot, ['rev-parse', 'HEAD']).trim();const detached = !company && syncGit(gitRoot, ['rev-parse', '--abbrev-ref', 'HEAD']).trim() === 'HEAD';- const working = !company && (detached || (opts.workingTree ?? (await engine.getConfig('sync.include_working_tree') === 'true')));+ // #6349: a staged run stops at a commit, so uncommitted working-tree changes wait for the stage that reaches HEAD.+ const working = !company && !stage && (detached || (opts.workingTree ?? (await engine.getConfig('sync.include_working_tree') === 'true')));const dirty = company ? { added: [], modified: [], deleted: [], renamed: [] } : buildDetachedWorkingTreeManifest(gitRoot);const delta = !opts.full && source.last_commit ? computeSyncDelta(gitRoot, source.last_commit, target) : null;const entries = new Map<string, SyncEntry>();@@ -322,10 +348,30 @@ export async function discoverManagedSync(engine: BrainEngine, opts: SyncOpts, cconst unsupported = selected.find(e => e.action === 'import' && !/\.mdx?$/i.test(e.path) && !isCodeFilePath(e.path) && (company || !isImageFilePath(e.path)));if (unsupported) throw opError('writer_coordinator_required', 'Managed image sync requires a prepared importer; this sync was refused before any page write.',`Managed sync of ${sourceId} imports only Markdown and code files, and this run selected others (for example ${unsupported.path}). Exclude them with --exclude or the sync.exclude config, then run gbrain sync --no-pull --source ${sourceId}.`);- if (selected.length > 100_000 || Buffer.byteLength(JSON.stringify(selected)) > 16 * 1024 ** 2) throw opError('request_too_large', 'Sync discovery exceeds the bounded cursor size.',- `This sync of ${sourceId} selected ${selected.length} entries, above the 100,000-entry and 16 MiB cursor bound; nothing was written. Narrow it with --exclude or the sync.exclude config, then run gbrain sync --no-pull --source ${sourceId}.`);+ if (!manifestFits(selected)) {+ // #6349: an incremental delta past the bound is synced in stages: the furthest first-parent commit whose delta fits,+ // then the next stage from there (the CLI loops; a scheduled sync takes one stage per run).+ if (delta?.status === 'ok' && !company && source.last_commit) {+ const last = source.last_commit;+ const deltaEntries = (commit: string) => {+ const step = computeSyncDelta(gitRoot, last, commit);+ if (step.status !== 'ok') return null;+ const paths = [...step.manifest.added, ...step.manifest.modified, ...step.manifest.deleted, ...step.manifest.renamed.flatMap(r => [r.from, r.to])].filter(eligible);+ return paths.map(path => ({ path: relative(nativeRoot, join(nativeGitRoot, path)).split(sep).join('/'), sourcePath: sourcePath(path), action: 'import', working: false }));+ };+ const staged = stagedSyncTarget(gitRoot, last, stage?.head ?? target, commit => { const entries = deltaEntries(commit); return !!entries && manifestFits(entries); });+ if ('commit' in staged && staged.commit !== target) return discoverManagedSync(engine, opts, context, { target: staged.commit, head: stage?.head ?? target });+ if ('oversized' in staged) {+ const size = deltaEntries(staged.oversized)?.length ?? selected.length;+ throw opError('request_too_large', 'One commit exceeds the bounded cursor size.',+ `Commit ${staged.oversized.slice(0, 12)} alone changes ${size} syncable entries in ${sourceId} (from ${last.slice(0, 12)}), above the ${cursorBound.entries.toLocaleString('en-US')}-entry and ${Math.round(cursorBound.bytes / 1024 ** 2)} MiB cursor bound, so it cannot be synced in stages; nothing was written. Exclude part of it with --exclude or the sync.exclude config, then run gbrain sync --no-pull --source ${sourceId}.`);+ }+ }+ throw opError('request_too_large', 'Sync discovery exceeds the bounded cursor size.',+ `This sync of ${sourceId} selected ${selected.length} entries, above the 100,000-entry and 16 MiB cursor bound; nothing was written. Narrow it with --exclude or the sync.exclude config, then run gbrain sync --no-pull --source ${sourceId}.`);+ }const discovered: SyncDiscovery = { discoveredAt, ...(released.length ? { releasedHolds: released } : {}), ...(retryTaken.length ? { retryTaken } : {}),- ...(refused.size ? { fileRefusals: [...refused.values()] } : {}), binding: { ...binding, owner_epoch: String(binding.owner_epoch), topology_generation: String(binding.topology_generation) }, root, gitRoot, sourceId, incarnation, from: source.last_commit, target, entries: selected, slugMode, ...(company ? { companyPlan: company.plan } : {}) };+ ...(refused.size ? { fileRefusals: [...refused.values()] } : {}), binding: { ...binding, owner_epoch: String(binding.owner_epoch), topology_generation: String(binding.topology_generation) }, root, gitRoot, sourceId, incarnation, from: source.last_commit, target, entries: selected, slugMode, ...(company ? { companyPlan: company.plan } : {}), ...(stage ? { stagedHead: stage.head } : {}) };// Freeze all logical identities in one database statement, before yielding// between pages. A later interactive edit must conflict with this scan.const identities = await engine.executeRaw<{ id: number; slug: string; source_path: string | null; knowledge_revision: string }>(diff --git a/src/core/persistence/sync-drain.ts b/src/core/persistence/sync-drain.tsindex d665022b5f..00e4b7ddb3 100644--- a/src/core/persistence/sync-drain.ts+++ b/src/core/persistence/sync-drain.ts@@ -708,7 +708,7 @@ export async function drainManagedSync(engine: BrainEngine, opts: SyncOpts, anno// since the pin (an incremental pin..HEAD discovery, which also re-screens holds whose file a later commit changed), so the// invocation ends at HEAD instead of leaving the gap to the next launch. Never a second extra pass: a checkout that keeps// committing would otherwise loop forever.- if (result.drain?.outcome === 'synced' && result.toCommit && !opts.dryRun && !opts.signal?.aborted && result.status !== 'up_to_date') {+ if (result.drain?.outcome === 'synced' && result.toCommit && !opts.dryRun && !opts.signal?.aborted && result.status !== 'up_to_date' && !result.staged) {const head = await headOfSource(engine, opts);if (head && head !== result.toCommit) {if (announce) serr(`[sync] HEAD moved past the pinned target ${result.toCommit.slice(0, 8)} while the run drained; one more pass imports the commits since (to ${head.slice(0, 8)}).`);diff --git a/src/core/persistence/sync-run.ts b/src/core/persistence/sync-run.tsindex 164f4049cf..0b171b813f 100644--- a/src/core/persistence/sync-run.ts+++ b/src/core/persistence/sync-run.ts@@ -287,6 +287,7 @@ function result(cursor: Cursor | CursorHeader, status: SyncResult['status'], readeleted: cursor.counts.deleted, renamed: cursor.counts.renamed ?? 0, chunksCreated: cursor.counts.chunks, embedded: 0, pagesAffected: [],...(cursor.slugCollisions?.length ? { slugCollisions: cursor.slugCollisions } : {}),...(cursor.fileRefusals?.length ? { fileRefusals: cursor.fileRefusals } : {}),+ ...(cursor.stagedHead && !cursor.authority.writer.remote ? { staged: { target: cursor.target, head: cursor.stagedHead } } : {}),waived: { imports: cursor.counts.waived?.imports ?? 0, deletes: cursor.counts.waived?.deletes ?? 0 },filesImported: cursor.index, bankedFiles: cursor.index,managedCursor: { index: cursor.index, total: 'total' in cursor ? cursor.total : cursor.entries.length, ...(cursor.progress ? { progress: cursor.progress } : {}) },diff --git a/test/sync-staged-catchup.test.ts b/test/sync-staged-catchup.test.tsnew file mode 100644index 0000000000..0e874a4a92--- /dev/null+++ b/test/sync-staged-catchup.test.ts@@ -0,0 +1,152 @@+/**+ * #6349 (P2.14): a managed source whose delta since its last synced commit exceeds the cursor bound used to refuse every+ * sync forever. Discovery now stages it: the furthest first-parent commit whose delta fits, found by a forward gallop that+ * verifies every candidate (a net delta is not monotone along history, so binary search has no valid predicate); a drain+ * then takes stage after stage to HEAD. One commit above the bound still refuses, naming that commit. The bound is+ * lowered through the test seam. Synthetic content only.+ */+import { afterAll, afterEach, beforeAll, describe, expect, test } from 'bun:test';+import { execFileSync } from 'node:child_process';+import { randomUUID } from 'node:crypto';+import { mkdirSync, mkdtempSync, rmSync, writeFileSync, unlinkSync, renameSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import type { BrainEngine } from '../src/core/engine.ts';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { claimWorktree } from '../src/core/persistence/ownership.ts';+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';+import { drainManagedSync } from '../src/core/persistence/sync-drain.ts';+import { _setCursorBoundForTest, stagedSyncTarget } from '../src/core/persistence/sync-discovery.ts';+import { performSync } from '../src/commands/sync/perform.ts';+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';+import { testBackends } from './helpers/test-backends.ts';+import { withEnv } from './helpers/with-env.ts';++const home = mkdtempSync(join(tmpdir(), 'gbrain-staged-'));+afterAll(() => rmSync(home, { recursive: true, force: true }));+afterEach(() => _setCursorBoundForTest());++function repo() {+ const root = join(home, `r-${randomUUID().slice(0, 8)}`);+ mkdirSync(join(root, 'notes'), { recursive: true });+ const git = (...args: string[]) => execFileSync('git', ['-C', root, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim();+ const write = (name: string, body = `A synthetic observation about ${name}.`) => writeFileSync(join(root, 'notes', `${name}.md`), `---\ntitle: ${name}\n---\n${body}\n`);+ const remove = (name: string) => unlinkSync(join(root, 'notes', `${name}.md`));+ const move = (from: string, to: string) => renameSync(join(root, 'notes', `${from}.md`), join(root, 'notes', `${to}.md`));+ const commit = (message: string) => { git('add', '-A'); git('-c', 'user.name=Example', '-c', '[email protected]', 'commit', '-qm', message, '--allow-empty'); return git('rev-parse', 'HEAD'); };+ git('init', '-q');+ return { root, git, write, remove, move, commit };+}++describe('stagedSyncTarget (forward gallop, every candidate verified)', () => {+ test('non-monotone history (add 2, add 2, delete 2, add 3) with bound 3: the walk lands past where binary search stops', () => {+ const r = repo();+ r.write('base'); const base = r.commit('base');+ r.write('a'); r.write('b'); const c1 = r.commit('add 2');+ r.write('c'); r.write('d'); const c2 = r.commit('add 2 more');+ r.remove('c'); r.remove('d'); const c3 = r.commit('delete 2');+ r.write('e'); r.write('f'); r.write('g'); const c4 = r.commit('add 3');+ const size = (commit: string) => r.git('diff', '--name-only', `${base}..${commit}`).split('\n').filter(Boolean).length;+ expect([c1, c2, c3, c4].map(size)).toEqual([2, 4, 2, 5]);+ const checked: string[] = [];+ const staged = stagedSyncTarget(r.root, base, c4, commit => { checked.push(commit); return size(commit) <= 3; });+ expect(staged).toEqual({ commit: c3, first: c1 });+ // A binary search over the same predicate checks c2 first, fails, and settles on c1.+ expect(checked).not.toContain(c2);+ });++ test('the first commit alone above the bound is reported oversized', () => {+ const r = repo();+ r.write('base'); const base = r.commit('base');+ for (const n of ['a', 'b', 'c', 'd']) r.write(n);+ const big = r.commit('add 4');+ r.write('e'); const head = r.commit('add 1');+ expect(stagedSyncTarget(r.root, base, head, commit => r.git('diff', '--name-only', `${base}..${commit}`).split('\n').filter(Boolean).length <= 3)).toEqual({ oversized: big });+ });+});++describe('staged managed catch-up on a real brain', () => {+ const engines: BrainEngine[] = [];+ let closePostgres: (() => Promise<void>) | undefined;+ beforeAll(async () => {+ if (testBackends().includes('pglite')) { const lite = new PGLiteEngine(); await lite.connect({}); await lite.initSchema(); engines.push(lite); }+ if (testBackends().includes('postgres')) { const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL!); engines.push(pg.engine); closePostgres = pg.close; }+ }, 120_000);+ afterAll(async () => { for (const engine of engines) { await disposePersistenceConsumer(engine); await engine.disconnect(); } await closePostgres?.(); });++ async function managedSource(engine: BrainEngine) {+ const r = repo();+ const id = `stg-${randomUUID().replace(/-/g, '').slice(0, 16)}`;+ r.write('base'); r.commit('base');+ 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, r.root]);+ await claimWorktree(engine, id, r.root);+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');+ const opts = { sourceId: id, noPull: true, noEmbed: true, noExtract: true };+ expect((await drainManagedSync(engine, opts, false)).drain).toMatchObject({ outcome: 'synced' });+ const pages = async () => (await engine.executeRaw<{ slug: string }>('SELECT slug FROM pages WHERE source_id=$1 AND deleted_at IS NULL ORDER BY slug', [id])).map(p => p.slug);+ const lastCommit = async () => (await engine.executeRaw<{ last_commit: string | null }>('SELECT last_commit FROM sources WHERE id=$1', [id]))[0]!.last_commit;+ return { r, id, opts, pages, lastCommit };+ }++ test('a backlog past the bound drains stage by stage to HEAD (renames, repeated paths, non-monotone history); the page set equals an unbounded sync', () => withEnv({ GBRAIN_HOME: home, GBRAIN_SYNC_FAILURES_DIR: home }, async () => {+ for (const engine of engines) {+ const { r, opts, pages, lastCommit, id } = await managedSource(engine);+ r.write('a'); r.write('b'); r.commit('add 2');+ r.write('c'); r.write('d'); r.commit('add 2 more');+ r.remove('c'); r.remove('d'); r.commit('delete 2');+ r.write('a', 'Edited once.'); r.move('b', 'b2'); r.commit('edit a, rename b');+ r.write('a', 'Edited twice.'); r.write('e'); r.commit('edit a again, add e');+ r.write('f'); r.write('g'); const head = r.commit('add 2 at the end');+ _setCursorBoundForTest({ entries: 3, bytes: 1024 ** 2 });+ const result = await performSync(engine, { ...opts, drain: true });+ expect(result.drain?.outcome).toBe('synced');+ expect(result.staged).toBeUndefined();+ expect(await lastCommit()).toBe(head);+ expect(await pages()).toEqual(['notes/a', 'notes/b2', 'notes/base', 'notes/e', 'notes/f', 'notes/g']);+ expect((await engine.getPage('notes/a', { sourceId: id }))?.compiled_truth).toContain('Edited twice.');+ }+ }), 300_000);++ test('a stage stopped mid-way resumes from its stored cursor; then the next stage reaches HEAD', () => withEnv({ GBRAIN_HOME: home, GBRAIN_SYNC_FAILURES_DIR: home }, async () => {+ for (const engine of engines) {+ const { r, opts, pages, lastCommit } = await managedSource(engine);+ r.write('a'); r.write('b'); const c1 = r.commit('add 2');+ r.write('c'); r.write('d'); const head = r.commit('add 2 more');+ _setCursorBoundForTest({ entries: 3, bytes: 1024 ** 2 });+ const abort = new AbortController();+ let committed = 0;+ const first = await drainManagedSync(engine, { ...opts, signal: abort.signal, onProgress: event => { if (event.phase === 'managed_sync.page_committed' && ++committed === 1) abort.abort(); } }, false);+ expect(first.drain?.outcome).not.toBe('synced');+ expect(first.toCommit).toBe(c1);+ const resumed = await drainManagedSync(engine, opts, false);+ expect(resumed).toMatchObject({ toCommit: c1, staged: { target: c1, head } });+ expect(await lastCommit()).toBe(c1);+ const finished = await drainManagedSync(engine, opts, false);+ expect(finished.staged).toBeUndefined();+ expect(await lastCommit()).toBe(head);+ expect(await pages()).toEqual(['notes/a', 'notes/b', 'notes/base', 'notes/c', 'notes/d']);+ }+ }), 300_000);++ test('the byte bound stages too, and one commit above the bound refuses naming it', () => withEnv({ GBRAIN_HOME: home, GBRAIN_SYNC_FAILURES_DIR: home }, async () => {+ for (const engine of engines) {+ const { r, opts, lastCommit } = await managedSource(engine);+ const before = await lastCommit();+ for (const n of ['p', 'q', 'r', 's']) r.write(n);+ const big = r.commit('add 4 in one commit');+ _setCursorBoundForTest({ entries: 3, bytes: 1024 ** 2 });+ const refusal = await drainManagedSync(engine, opts, false).then(() => null, (error: { code?: string; message: string; suggestion?: string }) => error);+ expect(refusal).toMatchObject({ code: 'request_too_large' });+ expect(refusal!.message).toContain('One commit exceeds the bounded cursor size.');+ expect(refusal!.suggestion).toContain(`Commit ${big.slice(0, 12)} alone changes 4 syncable entries`);+ expect(await lastCommit()).toBe(before);+ // The byte bound: ample entries, but only one entry's worth of bytes per stage.+ _setCursorBoundForTest({ entries: 100, bytes: 120 });+ r.git('reset', '-q', '--hard', before!);+ r.write('x'); const c1 = r.commit('x'); r.write('y'); r.commit('y');+ const staged = await drainManagedSync(engine, opts, false);+ expect(staged.staged?.target).toBe(c1);+ }+ }), 300_000);+});