Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix: CI follow-ups for #5984 (shared validation only inside transactions, connector waits for page mirrors before freezing its file hash, registries and goldens for prepared statements, set-based guards and the backlog check, resumable exit in the stdio owner test)

garrytanae2961651e5b
diff --git a/llms-full.txt b/llms-full.txt
index 008c30c224..ba91e760c9 100644
--- a/llms-full.txt
+++ b/llms-full.txt
@@ -4850,6 +4850,84 @@ results erode trust. The brain becomes unreliable.
With this: edits show up in search within minutes. The vector DB stays current
with the brain repo automatically. You never have to remember to run sync.
+## Catching up a large backlog on managed Postgres
+
+On a managed brain (managed persistence on, Postgres), every changed file
+publishes through its own durable write request, in manifest order. One
+command drains the whole backlog:
+
+```bash
+gbrain sync --source <id> --no-pull --json
+```
+
+`--no-pull` is required on managed brains: the checkout is fast-forwarded by
+`gbrain sources refresh <id>`, never by sync. Sync then catches the index up
+to whatever the checkout holds.
+
+The run prints one line before the first write and a progress line about
+every 10 seconds on stderr:
+
+```
+[sync] managed catch-up: 9382 entries frozen, 9382 remaining; publishing in bulk groups (each page keeps its own request).
+[sync] 1240/9382 processed (1200 written, 40 waived this run) · 42.1 pages/min · indexing ETA 3h13m
+```
+
+On Postgres the drain publishes in **bulk groups**: it freezes up to 16
+following page imports and deletes with the current one, admits them in one
+transaction, and the writer publishes the group in one transaction. Every
+page still gets its own write request, receipt, attribution and failure
+report; if one page fails, the pages before it commit, that page is reported,
+and the pages after it are cancelled and re-frozen once it is fixed. Group size
+adapts so a group takes about `sync.bulk_max_txn_ms` (default 30 s); a
+foreground write waits behind at most one group. Turn bulk off with
+`--no-bulk`, `GBRAIN_SYNC_BULK=0` or `gbrain config set sync.bulk false`. The
+final JSON reports `drain.bulk` (`enabled`, `reason` when off, `groups`,
+`largest_group`). PGLite publishes without network round trips and does not
+use bulk groups.
+
+*Written* pages published a change. *Waived* entries needed no write (an
+unchanged file, or a delete of a page that is already deleted) and advanced
+the cursor without a request. The ETA covers indexing only; embeddings and
+extraction queued by the run drain afterwards. Measured throughput by database
+distance is in [`docs/eval/managed-sync-catchup.md`](../eval/managed-sync-catchup.md).
+
+The run ends in exactly one outcome:
+
+| Outcome | Exit | Meaning | What to do |
+| --- | --- | --- | --- |
+| `synced` | 0 | The cursor reached its target. | Nothing. |
+| `resumable` | 0 | A deadline, `--timeout` or Ctrl-C stopped it; the cursor and accepted writes are intact. | Rerun `next.command`; safe in a loop. |
+| `blocked` | 1 | A page failed or the writer needs intervention. | Follow `next.why`, then run `next.command`. See [drain stops](write-refusals.md#managed-sync-drain-stops). |
+
+**Say to your agent:** *"Catch up my managed brain's sync backlog and tell me
+how long it will take."* or *"My managed sync stopped. Is it safe to rerun?"*
+
+Timing knobs the drain uses:
+
+| Knob | Scope | Default | At expiry |
+| --- | --- | --- | --- |
+| `--timeout <dur>` | Whole drain (per source under `--all`). Never extended by progress. | none | Stops as `resumable`. |
+| `--hard-deadline <dur>` | Whole process, enforced out of band. | none | The drain stops itself about 15 s early as `resumable`; the watchdog stops a hung process. |
+| `GBRAIN_SYNC_MAX_RUNTIME_SECONDS` | Whole process, non-interactive runs. Extends while pages keep committing. | 3600 (non-TTY) | Stops only after `GBRAIN_SYNC_STALL_ABORT_SECONDS` without progress. |
+| `GBRAIN_SYNC_STALL_ABORT_SECONDS` | Progress window for the deadline above. | 900 | The watchdog stops the run and prints the resume command. |
+| No-progress detector | Awaited write and checkout head unchanged. | 30 s and 3 passes | Stops as `blocked` / `drain_stalled` with diagnostics. |
+| Page write wait | One page's (or group's) publication before the drain re-checks. | 30 s inside a drain (5 s, checkpoint 8 s, for a single pass) | The drain re-enters; this is not a stop. |
+| `sync.bulk_max_txn_ms` / `GBRAIN_SYNC_BULK_MAX_TXN_MS` | Target time per bulk group; sizes the next group from the last one's time per page. | 30000 | A smaller next group. |
+| `sync.bulk_size` / `GBRAIN_SYNC_BULK_SIZE` | Largest bulk group. | 16 | — |
+
+Two more tips:
+
+- **Run the catch-up near the database.** Each page costs several database
+ round trips, so a host in the database's region drains far faster than a
+ laptop across the internet.
+- **Triage.** `gbrain sources writer status <id>` shows the oldest unfinished
+ request and why it waits. `gbrain doctor` reports a managed cursor's
+ remaining entries and ETA from any process.
+
+Before this drain shipped, the workaround was a shell loop around
+`gbrain sync --source <id> --no-pull` until it printed `synced`. That loop
+still works, and each run now drains as far as its deadline allows.
+
## Implementation
### Prerequisite: a reachable direct connection
@@ -10097,6 +10175,26 @@ that already reached the verified upstream commit moves on to syncing.
reports `worktree_refresh_stuck` for a refresh active longer than 15 minutes,
with the resume command.
+## Managed sync drain stops
+
+`gbrain sync` on a managed brain keeps going until the source's cursor is done
+(see [catching up a large backlog](live-sync.md#catching-up-a-large-backlog-on-managed-postgres)).
+When it stops early, the run ends in one outcome: `resumable` (exit 0, safe to
+rerun the same command) or `blocked` (exit 1, needs a fix first). `--json`
+carries `outcome`, `drain.stop_reason` and `next: { command, safe_to_loop,
+retry_after_ms, eta_seconds, rate_pages_per_min, why, docs }`. Run
+`next.command`; loop on it only when `next.safe_to_loop` is true.
+
+**Say to your agent:** *"Catch up my managed brain's sync backlog and tell me how long it will take."*
+
+| Stop reason | Code | Outcome | What it means | Recovery |
+| --- | --- | --- | --- | --- |
+| <a id="drain-stopped-at-its-deadline"></a>`deadline` | `writer_pending` | `resumable` | `--timeout`, `--hard-deadline`, Ctrl-C or the run deadline stopped the drain. Accepted page writes keep their request IDs and the cursor is intact. | Rerun `next.command` (the same options). It resumes where the last run stopped. |
+| <a id="drain-stalled"></a>`drain_stalled` | `drain_stalled` | `blocked` | The awaited page write and the oldest unfinished write on its checkout did not change for 30 s across several passes, and nothing on this host can claim it. `drain.stall` names the request, its state, `blocked_reason` and whether this host owns the checkout. | `gbrain sources writer status <source>`. When this host is not the owner, make sure the owner (`gbrain serve`) is running. Then rerun `next.command`. |
+| <a id="drain-database-contention"></a>`database_contention` | `database_contention` | `blocked` (or an error) | Three consecutive passes hit database contention, a statement timeout or a dropped connection, or reading the awaited write's state failed (an authentication or permission failure stops at once). The drain retries transient failures with backoff before giving up. Accepted writes keep their request IDs. | Fix database access (`gbrain engine status --probe`), then rerun `next.command`. |
+| <a id="drain-writer-blocked"></a>`recovery_required`, `owner_unavailable`, `unexpected_file_bytes`, `unexpected_staging_bytes` | `recovery_required` | `blocked` | The checkout's writer needs intervention before more pages can publish: interrupted publication recovery, no live owner, or unexpected bytes in the file or staging area. | `gbrain sources writer status <source>` and the fix it prints. Unexpected bytes are the user's edits; ask before discarding them. Then rerun `next.command`. |
+| <a id="drain-blocked-by-a-failed-page"></a>`blocked_by_failures` | `blocked_by_failures` | `blocked` | A page write failed terminally. `managed_write` and `failures` name the page and cause. Rerunning without a fix returns the same failure. | Fix the cause, then run `next.command` (it adds `--retry-failed`). Ask the user before skipping content. |
+
## Unbound sources on Postgres
A source with a checkout path (`local_path`, or `sync.repo_path` for the
diff --git a/scripts/e2e-test-map.ts b/scripts/e2e-test-map.ts
index 076ed36392..cd1dc5f23f 100644
--- a/scripts/e2e-test-map.ts
+++ b/scripts/e2e-test-map.ts
@@ -24,6 +24,8 @@ const MIGRATION_WAVE_TESTS = [
];
export const E2E_TEST_MAP: Record<string, string[]> = {
+ // #5984: the env-gated wire-level SQL trace for the managed-sync catch-up bench.
+ "src/core/sql-trace.ts": ["test/e2e/sql-trace-postgres.test.ts"],
// Fix wave 8, Lane G: reindex auto-concurrency sizing (#5181).
"src/commands/reindex.ts": ["test/e2e/reindex-auto-workers-5181.test.ts"],
// Fix wave 8, Lane G: deferred ANN build after the embedding re-embed (#5088).
diff --git a/src/commands/doctor/checks/local-audits.ts b/src/commands/doctor/checks/local-audits.ts
index f821574ae4..4f7116055c 100644
--- a/src/commands/doctor/checks/local-audits.ts
+++ b/src/commands/doctor/checks/local-audits.ts
@@ -89,7 +89,7 @@ async function runStubGuard(ctx: DoctorContext): Promise<Check[]> {
}
try {
const { checkManagedSyncBacklog } = await import('./managed-sync-backlog.ts');
- const check = engine ? await checkManagedSyncBacklog(engine, orphanRatioSourceId ? [orphanRatioSourceId] : undefined) : null;
+ const check = await checkManagedSyncBacklog(engine, orphanRatioSourceId ? [orphanRatioSourceId] : undefined);
if (check) checks.push(check);
} catch { /* managed backlog is informational; doctor's other checks report persistence health */ }
@@ -116,7 +116,7 @@ async function runStubGuard(ctx: DoctorContext): Promise<Check[]> {
export const stubGuardEntry: DoctorEntry = {
name: 'stub_guard_24h',
- emits: ['stub_guard_24h', 'sync_failures', 'slug_fallback_audit'],
+ emits: ['stub_guard_24h', 'sync_failures', 'managed_sync_backlog', 'slug_fallback_audit'],
run: runStubGuard,
};
diff --git a/src/commands/doctor/checks/managed-sync-backlog.ts b/src/commands/doctor/checks/managed-sync-backlog.ts
index 536f0aa75b..d77471a8d9 100644
--- a/src/commands/doctor/checks/managed-sync-backlog.ts
+++ b/src/commands/doctor/checks/managed-sync-backlog.ts
@@ -5,7 +5,8 @@ import { formatManagedSyncBacklog, readManagedSyncBacklog } from '../../../core/
const IDLE_MS = 60 * 60_000;
/** #5984: unfinished managed sync cursors, their remaining entries and ETA; warns when one has not advanced for an hour. */
-export async function checkManagedSyncBacklog(engine: BrainEngine, sourceIds?: string[]): Promise<Check | null> {
+export async function checkManagedSyncBacklog(engine: BrainEngine | null, sourceIds?: string[]): Promise<Check | null> {
+ if (!engine) return null;
const backlog = await readManagedSyncBacklog(engine, sourceIds);
if (!backlog.length) return null;
const idle = backlog.filter(b => !b.last_progress_at || Date.now() - Date.parse(b.last_progress_at) > IDLE_MS);
diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.ts
index a84bd94360..ea98ad39b6 100644
--- a/src/core/cli-flag-registry.generated.ts
+++ b/src/core/cli-flag-registry.generated.ts
@@ -70,7 +70,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'init': ['--all', '--allow-create-db', '--allow-docker', '--brain', '--break-lock', '--chat-model', '--check', '--content-root', '--db-only', '--dim', '--embedding-dimensions', '--embedding-model', '--entity', '--expansion-model', '--force', '--git', '--grant-types', '--help', '--http', '--issuer-url', '--json', '--key', '--local-postgres', '--mcp-only', '--mcp-url', '--migrate-only', '--model', '--no-embedding', '--no-expand', '--no-git', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--path', '--pglite', '--prefer-postgres', '--probe', '--provenance', '--quiet', '--schema-pack', '--scopes', '--show-toplevel', '--skip-embed-check', '--source', '--stale', '--status', '--supabase', '--surface', '--to', '--touchpoint', '--url', '--version', '--yes'],
'integrations': ['--auto', '--brain', '--dry-run', '--help', '--json', '--overwrite', '--refresh', '--source', '--target'],
'integrity': ['--accept-pending', '--auto', '--backend', '--background', '--brain', '--confidence', '--cost', '--dry-run', '--explain', '--follow', '--fresh', '--help', '--json', '--limit', '--no-accept-pending', '--progress-interval', '--progress-json', '--quiet', '--review-lower', '--skip-bare-tweet', '--skip-urls', '--source', '--supabase', '--timeout', '--type', '--url', '--wait'],
- 'jobs': ['--abbrev-ref', '--access', '--aliases', '--all', '--allow-empty', '--allow-shell-jobs', '--asof', '--auto', '--background', '--backoff-delay', '--backoff-jitter', '--backoff-type', '--batch-size', '--bound-slug-prefixes', '--brain', '--break-lock', '--by-mention', '--cached', '--catch-up', '--cli-path', '--cluster-errors', '--concurrency', '--confidence', '--confirm-destructive', '--cost-estimate', '--date', '--days', '--delay', '--detach', '--diff-filter', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--entities', '--exclude', '--exclude-standard', '--expect', '--explain', '--fact', '--facts', '--federated-read', '--file', '--filters', '--fix', '--follow', '--force', '--force-break-lock', '--force-retry', '--format', '--fresh', '--from-meetings', '--full', '--full-history', '--hard-deadline', '--health-interval', '--help', '--http', '--idempotency-key', '--ids', '--image', '--images', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--infer-dates', '--inject-bootstrap', '--inline', '--input', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--job-id', '--job-isolation', '--json', '--kind', '--limit', '--lock-duration-ms', '--log-noop', '--markdown', '--max-age', '--max-attempts', '--max-cost-usd', '--max-crashes', '--max-rss', '--max-sources', '--max-stalled', '--max-usd', '--max-waiting', '--mcp-only', '--min-context', '--missing-path', '--mode', '--model', '--multimodal', '--name-only', '--ner', '--nice', '--no-auto-embed', '--no-delegate', '--no-embed', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-inject', '--no-pull', '--no-renames', '--no-schema-pack', '--no-verify', '--no-worker', '--now', '--older-than', '--once', '--order', '--others', '--output', '--override-disabled', '--pace', '--pace-max-concurrency', '--pack', '--page', '--parallel', '--params', '--path', '--pause', '--phase', '--pid-file', '--priority', '--prune-orphans', '--queue', '--quiet', '--reason', '--rebuild', '--redact-secrets', '--reenrich-after', '--refresh-ms', '--repo', '--reset-checkpoint', '--resume', '--retry-failed', '--review-lower', '--segment-limit', '--select', '--serial', '--session', '--show-toplevel', '--sigkill-rescue', '--since', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--sleep', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--stale', '--stats', '--status', '--strategy', '--surface', '--swap-only', '--take', '--target', '--thin', '--thin-threshold', '--timeline', '--timeout', '--timeout-ms', '--trusted-extraction', '--type', '--types', '--uninstall', '--url', '--user', '--vectors', '--verbose', '--verify', '--watch', '--wedge-rescue', '--workers', '--working-tree', '--yes'],
+ 'jobs': ['--abbrev-ref', '--access', '--aliases', '--all', '--allow-empty', '--allow-shell-jobs', '--asof', '--auto', '--background', '--backoff-delay', '--backoff-jitter', '--backoff-type', '--batch-size', '--bound-slug-prefixes', '--brain', '--break-lock', '--by-mention', '--cached', '--catch-up', '--cli-path', '--cluster-errors', '--concurrency', '--confidence', '--confirm-destructive', '--cost-estimate', '--date', '--days', '--delay', '--detach', '--diff-filter', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--entities', '--exclude', '--exclude-standard', '--expect', '--explain', '--fact', '--facts', '--federated-read', '--file', '--filters', '--fix', '--follow', '--force', '--force-break-lock', '--force-retry', '--format', '--fresh', '--from-meetings', '--full', '--full-history', '--hard-deadline', '--health-interval', '--help', '--http', '--idempotency-key', '--ids', '--image', '--images', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--infer-dates', '--inject-bootstrap', '--inline', '--input', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--job-id', '--job-isolation', '--json', '--kind', '--limit', '--lock-duration-ms', '--log-noop', '--markdown', '--max-age', '--max-attempts', '--max-cost-usd', '--max-crashes', '--max-rss', '--max-sources', '--max-stalled', '--max-usd', '--max-waiting', '--mcp-only', '--min-context', '--missing-path', '--mode', '--model', '--multimodal', '--name-only', '--ner', '--nice', '--no-auto-embed', '--no-bulk', '--no-delegate', '--no-embed', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-inject', '--no-pull', '--no-renames', '--no-schema-pack', '--no-verify', '--no-worker', '--now', '--older-than', '--once', '--order', '--others', '--output', '--override-disabled', '--pace', '--pace-max-concurrency', '--pack', '--page', '--parallel', '--params', '--path', '--pause', '--phase', '--pid-file', '--priority', '--prune-orphans', '--queue', '--quiet', '--reason', '--rebuild', '--redact-secrets', '--reenrich-after', '--refresh-ms', '--repo', '--reset-checkpoint', '--resume', '--retry-failed', '--review-lower', '--segment-limit', '--select', '--serial', '--session', '--show-toplevel', '--sigkill-rescue', '--since', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--sleep', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--stale', '--stats', '--status', '--strategy', '--surface', '--swap-only', '--take', '--target', '--thin', '--thin-threshold', '--timeline', '--timeout', '--timeout-ms', '--trusted-extraction', '--type', '--types', '--uninstall', '--url', '--user', '--vectors', '--verbose', '--verify', '--watch', '--wedge-rescue', '--workers', '--working-tree', '--yes'],
'lint': ['--abbrev-ref', '--abort', '--accept-pending', '--all', '--background', '--brain', '--branch', '--cached', '--dry-run', '--exclude', '--exit-code', '--explain', '--file', '--fix', '--follow', '--get', '--get-url', '--git-dir', '--git-path', '--help', '--is-ancestor', '--is-inside-work-tree', '--json', '--local', '--name-only', '--no-accept-pending', '--no-cron', '--no-tags', '--no-verify', '--no-write-fetch-head', '--pat-file', '--path', '--progress-interval', '--progress-json', '--push', '--push-only', '--quiet', '--rebase', '--short', '--show-toplevel', '--source', '--timeout', '--unset-all', '--wait'],
'loops': ['--all', '--as-of', '--brain', '--help', '--json', '--note', '--source', '--stale-ok', '--status', '--top', '--type'],
'lsd': ['--brain', '--force-resume', '--help', '--json', '--judge-model', '--limit', '--list-runs', '--max-cost', '--max-far-set', '--max-ideas-per-judge-call', '--no-save', '--resume', '--save', '--source', '--strict-budget', '--yes'],
@@ -97,12 +97,12 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'reindex-code': ['--accept-pending', '--background', '--brain', '--break-lock', '--concurrency', '--db-url', '--dry-run', '--embedding-dimensions', '--embedding-model', '--explain', '--follow', '--force', '--help', '--json', '--max-cost', '--max-cost-usd', '--max-runtime', '--no-accept-pending', '--no-embed', '--path', '--progress-interval', '--progress-json', '--quiet', '--source', '--status', '--timeout', '--wait', '--workers', '--yes'],
'reindex-frontmatter': ['--brain', '--concurrency', '--dry-run', '--force', '--help', '--json', '--slug-prefix', '--source', '--workers', '--yes'],
'reindex-search-vector': ['--accept-pending', '--background', '--brain', '--dry-run', '--explain', '--follow', '--help', '--json', '--no-accept-pending', '--progress-interval', '--progress-json', '--quiet', '--resume', '--source', '--timeout', '--wait', '--yes'],
- 'reinit-pglite': ['--abbrev-ref', '--all', '--allow-create-db', '--allow-docker', '--allow-empty', '--brain', '--break-lock', '--cached', '--chat-model', '--concurrency', '--confirm-destructive', '--content-root', '--db-only', '--diff-filter', '--embedding-dimensions', '--embedding-model', '--empty', '--entity', '--exclude', '--exclude-standard', '--expansion-model', '--filters', '--fix', '--force', '--force-break-lock', '--format', '--full', '--full-history', '--git', '--grant-types', '--hard-deadline', '--help', '--http', '--include-gitignored', '--include-hidden', '--interval', '--is-ancestor', '--is-shallow-repository', '--issuer-url', '--json', '--key', '--local-postgres', '--max-age', '--max-sources', '--mcp-only', '--mcp-url', '--migrate-only', '--missing-path', '--model', '--name-only', '--no-auto-embed', '--no-delegate', '--no-embed', '--no-embedding', '--no-extract', '--no-git', '--no-gpg-sign', '--no-hard-deadline', '--no-pull', '--no-renames', '--no-schema-pack', '--no-sync', '--no-verify', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--others', '--parallel', '--path', '--pglite', '--prefer-postgres', '--priority', '--provenance', '--quiet', '--repo', '--reset-checkpoint', '--retry-failed', '--schema-pack', '--scopes', '--serial', '--show-toplevel', '--skip-embed-check', '--skip-failed', '--slugs', '--source', '--source-id', '--src-subpath', '--stale', '--status', '--strategy', '--supabase', '--surface', '--timeout', '--to', '--url', '--verify', '--version', '--watch', '--workers', '--working-tree', '--yes'],
+ 'reinit-pglite': ['--abbrev-ref', '--all', '--allow-create-db', '--allow-docker', '--allow-empty', '--brain', '--break-lock', '--cached', '--chat-model', '--concurrency', '--confirm-destructive', '--content-root', '--db-only', '--diff-filter', '--embedding-dimensions', '--embedding-model', '--empty', '--entity', '--exclude', '--exclude-standard', '--expansion-model', '--filters', '--fix', '--force', '--force-break-lock', '--format', '--full', '--full-history', '--git', '--grant-types', '--hard-deadline', '--help', '--http', '--include-gitignored', '--include-hidden', '--interval', '--is-ancestor', '--is-shallow-repository', '--issuer-url', '--json', '--key', '--local-postgres', '--max-age', '--max-sources', '--mcp-only', '--mcp-url', '--migrate-only', '--missing-path', '--model', '--name-only', '--no-auto-embed', '--no-bulk', '--no-delegate', '--no-embed', '--no-embedding', '--no-extract', '--no-git', '--no-gpg-sign', '--no-hard-deadline', '--no-pull', '--no-renames', '--no-schema-pack', '--no-sync', '--no-verify', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--others', '--parallel', '--path', '--pglite', '--prefer-postgres', '--priority', '--provenance', '--quiet', '--repo', '--reset-checkpoint', '--retry-failed', '--schema-pack', '--scopes', '--serial', '--show-toplevel', '--skip-embed-check', '--skip-failed', '--slugs', '--source', '--source-id', '--src-subpath', '--stale', '--status', '--strategy', '--supabase', '--surface', '--timeout', '--to', '--url', '--verify', '--version', '--watch', '--workers', '--working-tree', '--yes'],
'remote': ['--brain', '--help', '--json', '--mcp-only', '--scopes', '--source', '--timeout'],
'repair': ['--all', '--apply', '--brain', '--expect', '--help', '--include-ambiguous', '--include-repairs', '--json', '--limit', '--max-cost', '--max-usd', '--no-embed', '--remediate', '--source', '--stale', '--yes'],
'repair-jsonb': ['--accept-pending', '--background', '--brain', '--dry-run', '--explain', '--follow', '--help', '--json', '--no-accept-pending', '--progress-interval', '--progress-json', '--quiet', '--source', '--supabase', '--timeout', '--url', '--wait'],
'report': ['--brain', '--content', '--dir', '--help', '--json', '--source', '--title', '--type'],
- 'repos': ['--abandon', '--abbrev-ref', '--abort', '--accept-suggested', '--access', '--account', '--add', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--after', '--all', '--all-new', '--allow-unverified-remote', '--allowed-operations', '--app-id', '--app-install', '--app-pem', '--apply', '--audit', '--auto-additive', '--backups', '--before', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--budget-usd-per-day', '--cached', '--calendar-id', '--classify', '--cleanup-dead-local-locks', '--clear', '--client', '--clone-dir', '--confirm-destructive', '--confirm-quiesced', '--count', '--days', '--decisions', '--delegated-namespace', '--delegated-slug-prefixes', '--detect', '--diff-filter', '--dir', '--dry-run', '--exclude', '--exit-code', '--expected-epoch', '--expected-incarnation', '--expected-state', '--federated', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--fix', '--force', '--format', '--from', '--get', '--get-url', '--git-dir', '--git-path', '--github-repo', '--grant-types', '--help', '--history-days', '--http', '--id', '--if-version', '--include', '--include-warns', '--is-ancestor', '--is-inside-work-tree', '--json', '--keep-storage', '--kind', '--limit', '--local', '--manifest', '--max-cost-usd', '--message', '--migrate-legacy', '--name', '--name-only', '--no-cron', '--no-embed', '--no-federate', '--no-federated', '--no-harden', '--no-pull', '--no-tags', '--no-verify', '--no-write-fetch-head', '--operations', '--others', '--out', '--params', '--pat-file', '--path', '--plan', '--preview', '--probe', '--profile', '--push', '--push-only', '--quiet', '--read-sources', '--rebase', '--redirect-uri', '--refresh-operations', '--remove-backup', '--repair', '--replace', '--repos', '--request-id', '--reset-checkpoint', '--reset-default', '--resume', '--retry-failed', '--scope', '--scopes', '--secret', '--self-transfer', '--services', '--set', '--shared-skills', '--short', '--show-toplevel', '--slug-prefixes', '--source', '--source-id', '--source-ids', '--sources', '--stale', '--status', '--surface', '--takes-holders', '--token', '--token-command', '--token-endpoint-auth-method', '--token-env', '--token-ttl', '--unset-all', '--url', '--usage', '--wait-drain', '--yes'],
+ 'repos': ['--abandon', '--abbrev-ref', '--abort', '--accept-suggested', '--access', '--account', '--add', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--after', '--all', '--all-new', '--allow-unverified-remote', '--allowed-operations', '--app-id', '--app-install', '--app-pem', '--apply', '--audit', '--auto-additive', '--backups', '--before', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--budget-usd-per-day', '--cached', '--calendar-id', '--classify', '--cleanup-dead-local-locks', '--clear', '--client', '--clone-dir', '--confirm-destructive', '--confirm-quiesced', '--count', '--days', '--decisions', '--delegated-namespace', '--delegated-slug-prefixes', '--detect', '--diff-filter', '--dir', '--dry-run', '--exclude', '--exit-code', '--expected-epoch', '--expected-incarnation', '--expected-state', '--federated', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--fix', '--force', '--format', '--from', '--get', '--get-url', '--git-dir', '--git-path', '--github-repo', '--grant-types', '--help', '--history-days', '--http', '--id', '--if-version', '--include', '--include-warns', '--is-ancestor', '--is-inside-work-tree', '--json', '--keep-storage', '--kind', '--limit', '--local', '--manifest', '--max-cost-usd', '--message', '--migrate-legacy', '--name', '--name-only', '--no-cron', '--no-embed', '--no-extract', '--no-federate', '--no-federated', '--no-harden', '--no-pull', '--no-schema-pack', '--no-tags', '--no-verify', '--no-write-fetch-head', '--operations', '--others', '--out', '--params', '--pat-file', '--path', '--plan', '--preview', '--probe', '--profile', '--push', '--push-only', '--quiet', '--read-sources', '--rebase', '--redirect-uri', '--refresh-operations', '--remove-backup', '--repair', '--replace', '--repos', '--request-id', '--reset-checkpoint', '--reset-default', '--resume', '--retry-failed', '--scope', '--scopes', '--secret', '--self-transfer', '--services', '--set', '--shared-skills', '--short', '--show-toplevel', '--slug-prefixes', '--source', '--source-id', '--source-ids', '--sources', '--stale', '--status', '--surface', '--takes-holders', '--token', '--token-command', '--token-endpoint-auth-method', '--token-env', '--token-ttl', '--unset-all', '--url', '--usage', '--wait-drain', '--yes'],
'resolvers': ['--backend', '--brain', '--cost', '--help', '--json', '--source'],
'retrieval-upgrade': ['--accept-pending', '--all', '--background', '--batch-size', '--brain', '--catch-up', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--explain', '--facts', '--follow', '--force', '--help', '--ignore-env-override', '--images', '--include-null-signature', '--json', '--max-cost-usd', '--no-accept-pending', '--no-embed', '--non-interactive', '--pace', '--pace-max-concurrency', '--priority', '--progress-interval', '--progress-json', '--quiet', '--reranker', '--retarget', '--slugs', '--source', '--stale', '--status', '--timeout', '--to', '--wait', '--yes'],
'routing-eval': ['--brain', '--help', '--json', '--llm', '--skills-dir', '--source'],
@@ -115,11 +115,11 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'skillpack': ['--all', '--apply-clean-hunks', '--author', '--auto', '--brain', '--dest', '--dry-run', '--env', '--exit-code', '--fast', '--fix', '--force-unlock', '--format', '--from', '--full', '--harness', '--help', '--homepage', '--json', '--license', '--list', '--minimal', '--name-only', '--no-cache', '--no-lint', '--note', '--out', '--overwrite-local', '--persona', '--pure', '--push', '--quick', '--quiet', '--refresh', '--repo', '--schema-pack', '--scope', '--short', '--since', '--skill', '--skills', '--skills-dir', '--skip-doctor', '--source', '--strict', '--stub', '--supabase', '--target', '--tier', '--trust', '--url', '--verify', '--workspace', '--yes'],
'skillpack-check': ['--accept-pending', '--background', '--brain', '--explain', '--fast', '--follow', '--help', '--json', '--list', '--no-accept-pending', '--progress-interval', '--progress-json', '--quiet', '--source', '--strict', '--timeout', '--wait', '--yes'],
'smoke-test': ['--brain', '--help', '--json', '--source'],
- 'sources': ['--abandon', '--abbrev-ref', '--abort', '--accept-suggested', '--access', '--account', '--add', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--after', '--all', '--all-new', '--allow-unverified-remote', '--allowed-operations', '--app-id', '--app-install', '--app-pem', '--apply', '--audit', '--auto-additive', '--backups', '--before', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--budget-usd-per-day', '--cached', '--calendar-id', '--classify', '--cleanup-dead-local-locks', '--clear', '--client', '--clone-dir', '--confirm-destructive', '--confirm-quiesced', '--count', '--days', '--decisions', '--delegated-namespace', '--delegated-slug-prefixes', '--detect', '--diff-filter', '--dir', '--dry-run', '--exclude', '--exit-code', '--expected-epoch', '--expected-incarnation', '--expected-state', '--federated', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--fix', '--force', '--format', '--from', '--get', '--get-url', '--git-dir', '--git-path', '--github-repo', '--grant-types', '--help', '--history-days', '--http', '--id', '--if-version', '--include', '--include-warns', '--is-ancestor', '--is-inside-work-tree', '--json', '--keep-storage', '--kind', '--limit', '--local', '--manifest', '--max-cost-usd', '--message', '--migrate-legacy', '--name', '--name-only', '--no-cron', '--no-embed', '--no-federate', '--no-federated', '--no-harden', '--no-pull', '--no-tags', '--no-verify', '--no-write-fetch-head', '--operations', '--others', '--out', '--params', '--pat-file', '--path', '--plan', '--preview', '--probe', '--profile', '--push', '--push-only', '--quiet', '--read-sources', '--rebase', '--redirect-uri', '--refresh-operations', '--remove-backup', '--repair', '--replace', '--repos', '--request-id', '--reset-checkpoint', '--reset-default', '--resume', '--retry-failed', '--scope', '--scopes', '--secret', '--self-transfer', '--services', '--set', '--shared-skills', '--short', '--show-toplevel', '--slug-prefixes', '--source', '--source-id', '--source-ids', '--sources', '--stale', '--status', '--surface', '--takes-holders', '--token', '--token-command', '--token-endpoint-auth-method', '--token-env', '--token-ttl', '--unset-all', '--url', '--usage', '--wait-drain', '--yes'],
- 'status': ['--abbrev-ref', '--all', '--allow-empty', '--brain', '--break-lock', '--cached', '--concurrency', '--confirm-destructive', '--deadline-ms', '--diff-filter', '--empty', '--exclude', '--exclude-standard', '--fast', '--filters', '--fix', '--force-break-lock', '--format', '--full', '--full-history', '--hard-deadline', '--help', '--include-gitignored', '--include-hidden', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--json', '--max-age', '--max-sources', '--mcp-only', '--missing-path', '--name-only', '--no-auto-embed', '--no-delegate', '--no-embed', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-pull', '--no-renames', '--no-schema-pack', '--no-verify', '--others', '--parallel', '--path', '--priority', '--quiet', '--repo', '--reset-checkpoint', '--retry-failed', '--section', '--serial', '--show-toplevel', '--skip-failed', '--slugs', '--source', '--source-id', '--src-subpath', '--stale', '--strategy', '--timeout', '--url', '--verify', '--watch', '--workers', '--working-tree', '--yes'],
+ 'sources': ['--abandon', '--abbrev-ref', '--abort', '--accept-suggested', '--access', '--account', '--add', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--after', '--all', '--all-new', '--allow-unverified-remote', '--allowed-operations', '--app-id', '--app-install', '--app-pem', '--apply', '--audit', '--auto-additive', '--backups', '--before', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--budget-usd-per-day', '--cached', '--calendar-id', '--classify', '--cleanup-dead-local-locks', '--clear', '--client', '--clone-dir', '--confirm-destructive', '--confirm-quiesced', '--count', '--days', '--decisions', '--delegated-namespace', '--delegated-slug-prefixes', '--detect', '--diff-filter', '--dir', '--dry-run', '--exclude', '--exit-code', '--expected-epoch', '--expected-incarnation', '--expected-state', '--federated', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--fix', '--force', '--format', '--from', '--get', '--get-url', '--git-dir', '--git-path', '--github-repo', '--grant-types', '--help', '--history-days', '--http', '--id', '--if-version', '--include', '--include-warns', '--is-ancestor', '--is-inside-work-tree', '--json', '--keep-storage', '--kind', '--limit', '--local', '--manifest', '--max-cost-usd', '--message', '--migrate-legacy', '--name', '--name-only', '--no-cron', '--no-embed', '--no-extract', '--no-federate', '--no-federated', '--no-harden', '--no-pull', '--no-schema-pack', '--no-tags', '--no-verify', '--no-write-fetch-head', '--operations', '--others', '--out', '--params', '--pat-file', '--path', '--plan', '--preview', '--probe', '--profile', '--push', '--push-only', '--quiet', '--read-sources', '--rebase', '--redirect-uri', '--refresh-operations', '--remove-backup', '--repair', '--replace', '--repos', '--request-id', '--reset-checkpoint', '--reset-default', '--resume', '--retry-failed', '--scope', '--scopes', '--secret', '--self-transfer', '--services', '--set', '--shared-skills', '--short', '--show-toplevel', '--slug-prefixes', '--source', '--source-id', '--source-ids', '--sources', '--stale', '--status', '--surface', '--takes-holders', '--token', '--token-command', '--token-endpoint-auth-method', '--token-env', '--token-ttl', '--unset-all', '--url', '--usage', '--wait-drain', '--yes'],
+ 'status': ['--abbrev-ref', '--all', '--allow-empty', '--brain', '--break-lock', '--cached', '--concurrency', '--confirm-destructive', '--deadline-ms', '--diff-filter', '--empty', '--exclude', '--exclude-standard', '--fast', '--filters', '--fix', '--force-break-lock', '--format', '--full', '--full-history', '--hard-deadline', '--help', '--include-gitignored', '--include-hidden', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--json', '--max-age', '--max-sources', '--mcp-only', '--missing-path', '--name-only', '--no-auto-embed', '--no-bulk', '--no-delegate', '--no-embed', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-pull', '--no-renames', '--no-schema-pack', '--no-verify', '--others', '--parallel', '--path', '--priority', '--quiet', '--repo', '--reset-checkpoint', '--retry-failed', '--section', '--serial', '--show-toplevel', '--skip-failed', '--slugs', '--source', '--source-id', '--src-subpath', '--stale', '--strategy', '--timeout', '--url', '--verify', '--watch', '--workers', '--working-tree', '--yes'],
'storage': ['--brain', '--fix', '--help', '--json', '--repo', '--restore-only', '--source', '--to'],
'sweep': ['--accept-pending', '--background', '--batch-limit', '--brain', '--budget-ms', '--delete-brain', '--explain', '--follow', '--help', '--home', '--json', '--no-accept-pending', '--no-delegate', '--once', '--progress-interval', '--progress-json', '--quiet', '--source', '--timeout', '--wait'],
- 'sync': ['--abbrev-ref', '--abort', '--accept-pending', '--account', '--adopt-columns', '--adopt-permissions', '--all', '--allow-empty', '--apply', '--apply-rewrites', '--auto', '--background', '--batch-size', '--brain', '--branch', '--break-lock', '--by-mention', '--cached', '--catch-up', '--concurrency', '--confirm-destructive', '--content-audit', '--count', '--db-url', '--delete-brain', '--depth', '--detach', '--diff-filter', '--dim', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--exclude', '--exclude-standard', '--expect', '--explain', '--facts', '--fast', '--ff-only', '--filters', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from-meetings', '--full', '--full-history', '--git-dir', '--git-path', '--hard-deadline', '--harness', '--help', '--home', '--http', '--id', '--images', '--include-ambiguous', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--include-repairs', '--index-audit', '--infer-dates', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--json', '--kind', '--lang', '--link-source', '--link-type', '--locks', '--log-noop', '--markdown', '--max-age', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-sources', '--max-usd', '--migrate-legacy', '--migrate-only', '--missing-path', '--multimodal', '--name-only', '--name-status', '--ner', '--no-accept-pending', '--no-auto-embed', '--no-autopilot-install', '--no-delegate', '--no-embed', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-pull', '--no-recurse-submodules', '--no-renames', '--no-schema-pack', '--no-verify', '--older-than', '--operations', '--others', '--overwrite', '--pace', '--pace-max-concurrency', '--pack', '--parallel', '--params', '--path', '--path-format', '--pglite', '--phase', '--pid-file', '--porcelain', '--prefer-postgres', '--preview', '--priority', '--probe', '--probe-pglite', '--progress-interval', '--progress-json', '--prune-orphans', '--query', '--queue', '--quiet', '--reauth', '--rebase', '--rebuild', '--refresh', '--regenerate', '--remediate', '--remediation-plan', '--remove', '--repo', '--request-id', '--reset', '--reset-checkpoint', '--restore-only', '--resume', '--retry-failed', '--scope', '--scopes', '--serial', '--short', '--show-current', '--show-toplevel', '--since', '--skills-dir', '--skip-failed', '--slot', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--stale', '--status', '--stdin', '--strategy', '--supabase', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--timeout', '--to', '--token', '--top-k', '--type', '--url', '--verbose', '--verify', '--version', '--wait', '--watch', '--window', '--workers', '--working-tree', '--yes'],
+ 'sync': ['--abbrev-ref', '--abort', '--accept-pending', '--account', '--adopt-columns', '--adopt-permissions', '--all', '--allow-empty', '--apply', '--apply-rewrites', '--auto', '--background', '--batch-size', '--brain', '--branch', '--break-lock', '--by-mention', '--cached', '--catch-up', '--concurrency', '--confirm-destructive', '--content-audit', '--count', '--db-url', '--delete-brain', '--depth', '--detach', '--diff-filter', '--dim', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--exclude', '--exclude-standard', '--expect', '--explain', '--facts', '--fast', '--ff-only', '--filters', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from-meetings', '--full', '--full-history', '--git-dir', '--git-path', '--hard-deadline', '--harness', '--help', '--home', '--http', '--id', '--images', '--include-ambiguous', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--include-repairs', '--index-audit', '--infer-dates', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--json', '--kind', '--lang', '--link-source', '--link-type', '--locks', '--log-noop', '--markdown', '--max-age', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-sources', '--max-usd', '--migrate-legacy', '--migrate-only', '--missing-path', '--multimodal', '--name-only', '--name-status', '--ner', '--no-accept-pending', '--no-auto-embed', '--no-autopilot-install', '--no-bulk', '--no-delegate', '--no-embed', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-pull', '--no-recurse-submodules', '--no-renames', '--no-schema-pack', '--no-verify', '--older-than', '--operations', '--others', '--overwrite', '--pace', '--pace-max-concurrency', '--pack', '--parallel', '--params', '--path', '--path-format', '--pglite', '--phase', '--pid-file', '--porcelain', '--prefer-postgres', '--preview', '--priority', '--probe', '--probe-pglite', '--progress-interval', '--progress-json', '--prune-orphans', '--query', '--queue', '--quiet', '--reauth', '--rebase', '--rebuild', '--refresh', '--regenerate', '--remediate', '--remediation-plan', '--remove', '--repo', '--request-id', '--reset', '--reset-checkpoint', '--restore-only', '--resume', '--retry-failed', '--scope', '--scopes', '--serial', '--short', '--show-current', '--show-toplevel', '--since', '--skills-dir', '--skip-failed', '--slot', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--stale', '--status', '--stdin', '--strategy', '--supabase', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--timeout', '--to', '--token', '--top-k', '--type', '--url', '--verbose', '--verify', '--version', '--wait', '--watch', '--window', '--workers', '--working-tree', '--yes'],
'takes': ['--accept', '--batch-size', '--brain', '--bucket-size', '--by', '--claim', '--dim', '--dir', '--domain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--evidence', '--expected-revision', '--expired', '--force', '--from-pages', '--help', '--holder', '--include-covered', '--json', '--kind', '--limit', '--max-pages', '--no-embed', '--no-embedding', '--offset', '--outcome', '--pglite', '--quality', '--reject', '--request-id', '--row', '--semantic', '--since', '--sort', '--source', '--source-id', '--stale', '--status', '--supabase', '--to', '--unit', '--until', '--value', '--weight', '--who', '--yes'],
'think': ['--anchor', '--brain', '--calibration-holder', '--help', '--json', '--mcp-only', '--model', '--rounds', '--save', '--since', '--source', '--take', '--until', '--with-calibration'],
'transcripts': ['--accept-pending', '--all', '--all-discovery', '--background', '--brain', '--days', '--dry-run', '--embed', '--explain', '--facts', '--follow', '--format', '--full', '--help', '--include-self', '--json', '--limit', '--max-bytes', '--max-cost-usd', '--no-accept-pending', '--progress-interval', '--progress-json', '--quiet', '--since', '--source', '--source-id', '--timeout', '--wait'],
diff --git a/src/core/doctor-categories.ts b/src/core/doctor-categories.ts
index c7c2ec5e64..a954624a4b 100644
--- a/src/core/doctor-categories.ts
+++ b/src/core/doctor-categories.ts
@@ -140,6 +140,8 @@ export const BRAIN_CHECK_NAMES: ReadonlySet<string> = new Set([
'stale_mentions',
'stub_guard_24h',
'sync_failures',
+ // #5984: unfinished managed sync cursors, their remaining entries and indexing ETA.
+ 'managed_sync_backlog',
'sync_freshness',
'takes_count',
'takes_weight_grid',
diff --git a/src/core/persistence/connector-sync.ts b/src/core/persistence/connector-sync.ts
index 4cc793b20d..22b49f07cd 100644
--- a/src/core/persistence/connector-sync.ts
+++ b/src/core/persistence/connector-sync.ts
@@ -584,6 +584,19 @@ export class ManagedConnectorSync {
pending = outstanding();
}
}
+ /**
+ * #5984: a withdrawal mirror still rewriting this page's file would change the bytes this write freezes as its
+ * expected before-image. Claims already wait for the mirror; admission waits too (within the run's wait budget).
+ */
+ private async awaitPageMirror(slug: string): Promise<void> {
+ if (!this.binding) return;
+ const pending = async () => (await this.engine.executeRaw(`SELECT 1 FROM persistence_effects WHERE worktree_id=$1::uuid AND kind='withdrawal-mirror'
+ AND state IN ('queued','running') AND (NOT (data ? 'targets') OR data->'targets' @> jsonb_build_array(jsonb_build_object('slug',$2::text))) LIMIT 1`,
+ [this.binding!.worktree_id, slug])).length > 0;
+ if (!await pending()) return;
+ startPersistenceConsumer(this.engine, loadConfig() ?? { engine: this.engine.kind }).wake();
+ while (this.remainingWait() > 0 && await pending()) await new Promise(resolve => setTimeout(resolve, 50));
+ }
/** Keeps outstanding writes below the principal's outstanding and intent-byte limits; stops the sweep when it cannot. */
private async makeRoom(): Promise<void> {
const full = () => this.pendingRows.size >= this.outstandingCap ||
@@ -699,6 +712,7 @@ export class ManagedConnectorSync {
private async submit(kind: ConnectorIntentKind, slug: string, sourcePath: string | null, extra: Partial<ConnectorIntent>):
Promise<{ row: WriteRequest | null; pending: boolean; created: boolean }> {
await this.awaitPagePending(slug);
+ await this.awaitPageMirror(slug);
await this.recover(slug);
const snapshot = await this.engine.readPageSnapshot(slug, { sourceId: this.sourceId, includeDeleted: true });
if (kind === 'connector_v2_google_receipts') {
diff --git a/src/core/persistence/sync-prepare.ts b/src/core/persistence/sync-prepare.ts
index 61945c746f..3b7c0a18d1 100644
--- a/src/core/persistence/sync-prepare.ts
+++ b/src/core/persistence/sync-prepare.ts
@@ -60,6 +60,7 @@ export interface SyncIntent extends Record<string, unknown> {
*/
const sharedValidations = new WeakMap<object, Map<string, Promise<{ run_id: string; request_id: string | null; group: string[] | null } | null>>>();
function sharedSyncValidation(tx: BrainEngine, key: string, run: () => Promise<{ run_id: string; request_id: string | null; group: string[] | null } | null>) {
+ if ((tx as { _pageTransaction?: boolean })._pageTransaction !== true) return run();
let byKey = sharedValidations.get(tx);
if (!byKey) { byKey = new Map(); sharedValidations.set(tx, byKey); }
let shared = byKey.get(key);
diff --git a/test/e2e/engine-sql-prepare-parity.test.ts b/test/e2e/engine-sql-prepare-parity.test.ts
index be6772ebdd..5ed8f0f7b8 100644
--- a/test/e2e/engine-sql-prepare-parity.test.ts
+++ b/test/e2e/engine-sql-prepare-parity.test.ts
@@ -53,13 +53,14 @@ describeDb(`engine-sql prepare parity on ${backend}`, () => {
else expect(count).toBe(1);
});
- test("master's executeRaw path keeps its unprepared behavior", async () => {
+ test('executeRaw prepares parameterized statements like converted ones, and never through PgBouncer (#5984)', async () => {
const marker = `engine_sql_raw_${Date.now()}`;
const count = await engine.transaction(async (tx) => {
for (let i = 0; i < 2; i++) await tx.executeRaw(`SELECT $1::int AS v /* ${marker} */`, [i]);
return preparedMatching(engineSql(tx), marker);
});
- expect(count).toBe(0);
+ if (backend === 'pgbouncer') expect(count).toBe(0);
+ else expect(count).toBe(1);
});
test('a zero-parameter multi-statement string is rejected (extended protocol)', async () => {
diff --git a/test/fixtures/goldens/doctor/registry-build-checks.json b/test/fixtures/goldens/doctor/registry-build-checks.json
index 5891604283..aaf5fa0700 100644
--- a/test/fixtures/goldens/doctor/registry-build-checks.json
+++ b/test/fixtures/goldens/doctor/registry-build-checks.json
@@ -133,6 +133,10 @@
"category": "brain",
"name": "sync_failures"
},
+ {
+ "category": "brain",
+ "name": "managed_sync_backlog"
+ },
{
"category": "meta",
"name": "slug_fallback_audit"
diff --git a/test/fixtures/goldens/exports/types.json b/test/fixtures/goldens/exports/types.json
index 99970b8152..79330c450d 100644
--- a/test/fixtures/goldens/exports/types.json
+++ b/test/fixtures/goldens/exports/types.json
@@ -1074,6 +1074,7 @@
"private _connectionStyle",
"private _disconnectPromise",
"private _factsEmbeddingCastSuffix",
+ "private _heldPageKeys",
"private _ownsModuleSingleton",
"private _pageTransaction",
"private _reconnecting",
diff --git a/test/fixtures/goldens/postgres-engine-gauge/acquires-by-case.json b/test/fixtures/goldens/postgres-engine-gauge/acquires-by-case.json
index 53aa11cfa2..6448c96bb8 100644
--- a/test/fixtures/goldens/postgres-engine-gauge/acquires-by-case.json
+++ b/test/fixtures/goldens/postgres-engine-gauge/acquires-by-case.json
@@ -282,7 +282,7 @@
"tx": 1
},
"replaceDerivedLinks#default": {
- "raw": 11,
+ "raw": 8,
"tx": 1
},
"resolveSlugWithAlias#default": {},
diff --git a/test/fixtures/goldens/sql-text/_driver.json b/test/fixtures/goldens/sql-text/_driver.json
index 8456ac5937..c11eebfd38 100644
--- a/test/fixtures/goldens/sql-text/_driver.json
+++ b/test/fixtures/goldens/sql-text/_driver.json
@@ -2035,33 +2035,6 @@
},
"via": "unsafe"
},
- {
- "paramCount": 2,
- "unsafeOptions": {
- "cancelFence": false,
- "prepare": true,
- "simple": false
- },
- "via": "unsafe"
- },
- {
- "paramCount": 2,
- "unsafeOptions": {
- "cancelFence": false,
- "prepare": true,
- "simple": false
- },
- "via": "unsafe"
- },
- {
- "paramCount": 2,
- "unsafeOptions": {
- "cancelFence": false,
- "prepare": true,
- "simple": false
- },
- "via": "unsafe"
- },
{
"paramCount": 3,
"unsafeOptions": {
diff --git a/test/fixtures/goldens/sql-text/links.json b/test/fixtures/goldens/sql-text/links.json
index c9be79b7f8..d6b7fe2b1a 100644
--- a/test/fixtures/goldens/sql-text/links.json
+++ b/test/fixtures/goldens/sql-text/links.json
@@ -284,56 +284,29 @@
{
"lane": "tx",
"params": [
- "string",
- "string"
- ],
- "sql": "INSERT INTO page_write_guards(source_incarnation,slug) VALUES ($1::uuid,$2) ON CONFLICT DO NOTHING",
- "textSha256": "fa56fa770a66caa8ae77b19c2c3ae9caac336d8e8281bc16f09d36a7fcdd74fd"
- },
- {
- "lane": "tx",
- "params": [
- "string",
- "string"
- ],
- "sql": "SELECT slug FROM page_write_guards WHERE source_incarnation=$1::uuid AND slug=$2 FOR UPDATE",
- "textSha256": "3d08e10394edab70fb78946e378dd11528213526b214a8516d8cf3825e87ac19"
- },
- {
- "lane": "tx",
- "params": [
- "string",
- "string"
- ],
- "sql": "SELECT id FROM pages WHERE source_id=$1 AND slug=$2 FOR UPDATE",
- "textSha256": "6c2eb61492fe7470a32169e89b9f04d471f3311d55ff790ad08f4736af483a2c"
- },
- {
- "lane": "tx",
- "params": [
- "string",
- "string"
+ "array<string>",
+ "array<string>"
],
- "sql": "INSERT INTO page_write_guards(source_incarnation,slug) VALUES ($1::uuid,$2) ON CONFLICT DO NOTHING",
- "textSha256": "fa56fa770a66caa8ae77b19c2c3ae9caac336d8e8281bc16f09d36a7fcdd74fd"
+ "sql": "INSERT INTO page_write_guards(source_incarnation,slug) SELECT i,s FROM unnest($1::uuid[],$2::text[]) WITH ORDINALITY AS k(i,s,n) ORDER BY n ON CONFLICT DO NOTHING",
+ "textSha256": "db6394eda2abba2a8ba0e233234bb764b79859d5462be942b725e581e8249151"
},
{
"lane": "tx",
"params": [
- "string",
- "string"
+ "array<string>",
+ "array<string>"
],
- "sql": "SELECT slug FROM page_write_guards WHERE source_incarnation=$1::uuid AND slug=$2 FOR UPDATE",
- "textSha256": "3d08e10394edab70fb78946e378dd11528213526b214a8516d8cf3825e87ac19"
+ "sql": "SELECT g.slug FROM unnest($1::uuid[],$2::text[]) WITH ORDINALITY AS k(i,s,n) JOIN page_write_guards g ON g.source_incarnation=k.i AND g.slug=k.s ORDER BY k.n FOR UPDATE OF g",
+ "textSha256": "69ee3b628ca6ff5d3e9e33077b9b22cb99da711d1bce84a4a566944b81d83d8e"
},
{
"lane": "tx",
"params": [
- "string",
- "string"
+ "array<string>",
+ "array<string>"
],
- "sql": "SELECT id FROM pages WHERE source_id=$1 AND slug=$2 FOR UPDATE",
- "textSha256": "6c2eb61492fe7470a32169e89b9f04d471f3311d55ff790ad08f4736af483a2c"
+ "sql": "SELECT p.id FROM unnest($1::text[],$2::text[]) WITH ORDINALITY AS k(src,s,n) JOIN pages p ON p.source_id=k.src AND p.slug=k.s ORDER BY k.n FOR UPDATE OF p",
+ "textSha256": "d2598c8eb0d051b3f8d25208513a7494b6db488c95574a3781e6db376d945b56"
},
{
"lane": "tx",
diff --git a/test/persistence-sync-stdio-owner.serial.test.ts b/test/persistence-sync-stdio-owner.serial.test.ts
index af8a804e8b..11057420fd 100644
--- a/test/persistence-sync-stdio-owner.serial.test.ts
+++ b/test/persistence-sync-stdio-owner.serial.test.ts
@@ -140,7 +140,7 @@ test('resident-owner failure JSON retains safe scoped diagnostics and the frozen
expect(inspectLockHolder(databasePath).pid).toBe(owner!.pid);
},90000);
-test('resident-owner pending timeout exits nonzero and resumes the same durable request after lock release',async()=>{
+test('resident-owner pending timeout is resumable (exit 0, #5984) and resumes the same durable request after lock release',async()=>{
const path=join(root,'a.md');
const content='A resident source observation waiting for the held worktree lock.\n';
writeFileSync(path,content);
@@ -150,9 +150,9 @@ test('resident-owner pending timeout exits nonzero and resumes the same durable
const args=['sync','--source','workspace','--full','--working-tree','--no-pull','--no-embed','--exclude','excluded.md','--exclude','example.ts','--json','--no-hard-deadline'];
try {
const pending=await cli([...args,'--timeout','1']);
- expect(pending.code).toBe(1);
+ expect(pending.code).toBe(0);
const body=JSON.parse(pending.out);
- expect(body).toMatchObject({sync_status:'partial',reason:'timeout',added:0,modified:0,
+ expect(body).toMatchObject({sync_status:'partial',reason:'timeout',added:0,modified:0,outcome:'resumable',next:{safe_to_loop:true},
managed_write:{source_id:'workspace',slug:'a',path:'a.md',write_error:'write_pending'}});
id=body.managed_write.write_request.request_id;
expect(body.managed_write.write_request.state).not.toBe('committed');
diff --git a/test/persistence-withdrawal-retry.test.ts b/test/persistence-withdrawal-retry.test.ts
index d5ead10599..8e860a3118 100644
--- a/test/persistence-withdrawal-retry.test.ts
+++ b/test/persistence-withdrawal-retry.test.ts
@@ -59,7 +59,7 @@ for (const boundary of ['admission-counter', 'completed-withdrawal'] as const) {
if (key === 'transaction') return (fn: (tx: BrainEngine) => Promise<any>) => nested.transaction(child => fn(wrap(child)));
if (key === 'executeRaw') return async (sql: string, args?: unknown[]) => {
if (sql === 'SELECT incarnation,archived FROM sources WHERE id=$1 FOR UPDATE') { withdrawal = true; sourceTransactions++; }
- if (!injected && boundary === 'admission-counter' && sql === 'SELECT * FROM persistence_counters WHERE key=$1 FOR UPDATE') {
+ if (!injected && boundary === 'admission-counter' && sql.startsWith('SELECT * FROM persistence_counters WHERE key')) {
injected = true;
throw Object.assign(new Error('confirmed counter statement abort'), { code: '55P03' });
}
diff --git a/test/zz-rt-latency.test.ts b/test/zz-rt-latency.test.ts
deleted file mode 100644
index 1a6637e22c..0000000000
--- a/test/zz-rt-latency.test.ts
+++ /dev/null
@@ -1,40 +0,0 @@
-import { expect, test } from 'bun:test';
-import { randomUUID } from 'node:crypto';
-import { mkdirSync, mkdtempSync, writeFileSync, appendFileSync } from 'node:fs';
-import { tmpdir } from 'node:os';
-import { join } from 'node:path';
-import { execFileSync } from 'node:child_process';
-import { PostgresEngine } from '../src/core/postgres-engine.ts';
-import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
-import { claimWorktree } from '../src/core/persistence/ownership.ts';
-import { performSync } from '../src/commands/sync/perform.ts';
-import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
-import { withEnv } from './helpers/with-env.ts';
-
-test('managed catch-up over injected latency', async () => {
- const N = Number(process.env.RT_PAGES ?? 30);
- const home = mkdtempSync(join(tmpdir(), 'rtl-'));
- await withEnv({ GBRAIN_HOME: home }, async () => {
- const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL!);
- const git = (...a: string[]) => execFileSync('git', ['-C', root, ...a], { stdio: 'pipe' });
- const id = `rt-${randomUUID().slice(0, 8)}`; const root = join(home, id); mkdirSync(join(root, 'notes'), { recursive: true }); git('init', '-q');
- for (let i = 0; i < N; i++) writeFileSync(join(root, 'notes', `n${i}.md`), `---\ntitle: Note ${i}\n---\nObservation ${i} about [[notes/n${(i + 1) % N}]].\n`);
- git('add', '.'); git('-c', 'user.name=E', '-c', '[email protected]', 'commit', '-qm', 'x');
- await pg.engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
- await pg.engine.executeRaw("INSERT INTO sources(id,name,local_path,config) VALUES($1,$1,$2,'{}')", [id, root]);
- await claimWorktree(pg.engine, id, root);
- await pg.engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');
- await disposePersistenceConsumer(pg.engine);
- const url = new URL(pg.databaseUrl); url.port = process.env.RT_PROXY_PORT ?? '6666';
- const engine = new PostgresEngine(); await engine.connect({ database_url: url.toString(), poolSize: 4 });
- const t0 = performance.now();
- const r = await performSync(engine, { sourceId: id, noPull: true, noEmbed: true, noExtract: true, drain: true });
- const ms = performance.now() - t0;
- const line = `${process.env.RT_LABEL ?? ''} pages=${N} status=${r.status} wall_ms=${Math.round(ms)} per_page_ms=${Math.round(ms / N)} pages_per_min=${(N / (ms / 60000)).toFixed(1)}`;
- console.log(line); appendFileSync(process.env.RT_OUT!, line + '\n');
- const reqs = await pg.engine.executeRaw<any>(`SELECT intent->>'kind' AS kind, slug, extract(epoch from created_at)*1000 AS c, extract(epoch from published_at)*1000 AS p, extract(epoch from completed_at)*1000 AS d, state FROM persistence_requests WHERE source_id=$1 ORDER BY sequence`, [id]);
- let prev = 0; for (const q of reqs) { console.log(`${q.kind} ${q.slug} admit_gap=${prev ? Math.round(q.c - prev) : 0} admit_to_done=${Math.round(q.d - q.c)} ${q.state}`); prev = q.d; }
- await disposePersistenceConsumer(engine); await engine.disconnect(); await pg.close();
- expect(r.drain?.outcome).toBe('synced');
- });
-}, 1_800_000);