Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
wip(#6340): holds, connection resume, operator contract (pre-docs)
garrytanf31f1d96b140
diff --git a/src/cli.ts b/src/cli.tsindex 3a4157cc88..c403b23520 100755--- a/src/cli.ts+++ b/src/cli.ts@@ -2426,7 +2426,10 @@ async function prepareConnectedDispatch(command: string, args: string[]): Promis// deadline even when the main event loop is starved by a synchronous spin —// the only thing that stops the cron orphan-pileup. Disposed in the finally.let syncWatchdog: { dispose(): void } | null = null;- if (command === 'sync') {+ // #6340: `gbrain sync status` / `gbrain sync unblock` are read-and-schedule commands on the brain's own engine: no+ // watchdog, no serve delegation (a delegate would refuse the subcommand as an unsupported option).+ const syncOperator = command === 'sync' && (args[0] === 'status' || args[0] === 'unblock');+ if (command === 'sync' && !syncOperator) {try {const { resolveSyncHardDeadline } = await import('./commands/sync.ts');const res = resolveSyncHardDeadline(args, {@@ -2452,7 +2455,7 @@ async function prepareConnectedDispatch(command: string, args: string[]): Promis// LiveServeLockError — instead the sync runs INSIDE the serve over its IPC// socket (commands/sync-delegate.ts). Handled === delegated or politely// refused (exit verdict set inside); false falls through unchanged.- if (command === 'sync') {+ if (command === 'sync' && !syncOperator) {const cfgSync = loadConfig();if (await (await import('./commands/sync-persistence-delegate.ts')).maybeDelegateSyncToPersistence(cfgSync, args)) return null;if (cfgSync?.engine === 'pglite' && cfgSync.database_path && !cfgSync.database_url) {diff --git a/src/commands/doctor/checks/git-holds.ts b/src/commands/doctor/checks/git-holds.tsindex 1a79b69cc6..0c18615d77 100644--- a/src/commands/doctor/checks/git-holds.ts+++ b/src/commands/doctor/checks/git-holds.ts@@ -35,7 +35,7 @@ export async function gitHeldFilesCheck(engine: BrainEngine, sourceIds?: string[const route = coverageRoute(source);const steps = holdRepairSteps(source.source_id, route, auto);return { source_id: source.source_id, held: source.missing + source.stale, stale: source.stale, missing: source.missing, ...(route.fences ? { fences: route.fences } : {}), ...(route.concurrent ? { concurrent: route.concurrent } : {}),- ...(route.stalled ? { stalled: route.stalled } : {}),+ ...(route.stalled ? { stalled: route.stalled } : {}), ...(route.dirty ? { dirty: route.dirty } : {}),first: (listing.get(source.source_id) ?? []).map(hold => ({ path: hold.path, code: hold.code, ...(hold.meta.reason ? { reason: hold.meta.reason } : {}), why: gitHoldFix(hold, auto).why })),escalated: source.missing + source.stale - (images.get(source.source_id) ?? 0) > policy.escalateCount,status: `gbrain sources status ${source.source_id}`, repair: steps.commands.join('; '),diff --git a/src/commands/sources-retry-held.ts b/src/commands/sources-retry-held.tsindex 9cfbe3ee07..ac05d9200b 100644--- a/src/commands/sources-retry-held.ts+++ b/src/commands/sources-retry-held.ts@@ -89,8 +89,9 @@ function gitNextStep(sourceId: string, dryRun: boolean, scheduled: Scheduled): {const fences = scheduled.items.filter(item => item.code === 'invalid_fence').length;const concurrent = scheduled.items.filter(item => item.code === 'concurrent_write').length;const stalled = scheduled.items.filter(item => item.code === 'preparation_stalled').length;+ const dirty = scheduled.items.filter(item => item.code === 'worktree_dirty').length;return { text: `${count} held file(s) scheduled for a re-screen; none has run yet. ${automatic} Run it now with: ${sync}, then verify with: gbrain sources status ${sourceId}. `- + `A file that still refuses stays held; ${holdRepairSteps(sourceId, { fences, others: count - fences - concurrent - stalled, concurrent, stalled }, scheduled.fenceAuto).text}.`,+ + `A file that still refuses stays held; ${holdRepairSteps(sourceId, { fences, others: count - fences - concurrent - stalled - dirty, concurrent, stalled, dirty }, scheduled.fenceAuto).text}.`,fix: { argv: scheduled.sync, consent: [], actor: 'agent', requires_exclusive: false, verify,why: `The sync re-screens the ${count} scheduled file(s): each one that now passes imports and its hold clears; the rest stay held without blocking the sync.` } };}diff --git a/src/commands/sync/args.ts b/src/commands/sync/args.tsindex 500eee0425..0e33a6aba2 100644--- a/src/commands/sync/args.ts+++ b/src/commands/sync/args.ts@@ -162,6 +162,18 @@ Options:backlog on managed Postgres).--yes Accept any interactive prompts (CI / non-TTY).+Subcommands:+ gbrain sync status --source <id> [--json]+ Where a managed catch-up stands: cursor, pages+ committed in the last 10 minutes, each hold and the+ last error with class / safe_actions / needs_human,+ and the next action (for an operator agent's loop).+ gbrain sync unblock --source <id> [--apply] [--json]+ Performs the safe action for every hold (re-screens a+ held file whose edit is now committed, retries a+ stalled preparation) and refuses the rest by name.+ Runbook: docs/guides/sync-unblock-runbook.md+See also:gbrain embed --stale Re-embed all stale chunks (post --no-embed).gbrain doctor Diagnose dim mismatches and other sync issues.diff --git a/src/commands/sync/operator.ts b/src/commands/sync/operator.tsnew file mode 100644index 0000000000..7bf5d6cbcb--- /dev/null+++ b/src/commands/sync/operator.ts@@ -0,0 +1,90 @@+/**+ * #6340: `gbrain sync status` and `gbrain sync unblock`, the operator contract+ * for a managed catch-up (core in `src/core/persistence/sync-status.ts`,+ * decision table in `sync-fault-class.ts`, prose in+ * `docs/guides/sync-unblock-runbook.md`). Both speak the agent operator+ * protocol: `--json` prints one envelope with `next` rendered as a fix.+ */+import type { BrainEngine } from '../../core/engine.ts';+import { cliRenderContext, renderAction } from '../../core/agent-output.ts';+import { opError } from '../../core/ops/contract.ts';+import { readSyncStatus, unblockSync } from '../../core/persistence/sync-status.ts';+import { SYNC_FAULT_TABLE } from '../../core/persistence/sync-fault-class.ts';+import { resolveSourceIdEngineFree } from '../../core/source-resolver.ts';++export function printSyncStatusHelp(): void {+ console.log(`Usage: gbrain sync status --source <id> [--json]++Where a managed catch-up stands and what to do next, for an operator agent:+the cursor (index/total, pinned target, last advance), pages committed in the+last 10 minutes, every held file and the last recorded failure, each with+ class page | connection | systemic+ safe_actions retry | retry_when_clean | repair | reconcile | upgrade | none+ needs_human whether a person has to decide or act (human_reason says why)+and one \`next\` action. The loop: run this every few minutes; when+committed_last_10m is 0 and needs_human is false, run+\`gbrain sync unblock --source <id> --apply\`, then the sync it prints; when+needs_human is true, page a person with the slug it names.++Decision table: docs/guides/sync-unblock-runbook.md+`);+}++export function printSyncUnblockHelp(): void {+ console.log(`Usage: gbrain sync unblock --source <id> [--apply] [--json]++Performs the safe action for every held file of a managed source and refuses+the rest by name. Without --apply it previews. Idempotent; it never writes a+page, never clears a hold and never drops content: refusing is the only way+it leaves a file out, and each refusal names the file, why, and its fix.++ worktree_dirty re-screened when its working-tree bytes are committed+ at HEAD now (still dirty: refused still_dirty)+ preparation_stalled re-screened (the writer, not the file, stalled)+ concurrent_write refused: a person reconciles the two versions+ repair-class holds refused with the repair preview to run+ held ${SYNC_FAULT_TABLE.find(rule => rule.code === 'worktree_dirty')!.escalate.split(' ')[1]} times refused: the page keeps moving; needs a person++Then run the sync \`next\` names (the cursor's own options).+`);+}++function sourceOf(args: string[]): string {+ const explicit = args.find((a, i) => args[i - 1] === '--source') ?? null;+ const source = resolveSourceIdEngineFree(explicit, process.cwd());+ if (!source || source === '__all__') throw opError('invalid_params', 'sync status and sync unblock need one source.', 'Pass --source <id>; gbrain sources list --json lists the ids.',+ { fix: { argv: ['gbrain', 'sources', 'list', '--json'], consent: [], actor: 'agent', requires_exclusive: false, why: 'Lists the source ids, read-only.' } });+ return source;+}++export async function runSyncStatus(engine: BrainEngine, args: string[]): Promise<void> {+ if (args.includes('--help') || args.includes('-h')) return printSyncStatusHelp();+ const sourceId = sourceOf(args);+ const status = await readSyncStatus(engine, sourceId);+ const ctx = cliRenderContext();+ const rendered = { ...status, holds: status.holds.map(hold => ({ ...hold, fix: renderAction(hold.fix, ctx) })), next: status.next ? renderAction(status.next, ctx) : null };+ if (args.includes('--json')) { console.log(JSON.stringify(rendered, null, 2)); return; }+ const c = status.cursor;+ console.log(`Source ${sourceId}: ${c ? c.done ? `last run finished at ${c.index}/${c.total} (pinned ${c.pinned_target?.slice(0, 8) ?? '?'})` : `cursor ${c.index}/${c.total} at pinned target ${c.pinned_target?.slice(0, 8) ?? '?'}`+ + `${c.last_advance_at ? `, last advance ${c.last_advance_at}` : ''}` : 'no managed cursor'}`);+ console.log(` committed in the last 10 minutes: ${status.committed_last_10m}${status.rate_pages_per_min !== null ? `, ${status.rate_pages_per_min} pages/min` : ''}`);+ console.log(` holds: ${status.holds.length}${status.holds.length ? ` (${status.holds.filter(h => h.needs_human).length} need a person)` : ''}; last error: ${status.last_error ? `${status.last_error.code} [${status.last_error.class}]` : 'none'}`);+ for (const hold of status.holds) console.log(` ${hold.path}${hold.slug ? ` (${hold.slug})` : ''}: ${hold.code} [${hold.class}] safe: ${hold.safe_actions.join(',')}${hold.needs_human ? ` NEEDS HUMAN: ${hold.human_reason}` : ''}${hold.attempts > 1 ? ` (held ${hold.attempts} times)` : ''}`);+ if (status.last_error) console.log(` ${status.last_error.path ?? ''}: ${status.last_error.code} safe: ${status.last_error.safe_actions.join(',')}${status.last_error.needs_human ? ` NEEDS HUMAN: ${status.last_error.human_reason}` : ''}`);+ if (rendered.next) console.log(` Next: ${rendered.next.command ?? rendered.next.argv?.join(' ')}\n Why: ${rendered.next.why}`);+ else console.log(' Next: nothing; the source is synced and holds nothing.');+}++export async function runSyncUnblock(engine: BrainEngine, args: string[]): Promise<void> {+ if (args.includes('--help') || args.includes('-h')) return printSyncUnblockHelp();+ const sourceId = sourceOf(args);+ const outcome = await unblockSync(engine, sourceId, { apply: args.includes('--apply') });+ const ctx = cliRenderContext();+ const rendered = { ...outcome, refused: outcome.refused.map(entry => ({ ...entry, fix: renderAction(entry.fix, ctx) })), next: outcome.next ? renderAction(outcome.next, ctx) : null };+ if (args.includes('--json')) { console.log(JSON.stringify(rendered, null, 2)); return; }+ console.log(`Source ${sourceId}: ${outcome.applied.length} held file(s) ${outcome.apply ? 'scheduled for a re-screen' : 'would be scheduled for a re-screen (preview; add --apply)'}, ${outcome.refused.length} refused.`);+ for (const entry of outcome.applied) console.log(` ${entry.path}: ${entry.code} → ${entry.action}: ${entry.detail}`);+ for (const entry of outcome.refused) console.log(` ${entry.path}: ${entry.code} refused (${entry.reason})${entry.needs_human ? ' NEEDS HUMAN' : ''}`);+ if (rendered.next) console.log(` Next: ${rendered.next.command ?? rendered.next.argv?.join(' ')}\n Why: ${rendered.next.why}`);+ else console.log(' Next: nothing held.');+}diff --git a/src/commands/sync/run.ts b/src/commands/sync/run.tsindex 32f876b907..60871e5e6a 100644--- a/src/commands/sync/run.ts+++ b/src/commands/sync/run.ts@@ -63,6 +63,11 @@ export async function runSyncInner(engine: BrainEngine, args: string[]) {if (args[0] === 'trigger') {return runSyncTrigger(engine, args.slice(1));}+ // #6340: the operator contract (status / unblock) reads and schedules; it never runs a sync.+ if (args[0] === 'status' || args[0] === 'unblock') {+ const { runSyncStatus, runSyncUnblock } = await import('./operator.ts');+ return args[0] === 'status' ? runSyncStatus(engine, args.slice(1)) : runSyncUnblock(engine, args.slice(1));+ }// v0.37 fix wave (Lane D.4 + CDX2-12): print usage when `--help`/`-h` is// passed. Pre-fix this was unreachable because the dispatcher's genericdiff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex abd373658d..9ce49b0d28 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -340,6 +340,10 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText }// R2 facts extraction default (GBRA-60); `since` is a placeholder equal to the branch's VERSION until the merge-slot stamp.{ since: '0.60.118.0', text: 'Background fact extraction now uses claude-haiku-5-5 instead of claude-sonnet-4-6 when no model is set and the reasoning tier resolves through Anthropic (less than a tenth of the cost; it passed a facts-absorb quality gate against Sonnet 4.6, with 4.6 points fewer planted items covered on natural transcripts). `gbrain config set facts.extraction_model anthropic:claude-sonnet-4-6` keeps the previous model; installs that resolve through OpenAI, or set facts.extraction_model, models.tier.reasoning or models.default, are unchanged.' },{ since: '0.60.119.0', text: 'On Postgres, gbrain now keeps one small file per database under `~/.gbrain/cache/pg-types/` with the parameter types the database described for gbrain\'s statements (hashes and type numbers only, no SQL text or credentials), so the next command skips those round trips; it is ignored when the Postgres or schema version differs and deleted when a migration runs. `GBRAIN_PG_TYPE_CACHE_PERSIST=0` keeps the types in memory only.' },+ // #6340 (GBRA-64); `since` is a placeholder equal to the branch's VERSION until the merge-slot stamp.+ { since: '0.60.119.0', text: 'A managed catch-up no longer stops on a page that moved under it: a database page that changed after the manifest was frozen is held as `concurrent_write` (re-bound and passed when it already holds what the file would import), uncommitted working-tree bytes that match neither the pinned commit nor the page are held with the new code `worktree_dirty`, and working-tree bytes committed at HEAD past the pinned target are imported as HEAD has them; the run finishes `synced` with the holds listed instead of `blocked_by_failures` (`sync.holds=fail` and company-brain sources keep blocking).' },+ { since: '0.60.119.0', text: 'A managed sync drain that loses its database connection (`write ECONNABORTED`, `ECONNRESET`, `ETIMEDOUT`, `EPIPE`) now reconnects and retries at 5, 15 and 45 seconds instead of exiting, and a connection fault is no longer recorded in the sync failure ledger, so a relaunch (with or without `--retry-failed`) resumes at the stored cursor against the frozen manifest instead of re-freezing it; three drops in a row with no page committed between them stop the drain `connection_lost`.' },+ { since: '0.60.119.0', text: 'New commands `gbrain sync status --source <id> --json` (cursor position, pages committed in the last 10 minutes, each hold and the last error with `class`, `safe_actions` and `needs_human`, and `next`) and `gbrain sync unblock --source <id> [--apply] --json` (performs the safe action for every hold and the last error, refuses the rest by name) let an operator agent drive a catch-up without a human; the decision table is `docs/guides/sync-unblock-runbook.md`.' },];/** The newest disclosed change's release: the notice id moves only when a release adds rows. */diff --git a/src/core/error-catalogue.ts b/src/core/error-catalogue.tsindex 3a2278fd5f..2f83ecaec3 100644--- a/src/core/error-catalogue.ts+++ b/src/core/error-catalogue.ts@@ -75,6 +75,7 @@ export const ERROR_CATALOGUE = {sync_drain_preparation_abandoned: { code: 'preparation_abandoned', docs: 'docs/guides/write-refusals.md#drain-preparation-abandoned' },sync_drain_preparation_systemic: { code: 'preparation_systemic', docs: 'docs/guides/write-refusals.md#preparation_systemic' },sync_drain_write_capacity: { code: 'queue_capacity', docs: 'docs/guides/write-refusals.md#drain-write-capacity' },+ sync_drain_connection_lost: { code: 'connection_lost', docs: 'docs/guides/sync-unblock-runbook.md#connection' },} as const satisfies Record<string, CatalogueEntry>;export type CatalogueName = keyof typeof ERROR_CATALOGUE;diff --git a/src/core/error-registry.ts b/src/core/error-registry.tsindex b0fcf9b948..03364d39d5 100644--- a/src/core/error-registry.ts+++ b/src/core/error-registry.ts@@ -105,6 +105,11 @@ export const CODES = {config_error: { class: 'caller', summary: "A required configuration value or directory is missing or invalid." },confirmation_required: { class: 'consent', summary: "The command needs the user's authorization before it runs; nothing was changed.", exit: 3 },conflicting_source_scope: { class: 'caller', summary: "--source and --all-sources were both given." },+ connection_lost: { class: 'retryable', retryable: true, actor: 'agent',+ summary: "The managed sync drain lost its database connection three times in a row without committing a page in between, so it stopped where the cursor stands; nothing is recorded against the source.",+ why: "A pooler drop (ECONNABORTED, ECONNRESET, ETIMEDOUT, EPIPE) is a transport fault, not a page fault: the drain reconnects and retries at 5, 15 and 45 seconds, and the frozen manifest and cursor stay as they are. Three consecutive drops with no progress mean the database is unreachable from here for now.",+ docs: 'docs/guides/sync-unblock-runbook.md#connection',+ suggestion: 'Check the database URL and pooler (gbrain doctor --json), then rerun the same gbrain sync; it resumes at the stored cursor without re-freezing the manifest.' },connector_account_changed: { class: 'caller', summary: "The connector credential resolves to a different account than the source is pinned to." },connector_fence_below_timeline: { class: 'caller', summary: "A stored page carries a fence the connector render cannot preserve." },connector_holds_exhausted: { class: 'caller', summary: "The source holds the maximum number of failed items; its cursor did not advance." },@@ -391,6 +396,11 @@ export const CODES = {withdrawal_provenance: { class: 'server', summary: "The withdrawal target manifest is invalid." },write_claim_lost: { class: 'retryable', summary: "Execution claim changed before publication." },write_pending: { class: 'retryable', summary: "The write was accepted and is still pending; it may commit later.", exit: 10 },+ worktree_dirty: { class: 'caller', retryable: false, actor: 'agent',+ summary: "A managed sync held a file whose uncommitted working-tree bytes match neither the pinned commit nor the current page; the rest of the source synced and the local edit was not overwritten.",+ why: "On a live checkout an agent may be mid-edit on a file the catch-up reaches. The bytes are not committed at HEAD, so sync cannot tell a deliberate local change from a stray one, and importing the pinned version would discard the edit; before #6340 this refusal stopped the whole run.",+ docs: 'docs/guides/write-refusals.md#worktree_dirty',+ suggestion: 'Commit the file (or restore it), then run gbrain sync unblock --source <id> --apply (it re-screens every held file that is now committed) and the same gbrain sync; a later commit that changes the file re-screens it on its own.' },writer_admin_intent_required: { class: 'host_only', summary: "Topology changes require an action-specific --admin-intent and the --expected-state from a reviewed writer status." },writer_admin_locked: { class: 'host_only', summary: "Writer administration is locked; deactivation was not applied." },writer_admin_state_changed: { class: 'caller', summary: "Writer topology changed since inspection; the administrative request was not applied." },diff --git a/src/core/persistence/held-reads.ts b/src/core/persistence/held-reads.tsindex 91c32aea5b..5c72b77afb 100644--- a/src/core/persistence/held-reads.ts+++ b/src/core/persistence/held-reads.ts@@ -35,7 +35,9 @@ export interface HeldPage { record: GitHoldRecord; revision: string | null; fenc*/export interface HeldCoverage { source_id: string; missing: number; stale: number; fences?: number; concurrent?: number;/** #6278 `preparation_stalled` holds: the writer stalled, not the file; they route to writer status and a re-screen. */- stalled?: number }+ stalled?: number;+ /** #6340 `worktree_dirty` holds: an uncommitted local edit; they clear once the file is committed and re-screened. */+ dirty?: number }/** `get_page.file_held`. */export interface FileHeld {@@ -92,10 +94,10 @@ export function readHeldCoverage(engine: Exec, scope: { sourceId?: string; sourcconst ids = scope.sourceIds ?? (scope.sourceId !== undefined && scope.sourceId !== ALL_SOURCES ? [scope.sourceId] : null);if (ids && !ids.length) return Promise.resolve([]);return cached(request, `coverage:${ids ? [...ids].sort().join(',') : '*'}`, async () => {- const rows = await engine.executeRaw<{ source_id: string; count: number | string; stale: number | string; fences: number | string; concurrent: number | string; stalled: number | string }>(`SELECT s.id AS source_id,+ const rows = await engine.executeRaw<{ source_id: string; count: number | string; stale: number | string; fences: number | string; concurrent: number | string; stalled: number | string; dirty: number | string }>(`SELECT s.id AS source_id,COALESCE((h.completed_keys->0->>'count')::int,0) AS count, COALESCE((h.completed_keys->0->>'stale')::int,0) AS stale,COALESCE((h.completed_keys->0->>'fences')::int,0) AS fences, COALESCE((h.completed_keys->0->>'concurrent')::int,0) AS concurrent,- COALESCE((h.completed_keys->0->>'stalled')::int,0) AS stalled+ COALESCE((h.completed_keys->0->>'stalled')::int,0) AS stalled, COALESCE((h.completed_keys->0->>'dirty')::int,0) AS dirtyFROM op_checkpoints h JOIN sources s ON h.fingerprint=s.id||':'||s.incarnation::textWHERE h.op=$1 AND s.archived IS NOT TRUE AND ($2::text[] IS NULL OR s.id=ANY($2::text[]))AND COALESCE((h.completed_keys->0->>'count')::int,0)>0@@ -104,15 +106,16 @@ export function readHeldCoverage(engine: Exec, scope: { sourceId?: string; sourcconst count = Number(row.count), stale = Math.min(Number(row.stale), count), fences = Math.min(Number(row.fences), count);const concurrent = Math.min(Number(row.concurrent), count - fences);const stalled = Math.min(Number(row.stalled), count - fences - concurrent);- return { source_id: row.source_id, missing: count - stale, stale, ...(fences ? { fences } : {}), ...(concurrent ? { concurrent } : {}), ...(stalled ? { stalled } : {}) };+ const dirty = Math.min(Number(row.dirty), count - fences - concurrent - stalled);+ return { source_id: row.source_id, missing: count - stale, stale, ...(fences ? { fences } : {}), ...(concurrent ? { concurrent } : {}), ...(stalled ? { stalled } : {}), ...(dirty ? { dirty } : {}) };});});}/** D6: which repair a held source needs, from its counts. */export function coverageRoute(source: HeldCoverage): HoldRepairRoute {- const fences = source.fences ?? 0, concurrent = source.concurrent ?? 0, stalled = source.stalled ?? 0;- return { fences, others: Math.max(0, source.missing + source.stale - fences - concurrent - stalled), ...(concurrent ? { concurrent } : {}), ...(stalled ? { stalled } : {}) };+ const fences = source.fences ?? 0, concurrent = source.concurrent ?? 0, stalled = source.stalled ?? 0, dirty = source.dirty ?? 0;+ return { fences, others: Math.max(0, source.missing + source.stale - fences - concurrent - stalled - dirty), ...(concurrent ? { concurrent } : {}), ...(stalled ? { stalled } : {}), ...(dirty ? { dirty } : {}) };}/**@@ -128,6 +131,7 @@ export function hostOperatorFix(sources: ReadonlyArray<{ source_id: string; routconst fences = sources.filter(source => source.route && source.route.fences > 0).map(source => `'${fencePreviewArgv(source.source_id).join(' ')}'`);const concurrent = sources.filter(source => source.route?.concurrent).map(source => source.source_id);const stalled = sources.filter(source => source.route?.stalled).map(source => source.source_id);+ const dirty = sources.filter(source => source.route?.dirty).map(source => source.source_id);const first = sources[0]!;const parts = [...(frontmatter.length ? [`Please run ${frontmatter.join(', ')} on the brain host to preview the fixes, then apply them.`] : []),@@ -135,6 +139,7 @@ export function hostOperatorFix(sources: ReadonlyArray<{ source_id: string; rout+ `to see each one's state and repair the rest now, run ${fences.join(', ')} on the brain host (a read-only preview that prints the apply command).`] : []),...(concurrent.length ? [`Some notes changed in their files while an agent saved a different version to the brain, so both were kept: on the brain host run ${concurrent.map(id => `'gbrain sources status ${id}'`).join(', ')} and reconcile each named note with 'gbrain sources reconcile <source> <slug> --preview'.`] : []),...(stalled.length ? [`Some files are held because the brain's write owner could not finish preparing them (the files themselves are fine): on the brain host run ${stalled.map(id => `'gbrain sources writer status --source ${id} --json'`).join(', ')} to see what the owner was stuck on, fix that or upgrade gbrain, then 'gbrain sources retry-held <source>' and the same sync.`] : []),+ ...(dirty.length ? [`Some files have uncommitted edits in the brain's checkout that sync would not overwrite: on the brain host commit them, then run ${dirty.map(id => `'gbrain sync unblock --source ${id} --apply'`).join(', ')} (or 'gbrain sources retry-held <source>') and the same sync.`] : []),];return { argv: holdRepairSteps(first.source_id, first.route ?? { fences: 0, others: 1 }).argv, consent: [], actor: 'host_admin', requires_exclusive: false, why,user_message: `Some files in your brain could not be imported, so answers from it can miss or show outdated notes. ${parts.join(' ')}` };@@ -143,7 +148,7 @@ export function hostOperatorFix(sources: ReadonlyArray<{ source_id: string; rout/** The route of one hold record. */export function recordRoute(record: Pick<GitHoldRecord, 'code'>): HoldRepairRoute {return record.code === 'invalid_fence' ? { fences: 1, others: 0 } : record.code === 'concurrent_write' ? { fences: 0, others: 0, concurrent: 1 }- : record.code === 'preparation_stalled' ? { fences: 0, others: 0, stalled: 1 } : { fences: 0, others: 1 };+ : record.code === 'preparation_stalled' ? { fences: 0, others: 0, stalled: 1 } : record.code === 'worktree_dirty' ? { fences: 0, others: 0, dirty: 1 } : { fences: 0, others: 1 };}/**diff --git a/src/core/persistence/sync-drain.ts b/src/core/persistence/sync-drain.tsindex 6fd3516365..f762aceda4 100644--- a/src/core/persistence/sync-drain.ts+++ b/src/core/persistence/sync-drain.ts@@ -34,7 +34,9 @@ export type DrainStopReason = 'deadline' | 'drain_stalled' | 'database_contentio/** #6278: the run's breaker tripped on `preparation_stalled` receipts (one systemic diagnostic instead of a pile of holds). */| 'preparation_systemic'/** #6278 (B7): the sync's next admission was refused for the whole no-progress window because other requests held the writer's outstanding-request cap. */- | 'write_capacity';+ | 'write_capacity'+ /** #6340: the database connection dropped `CONNECTION_STRIKES` times in a row with no page committed between the drops; the cursor stands, the same command resumes it. */+ | 'connection_lost';/** #6278 (B7): what the drain waited on when `write_capacity` stopped it: the counts the last refusal carried and how long it waited. */export interface DrainCapacityWait { outstanding: number | null; limit: number | null; scope: 'principal' | 'brain' | null; waited_seconds: number }/** #6278: what a stalled head's live claim says it is doing (`claim_phase`, stamped by its owner on every renewal). */@@ -114,6 +116,10 @@ export interface DrainReport {retry_after_ms?: number;stall?: DrainStall;capacity?: DrainCapacityWait;+ /** #6340 `connection_lost`: how many drops in a row ended the drain and the last error's text (message only, never a URL). */+ connection?: { drops: number; last_error: string };+ /** #6340: HEAD moved past the pinned target while the run drained, so the drain took exactly one more pass for the commits since (never a second). */+ extra_pass?: { from: string; to: string };/** DX-A5: whether pages were published in bulk groups, and why not when they were not. */bulk?: { enabled: boolean; reason: string | null; groups: number; grouped_pages: number; largest_group: number;/** #5984 admit-ahead: groups admitted while the previous group was still publishing. */@@ -139,6 +145,10 @@ const STALL_PASSES = 3;export const STALL_GRACE_MS = 30_000;const SYNC_PREPARATION_DEFAULT_MS = 120_000, MAINTENANCE_PREPARATION_DEFAULT_MS = 120_000, PREPARATION_CEILING_DEFAULT_MS = 600_000;const TRANSIENT_ATTEMPTS = 3;+/** #6340: a dropped database connection (a pooler drop mid-statement) is retried on this schedule after a reconnect; pooler recovery is seconds, not milliseconds. */+export const CONNECTION_RETRY_MS = [5_000, 15_000, 45_000] as const;+/** #6340: consecutive connection drops with no page committed between them that end the drain `connection_lost`. */+export const CONNECTION_STRIKES = CONNECTION_RETRY_MS.length;/** #6278 (B7): the longest pause between admission retries while other requests hold the writer's outstanding cap. */const CAPACITY_RETRY_MAX_MS = 5_000;/** #6278 (B7): the page counts of a run a drain finished before yielding for the next one. */@@ -183,6 +193,18 @@ export function formatDuration(seconds: number): string {return h ? `${h}h${String(m).padStart(2, '0')}m` : `${m}m${String(seconds % 60).padStart(2, '0')}s`;}+/**+ * #6340: whether `error` is the database connection going away under the pass (a pooler drop, a reset socket, a+ * timed-out write). `CONNECTION_DESTROYED` / `CONNECTION_CLOSED` are left out on purpose: #6329 classifies those as+ * this process's own settle of a cancelled statement after the owner's deadline, which becomes a+ * `preparation_stalled` receipt on the stall path, never a transport retry.+ */+export function isConnectionDrop(error: unknown): boolean {+ const code = getCode(error);+ if (code === 'CONNECTION_DESTROYED' || code === 'CONNECTION_CLOSED') return false;+ return isRetryableConnError(error);+}+/** Named transient failures the drain retries; anything else ends the drain (CEO-A31). */function transientDelay(error: unknown, attempt: number, refreshWaitedMs: number, baseMs: number): number | null {if (error instanceof OperationError && error.code === 'worktree_refreshing') {@@ -198,6 +220,12 @@ function transientDelay(error: unknown, attempt: number, refreshWaitedMs: numberreturn baseMs * 4 ** (attempt - 1);}+/** The error's message (or code), with anything that looks like a connection URL removed. */+function errorText(error: unknown): string {+ const text = error instanceof Error ? error.message : typeof error === 'object' && error && 'code' in error ? String((error as { code: unknown }).code) : String(error);+ return text.replace(/\b\w+:\/\/\S+/g, '<url>').slice(0, 200);+}+function sleep(ms: number, signal?: AbortSignal): Promise<void> {if (signal?.aborted) return Promise.resolve();return new Promise(resolve => {@@ -237,6 +265,8 @@ export interface StallProbe {export interface DrainInput {pass(signal: AbortSignal | undefined, onProgress: NonNullable<SyncOpts['onProgress']>): Promise<SyncResult>;+ /** #6340: recovers the engine's pool before a connection-class retry (`engine.reconnect`); absent for callers without one. */+ reconnect?(error: unknown): Promise<void>;signal?: AbortSignal;onProgress?: SyncOpts['onProgress'];probe?: StallProbe;@@ -281,6 +311,8 @@ export async function runDrain(input: DrainInput): Promise<SyncResult> {let last: SyncResult | undefined, capacity: { since: number; attempts: number } | null = null;// #6278 (B7): a pass may finish one run and yield for the next (re-screens scheduled while it ran); the counts of finished runs carry into the report.let carried: RunCounts | null = null;+ // #6340: consecutive connection drops since the last committed page; a commit between drops resets the count.+ let drops = 0;const remaining = () => total === null ? null : Math.max(0, total - index);const every = input.progressMs ?? PROGRESS_EVERY_MS;// #6278: the progress line prints on commits; while nothing commits, a timer names the stall instead of an ETA that assumes none.@@ -318,7 +350,7 @@ export async function runDrain(input: DrainInput): Promise<SyncResult> {if (event.phase === 'managed_sync.lanes' && event.lanes) lanes = { effective: event.lanes.effective, stepDown: event.lanes.stepDown, overlapped: event.lanes.overlapped, fallbacks: event.lanes.fallbacks };if (event.phase !== 'managed_sync.page_committed') return;if (event.waived) waived++; else written++;- lastCommitAt = Date.now();+ lastCommitAt = Date.now(); drops = 0;noteForwardProgress();if (input.announce && Date.now() - lastLine >= PROGRESS_EVERY_MS) {lastLine = Date.now();@@ -367,6 +399,18 @@ export async function runDrain(input: DrainInput): Promise<SyncResult> {await sleep(Math.min(CAPACITY_RETRY_MAX_MS, (input.backoffMs ?? 250) * 2 ** capacity.attempts++), signal);continue;}+ // #6340: a dropped connection is a transport fault, not a page fault: reconnect, wait 5/15/45 s, and re-enter the pass+ // at the stored cursor (nothing was recorded against the source). Three drops with no page committed between them+ // end the drain `connection_lost` with the same resume command; a drop that then moves data is a non-event.+ if (isConnectionDrop(error) && !signal?.aborted) {+ if (++drops >= CONNECTION_STRIKES) return finish(last ?? NO_PASS_RESULT, 'blocked', 'connection_lost', { connection: { drops, last_error: errorText(error) } });+ const delay = input.backoffMs !== undefined ? input.backoffMs * 4 ** (drops - 1) : CONNECTION_RETRY_MS[drops - 1]!;+ if (input.announce) serr(`[sync] ${index}/${total ?? '?'} processed · database connection dropped (${errorText(error)}); reconnecting and retrying in ${formatDuration(Math.round(delay / 1000))} (${drops} of ${CONNECTION_STRIKES})`);+ await sleep(delay, signal);+ if (signal?.aborted) throw error;+ await input.reconnect?.(error).catch(() => undefined);+ continue;+ }const delay = transientDelay(error, ++attempt, refreshWaitedMs, input.backoffMs ?? 250);if (delay === null || signal?.aborted) throw error;if (error instanceof OperationError && (error.code === 'worktree_refreshing' || error.detail === 'database_contention')) refreshWaitedMs += delay;@@ -572,6 +616,7 @@ export async function drainManagedSync(engine: BrainEngine, opts: SyncOpts, annolet result: SyncResult | undefined;try {result = await runDrain({ signal: opts.signal, onProgress: opts.onProgress, probe: engineStallProbe(engine, opts.sourceId), announce,+ reconnect: error => engine.reconnect({ error }),bulk: { enabled: bulk.enabled, reason: bulk.reason, lanes: bulk.lanes ?? 1, lanesMax: bulk.lanesMax, lanesReason: bulk.lanesReason ?? null, lanesCap: bulk.lanesCap },pass: (signal, onProgress) => performManagedSync(engine, { ...opts, signal, onProgress, drainStartedAt, ...(bulk.enabled ? { bulk: { ...bulk, laneRun } } : {}) }) });} finally {@@ -583,6 +628,22 @@ export async function drainManagedSync(engine: BrainEngine, opts: SyncOpts, annoif (lanes && stats) Object.assign(lanes, { busy: stats.busy, apply_ms_per_page: stats.applyMsPerPage, turn_wait_share: stats.turnWaitShare });}}+ // #6340: on a live checkout HEAD moves while the run drains its pinned manifest. One bounded extra pass imports the commits+ // 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') {+ 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)}).`);+ const pin = result.toCommit;+ const again = await runDrain({ signal: opts.signal, onProgress: opts.onProgress, probe: engineStallProbe(engine, opts.sourceId), announce: false,+ reconnect: error => engine.reconnect({ error }),+ bulk: { enabled: bulk.enabled, reason: bulk.reason, lanes: bulk.lanes ?? 1, lanesMax: bulk.lanesMax, lanesReason: bulk.lanesReason ?? null, lanesCap: bulk.lanesCap },+ pass: (signal, onProgress) => performManagedSync(engine, { ...opts, signal, onProgress, drainStartedAt, ...(bulk.enabled ? { bulk: { ...bulk, laneRun } } : {}) }) });+ result = mergeExtraPass(result, again, { from: pin, to: head });+ }+ }const lanes = result.drain?.bulk?.enabled ? result.drain.bulk.lanes : undefined;if (lanes && (result.drain!.written > 0 || lanes.configured === 1)) {lanes.limited_by = lanesLimit(lanes, bulk.lanesCap);@@ -591,6 +652,27 @@ export async function drainManagedSync(engine: BrainEngine, opts: SyncOpts, annoreturn result;}+/** The source's current HEAD (the commit a fresh discovery would pin), or null when the checkout cannot be read. */+async function headOfSource(engine: BrainEngine, opts: SyncOpts): Promise<string | null> {+ try {+ const { resolveManagedSyncContext, syncGit } = await import('./sync-discovery.ts');+ const context = await resolveManagedSyncContext(engine, opts);+ return syncGit(context.gitRoot, ['rev-parse', 'HEAD']).trim() || null;+ } catch { return null; }+}++/** #6340: the first drain's report plus the extra pass's: page counts and holds add up, the outcome and `next` are the extra pass's. */+function mergeExtraPass(first: SyncResult, extra: SyncResult, span: { from: string; to: string }): SyncResult {+ const f = first.drain!, e = extra.drain;+ const held = [...(first.held ?? []), ...(extra.held ?? [])];+ return { ...extra, added: first.added + extra.added, modified: first.modified + extra.modified, deleted: first.deleted + extra.deleted, renamed: first.renamed + extra.renamed,+ chunksCreated: first.chunksCreated + extra.chunksCreated, fromCommit: first.fromCommit,+ waived: { imports: (first.waived?.imports ?? 0) + (extra.waived?.imports ?? 0), deletes: (first.waived?.deletes ?? 0) + (extra.waived?.deletes ?? 0) },+ ...(held.length ? { held, held_count: held.length } : {}),+ drain: { ...(e ?? f), outcome: e?.outcome ?? 'synced', passes: f.passes + (e?.passes ?? 1), processed: f.processed + (e?.processed ?? 0), written: f.written + (e?.written ?? 0),+ waived: f.waived + (e?.waived ?? 0), extra_pass: span } };+}+/*** #5984 (E5): what limited a drain's lanes, for the agent. A lock or statement timeout that lowered the lane* count comes first, then lanes that were mostly idle (the sync side did not prepare groups fast enough), then@@ -632,6 +714,7 @@ const STOP_DOCS: Record<DrainStopReason, CatalogueName> = {recovery_required: 'sync_drain_writer_blocked', owner_unavailable: 'sync_drain_writer_blocked', unexpected_file_bytes: 'sync_drain_writer_blocked',unexpected_staging_bytes: 'sync_drain_writer_blocked', blocked_by_failures: 'sync_drain_blocked_by_failures',preparation_abandoned: 'sync_drain_preparation_abandoned', preparation_systemic: 'sync_drain_preparation_systemic', write_capacity: 'sync_drain_write_capacity',+ connection_lost: 'sync_drain_connection_lost',};/** What the agent runs next, or null when the sync is done (DX-A2). */@@ -666,6 +749,14 @@ export function drainNext(result: SyncResult, resumeCommand: string, sourceId: s+ `Inspect them (read-only) and let them finish, or raise ${key}, then rerun: ${resumeCommand}`,...(docs ? { docs } : {}) };}+ // #6340: the connection dropped three times with no page committed between the drops; the cursor stands and the same command resumes it.+ if (d?.stop_reason === 'connection_lost') {+ return { command: resumeCommand, safe_to_loop: true, retry_after_ms: 60_000, ...estimate, code: 'connection_lost',+ why: `The database connection dropped ${d.connection?.drops ?? CONNECTION_STRIKES} times in a row (${d.connection?.last_error ?? 'connection error'}) with no page committed between the drops; `+ + 'the drain reconnected and retried at 5, 15 and 45 s each time. Nothing is recorded against the source: the cursor and its frozen manifest stand. '+ + `Check the database and pooler (gbrain doctor --json), then rerun: ${resumeCommand} (safe in a loop after retry_after_ms; it resumes without re-freezing).`,+ ...(docs ? { docs } : {}) };+ }if (d?.stop_reason === 'database_contention') {const wait = result.writeWait?.status === 'read_failed' ? result.writeWait : null;return { command: resumeCommand, safe_to_loop: false, retry_after_ms: 0, ...estimate,@@ -724,6 +815,7 @@ export function formatDrainSummary(result: SyncResult, resumeCommand: string, so+ (d.remaining ? `, ${d.remaining} remaining` : '') + (d.rate_pages_per_min !== null ? `, ${d.rate_pages_per_min} pages/min` : '')+ (d.remaining && d.eta_seconds !== null ? `, indexing ETA ${formatDuration(d.eta_seconds)}` : '') + '.'];if (d.capacity) lines.push(` Waited ${d.capacity.waited_seconds}s for write capacity: ${d.capacity.outstanding ?? '?'} of ${d.capacity.limit ?? '?'} ${d.capacity.scope ?? 'principal'} outstanding-request slots in use.`);+ if (d.connection) lines.push(` Database connection dropped ${d.connection.drops} times in a row (${d.connection.last_error}); the cursor and its frozen manifest are intact.`);// #6317 (C3): the summary line carries the same step / waiting_on / last_sql triple as the log lines, and the owner process.if (d.stall) lines.push(` Oldest unfinished request ${d.stall.head_request_id ?? d.stall.request_id} (${d.stall.head_state ?? d.stall.state})`+ `${d.stall.blocked_reason ? `, blocked_reason=${d.stall.blocked_reason}` : ''}${d.stall.step ? `, step=${d.stall.step}` : ''}${d.stall.waiting_on ? `, waiting_on=${d.stall.waiting_on}` : ''}`diff --git a/src/core/persistence/sync-fault-class.ts b/src/core/persistence/sync-fault-class.tsnew file mode 100644index 0000000000..b8cf4ec55c--- /dev/null+++ b/src/core/persistence/sync-fault-class.ts@@ -0,0 +1,94 @@+/**+ * #6340: the one table that turns a managed-sync fault code into three+ * decisions an operator agent can act on without reading fifteen error codes:+ *+ * - `class`: `page` (one entry moved under the sync; the rest of the source is+ * fine), `connection` (the database went away for a moment; nothing is+ * recorded against the source), or `systemic` (the writer, the binding, an+ * approval or gbrain itself; a retry alone changes nothing).+ * - `safe_actions`: what an agent may do on its own, in order of preference.+ * `retry` reruns the same sync; `retry_when_clean` re-screens a held file once+ * its edit is committed; `repair` previews and applies a hash-bound file+ * repair; `reconcile` previews the two diverged versions; `upgrade` installs a+ * newer gbrain; `none` means wait for a person.+ * - `needs_human`: whether a person has to choose or act before the fault+ * clears, with `human_reason` naming why.+ *+ * `gbrain sync status --json`, `gbrain sync unblock` and the drain summary all+ * read this table; `docs/guides/sync-unblock-runbook.md` renders it, and+ * `test/sync-runbook-table.test.ts` pins the two together.+ */+export type SyncFaultClass = 'page' | 'connection' | 'systemic';+export type SyncSafeAction = 'retry' | 'retry_when_clean' | 'repair' | 'reconcile' | 'upgrade' | 'none';++export interface SyncFaultRule {+ code: string;+ class: SyncFaultClass;+ safe_actions: SyncSafeAction[];+ needs_human: boolean;+ /** When an agent stops looping and pages a person (the runbook's "escalate when" column). */+ escalate: string;+ /** What a person has to do; present when `needs_human`, or when repeated attempts turn it on. */+ human_reason?: string;+}++/** #6340: a hold earned at or after this many re-holds of one path says the page keeps moving under the sync. */+export const HOLD_ATTEMPTS_NEEDS_HUMAN = 3;++export const SYNC_FAULT_TABLE: ReadonlyArray<SyncFaultRule> = [+ // Page class: one entry, held; the run finished.+ { code: 'worktree_dirty', class: 'page', safe_actions: ['retry_when_clean'], needs_human: false,+ escalate: `held ${HOLD_ATTEMPTS_NEEDS_HUMAN} times: the file keeps changing without being committed`, human_reason: 'Someone (or an agent) keeps editing the file without committing it; find out who and commit or restore it.' },+ { code: 'concurrent_write', class: 'page', safe_actions: ['reconcile'], needs_human: true, escalate: 'always: the file and the database page diverge',+ human_reason: 'The Git file and the database page both changed; a person chooses which version wins (gbrain sources reconcile <source> <slug> --preview shows both and writes nothing).' },+ { code: 'preparation_stalled', class: 'page', safe_actions: ['retry', 'upgrade'], needs_human: false,+ escalate: `held ${HOLD_ATTEMPTS_NEEDS_HUMAN} times, or writer status names a step that never finishes`, human_reason: 'The write owner cannot finish preparing this file; writer status names the step, fix or report it.' },+ { code: 'invalid_fence', class: 'page', safe_actions: ['repair'], needs_human: false, escalate: 'the fence repair preview offers no plan (a manual reason)', human_reason: 'Edit the facts or takes table the hold names and commit.' },+ { code: 'invalid_frontmatter', class: 'page', safe_actions: ['repair'], needs_human: false, escalate: 'the repair preview needs an interpretation (--include-ambiguous)', human_reason: 'Approve the proposed frontmatter fix or edit the file.' },+ { code: 'frontmatter_slug_conflict', class: 'page', safe_actions: ['repair'], needs_human: false, escalate: 'the repair preview needs an interpretation', human_reason: 'Decide which page keeps the slug.' },+ { code: 'rename_held', class: 'page', safe_actions: ['repair'], needs_human: false, escalate: 'the repair preview needs an interpretation', human_reason: 'Approve re-binding the rename to the current page.' },+ { code: 'file_too_large', class: 'page', safe_actions: ['none'], needs_human: true, escalate: 'always', human_reason: 'Split the file or exclude it with sync.exclude.' },+ { code: 'content_rejected', class: 'page', safe_actions: ['none'], needs_human: true, escalate: 'always', human_reason: 'The content-sanity gate rejected the file; remove the junk or change junk_disposition.' },+ { code: 'parser_regression', class: 'page', safe_actions: ['upgrade'], needs_human: true, escalate: 'always: a gbrain bug', human_reason: 'Report the file and gbrain version, then upgrade or pin the last good release.' },+ { code: 'managed_image_sync_unsupported', class: 'page', safe_actions: ['none'], needs_human: false, escalate: 'never: images stay held by design', human_reason: 'Leave images held, or exclude them with sync.exclude.' },+ // Older releases recorded these as run failures; a rerun on this release holds the page instead.+ { code: 'revision_conflict', class: 'page', safe_actions: ['retry'], needs_human: false, escalate: 'the same path fails again after a rerun' },+ { code: 'page_identity_changed', class: 'page', safe_actions: ['retry'], needs_human: false, escalate: 'the same path fails again after a rerun' },+ { code: 'pinned_git_worktree_conflict', class: 'page', safe_actions: ['retry'], needs_human: false, escalate: 'the same path fails again after a rerun' },+ { code: 'source_changed', class: 'page', safe_actions: ['retry'], needs_human: false, escalate: 'the same path fails again after a rerun' },+ { code: 'sync_incomplete', class: 'page', safe_actions: ['retry'], needs_human: false, escalate: 'never: an unfinished cursor resumes with the same command' },+ // Connection class: transport only; the cursor and manifest stand.+ { code: 'connection_lost', class: 'connection', safe_actions: ['retry'], needs_human: false, escalate: 'three reruns in a row end connection_lost (the database is unreachable from this host)' },+ { code: 'database_contention', class: 'connection', safe_actions: ['retry'], needs_human: false, escalate: 'three reruns in a row stop on it' },+ { code: 'write_capacity', class: 'connection', safe_actions: ['retry'], needs_human: false, escalate: 'writer status shows the cap held by requests that never settle' },+ { code: 'storage_error', class: 'connection', safe_actions: ['retry'], needs_human: false, escalate: 'the same error after a rerun (then it is not a dropped connection)' },+ // Systemic class: a retry alone changes nothing.+ { code: 'preparation_systemic', class: 'systemic', safe_actions: ['upgrade', 'retry'], needs_human: true, escalate: 'always', human_reason: 'Several writes could not finish preparing: the write owner is the likely cause. Writer status names it; fix, restart or upgrade it.' },+ { code: 'drain_stalled', class: 'systemic', safe_actions: ['none'], needs_human: true, escalate: 'always', human_reason: 'The write at the head of the source is wedged in its owner; restart the owner process writer status names.' },+ { code: 'recovery_required', class: 'systemic', safe_actions: ['none'], needs_human: true, escalate: 'always', human_reason: 'A write needs recovery on the brain host (gbrain sources writer status --json names it).' },+ { code: 'owner_unavailable', class: 'systemic', safe_actions: ['none'], needs_human: true, escalate: 'always', human_reason: 'The write owner is gone; start or restart it on the brain host.' },+ { code: 'writer_coordinator_required', class: 'systemic', safe_actions: ['none'], needs_human: true, escalate: 'always', human_reason: 'Managed persistence is not active for this source; activate it or sync unmanaged.' },+ { code: 'permission_denied', class: 'systemic', safe_actions: ['none'], needs_human: true, escalate: 'always', human_reason: 'This principal may not sync the source; the owner grants it.' },+ { code: 'plan_stale', class: 'systemic', safe_actions: ['none'], needs_human: true, escalate: 'always', human_reason: 'The approved company-brain manifest changed; inspect and approve the repository again.' },+ { code: 'invalid_params', class: 'systemic', safe_actions: ['none'], needs_human: true, escalate: 'always', human_reason: 'The resume options conflict with the stored cursor; use the resume command the error prints.' },+];++const BY_CODE = new Map(SYNC_FAULT_TABLE.map(rule => [rule.code, rule]));++export interface SyncFaultVerdict { class: SyncFaultClass; safe_actions: SyncSafeAction[]; needs_human: boolean; human_reason?: string }++/**+ * The verdict for one fault. `attempts` is a hold's re-hold count: a page held `HOLD_ATTEMPTS_NEEDS_HUMAN` times with the+ * same code keeps moving under the sync, so its own safe action is exhausted and a person is named. `detail` is a receipt's+ * `reason` (for example `pinned_git_worktree_conflict` under `source_changed`) or a drain stop's `cause`; it refines the code+ * when the table knows it. An unknown code is systemic and human: an agent must not guess at it.+ */+export function classifySyncFault(input: { code: string; detail?: string | null; attempts?: number | null; message?: string | null }): SyncFaultVerdict {+ const rule = (input.detail ? BY_CODE.get(input.detail) : undefined) ?? BY_CODE.get(input.code)+ ?? (/ECONN|ETIMEDOUT|EPIPE|connection.*closed|CONNECTION_ENDED/i.test(input.message ?? '') ? BY_CODE.get('connection_lost') : undefined);+ if (!rule) return { class: 'systemic', safe_actions: ['none'], needs_human: true, human_reason: `Unknown code ${input.code}; run gbrain doctor --json and read gbrain errors ${input.code}.` };+ const exhausted = !rule.needs_human && (input.attempts ?? 0) >= HOLD_ATTEMPTS_NEEDS_HUMAN && rule.safe_actions[0] !== 'none' && rule.class === 'page';+ if (!exhausted) return { class: rule.class, safe_actions: rule.safe_actions, needs_human: rule.needs_human, ...(rule.needs_human && rule.human_reason ? { human_reason: rule.human_reason } : {}) };+ return { class: rule.class, safe_actions: ['none'], needs_human: true,+ human_reason: `${rule.human_reason ?? 'The page keeps moving under the sync.'} (held ${input.attempts} times with code ${rule.code})` };+}diff --git a/src/core/persistence/sync-holds.ts b/src/core/persistence/sync-holds.tsindex 7d926f3a65..979e887ae5 100644--- a/src/core/persistence/sync-holds.ts+++ b/src/core/persistence/sync-holds.ts@@ -54,7 +54,7 @@ export const GIT_HOLD_ESCALATE_MIN_SCREENED = 40;type Exec = Pick<BrainEngine, 'executeRaw'>;-export type GitHoldCode = ContentRefusal['code'] | 'rename_held' | 'parser_regression' | 'managed_image_sync_unsupported' | 'concurrent_write' | 'preparation_stalled';+export type GitHoldCode = ContentRefusal['code'] | 'rename_held' | 'parser_regression' | 'managed_image_sync_unsupported' | 'concurrent_write' | 'preparation_stalled' | 'worktree_dirty';/** #6278: what the owner recorded about a preparation it gave up on (step names and vocabulary only, never content). */export interface PreparationStallMeta {request_id: string;@@ -89,6 +89,12 @@ export interface GitHoldMeta {competing_request_id?: string;competing_operation?: string;page_revision?: string;+ /** #6340 `concurrent_write`: the revision the entry was frozen against (the page's live revision is `page_revision`). */+ expected_revision?: string;+ /** #6340 `worktree_dirty`: sha256 of the uncommitted working-tree bytes the hold protected (`blob_oid` is the pinned blob). */+ working_hash?: string;+ /** #6340: how many times this path was held again with the same code since the hold was first written; at `HOLD_ATTEMPTS_NEEDS_HUMAN` the page keeps moving. */+ attempts?: number;/** #6188: the last fence repair attempt (repair kind or maintenance phase) that left this hold in place; location and reason only. */fence_repair?: FenceHoldRepairState;/** #6278 `preparation_stalled`: the failed receipt's step, wait cause and attempt count. */@@ -171,9 +177,9 @@ async function lockSummary(tx: Exec, sourceId: string, incarnation: string): Pro/*** `count` is every hold; `stale` the holds of files whose page exists (the rest are missing pages);* `images` the #5493 unsupported-image holds, which never escalate; `fences` the #6188 `invalid_fence` holds;- * `concurrent` the #6194 `concurrent_write` holds; `stalled` the #6278 `preparation_stalled` holds.+ * `concurrent` the #6194 `concurrent_write` holds; `stalled` the #6278 `preparation_stalled` holds; `dirty` the #6340 `worktree_dirty` holds.*/-const SUMMARY_COUNTERS = ['stale', 'images', 'fences', 'concurrent', 'stalled'] as const;+const SUMMARY_COUNTERS = ['stale', 'images', 'fences', 'concurrent', 'stalled', 'dirty'] as const;type SummaryWeights = Record<typeof SUMMARY_COUNTERS[number], number>;async function adjustSummary(tx: Exec, sourceId: string, incarnation: string, delta: number, weights: SummaryWeights): Promise<void> {const pairs = SUMMARY_COUNTERS.map((name, i) => `'${name}',GREATEST(0,COALESCE((completed_keys->0->>'${name}')::int,0)+$${i + 4}::int)`).join(',');@@ -187,8 +193,9 @@ const imageWeight = (record: Pick<GitHoldRecord, 'code'> | null) => record?.codeconst fenceWeight = (record: Pick<GitHoldRecord, 'code'> | null) => record?.code === 'invalid_fence' ? 1 : 0;const concurrentWeight = (record: Pick<GitHoldRecord, 'code'> | null) => record?.code === 'concurrent_write' ? 1 : 0;const stalledWeight = (record: Pick<GitHoldRecord, 'code'> | null) => record?.code === 'preparation_stalled' ? 1 : 0;+const dirtyWeight = (record: Pick<GitHoldRecord, 'code'> | null) => record?.code === 'worktree_dirty' ? 1 : 0;const weightsOf = (record: Pick<GitHoldRecord, 'code' | 'page_id'>, sign = 1): SummaryWeights => ({ stale: sign * staleWeight(record), images: sign * imageWeight(record),- fences: sign * fenceWeight(record), concurrent: sign * concurrentWeight(record), stalled: sign * stalledWeight(record) });+ fences: sign * fenceWeight(record), concurrent: sign * concurrentWeight(record), stalled: sign * stalledWeight(record), dirty: sign * dirtyWeight(record) });async function readRow(tx: Exec, sourceId: string, incarnation: string, path: string): Promise<GitHoldRecord | null> {const [row] = await tx.executeRaw<{ record: GitHoldRecord }>('SELECT completed_keys->0 AS record FROM op_checkpoints WHERE op=$1 AND fingerprint=$2',@@ -206,7 +213,9 @@ export async function writeGitHold(tx: Exec, input: Omit<GitHoldRecord, 'versionconst existing = await readRow(tx, input.source_id, input.incarnation, input.path);if (existing && existing.observed_at > input.observed_at) return 'skipped';const now = new Date().toISOString();- const record: GitHoldRecord = { version: 1, ...input,+ // #6340: a path held again with the same code counts an attempt, so a page that keeps moving can be named.+ const attempts = existing && existing.code === input.code ? (existing.meta.attempts ?? 1) + 1 : 1;+ const record: GitHoldRecord = { version: 1, ...input, meta: { ...input.meta, attempts },held_at: existing && existing.upstream_version === input.upstream_version && existing.code === input.code ? existing.held_at : now, updated_at: now };await tx.executeRaw(`INSERT INTO op_checkpoints(op,fingerprint,completed_keys) VALUES($1,$2,$3::text::jsonb)ON CONFLICT(op,fingerprint) DO UPDATE SET completed_keys=EXCLUDED.completed_keys,updated_at=now()`,@@ -345,7 +354,7 @@ export function holdRescreenDue(record: Pick<GitHoldRecord, 'code' | 'meta'>, re* (never a file repair), every other hold to the frontmatter repair preview;* a source with several kinds names each.*/-export interface HoldRepairRoute { fences: number; others: number; concurrent?: number; stalled?: number }+export interface HoldRepairRoute { fences: number; others: number; concurrent?: number; stalled?: number; dirty?: number }/** #6278: the three commands that clear a source's `preparation_stalled` holds, in order (no file repair applies). */export function stalledHoldSteps(sourceId: string, syncArgv?: string[]): { status: string[]; retry: string[]; sync: string[] } {@@ -372,14 +381,20 @@ export function holdRepairSteps(sourceId: string, route: HoldRepairRoute, auto?:const stalled = stalledHoldSteps(sourceId);const stalledText = `the ${route.stalled ?? 0} preparation-stalled hold(s) are not file problems and need no repair: inspect the writer with ${stalled.status.join(' ')} (read-only), `+ `fix what it names or upgrade gbrain, then run ${stalled.retry.join(' ')} and the same sync again (${stalled.sync.join(' ')} with the run's options)`;- if (route.stalled && !route.others && !route.fences && !route.concurrent) {+ const unblock = ['gbrain', 'sync', 'unblock', '--source', sourceId, '--apply'];+ const dirtyText = `the ${route.dirty ?? 0} worktree-dirty hold(s) are uncommitted edits in the checkout that sync would not overwrite: commit them (gbrain sources status ${sourceId} names each file), `+ + `then run ${unblock.join(' ')}, which re-screens every held file that is now committed, and the same sync`;+ if (route.stalled && !route.others && !route.fences && !route.concurrent && !route.dirty) {return { argv: stalled.status, commands: [stalled.status.join(' '), stalled.retry.join(' '), stalled.sync.join(' ')], text: stalledText };}- if (route.concurrent || route.stalled) {- const parts = [...(route.others ? [frontmatterText] : []), ...(route.fences ? [fenceText] : []), ...(route.concurrent ? [concurrentText] : []), ...(route.stalled ? [stalledText] : [])];+ if (route.dirty && !route.others && !route.fences && !route.concurrent && !route.stalled) {+ return { argv: unblock, commands: [`gbrain sources status ${sourceId} --json`, unblock.join(' '), `gbrain sync --source ${sourceId} --no-pull`], text: dirtyText };+ }+ if (route.concurrent || route.stalled || route.dirty) {+ const parts = [...(route.others ? [frontmatterText] : []), ...(route.fences ? [fenceText] : []), ...(route.concurrent ? [concurrentText] : []), ...(route.stalled ? [stalledText] : []), ...(route.dirty ? [dirtyText] : [])];const commands = [...(route.others ? [frontmatter.join(' ')] : []), ...(route.fences ? [fences.join(' ')] : []),- ...(route.stalled ? [stalled.status.join(' ')] : []), `gbrain sources status ${sourceId} --json`, `gbrain sources retry-held ${sourceId}`, `gbrain sync --source ${sourceId} --no-pull`];- return { argv: route.others ? frontmatter : route.fences ? fences : route.concurrent ? ['gbrain', 'sources', 'status', sourceId, '--json'] : stalled.status, commands, text: parts.join('; ') };+ ...(route.stalled ? [stalled.status.join(' ')] : []), `gbrain sources status ${sourceId} --json`, ...(route.dirty ? [unblock.join(' ')] : []), `gbrain sources retry-held ${sourceId}`, `gbrain sync --source ${sourceId} --no-pull`];+ return { argv: route.others ? frontmatter : route.fences ? fences : route.concurrent ? ['gbrain', 'sources', 'status', sourceId, '--json'] : route.stalled ? stalled.status : unblock, commands, text: parts.join('; ') };}if (route.fences && !route.others) return { argv: fences, commands: [fences.join(' ')], text: fenceText };if (route.fences) return { argv: frontmatter, commands: [frontmatter.join(' '), fences.join(' ')], text: `${frontmatterText}; ${fenceText}` };@@ -401,10 +416,22 @@ export function gitHoldFix(record: Pick<GitHoldRecord, 'source_id' | 'path' | 'cswitch (record.code) {case 'invalid_fence':return fenceHoldFix(record, auto);+ case 'worktree_dirty': {+ const verify = { argv: ['gbrain', 'sources', 'status', source, '--json'] };+ return { argv: ['git', '-C', '<source root>', 'status', '--porcelain', '--', record.path], consent: [], actor: 'agent', requires_exclusive: false, docs: 'docs/guides/write-refusals.md#worktree_dirty',+ why: `${record.path} has uncommitted working-tree bytes that match neither the pinned commit nor the current page, so sync held it instead of overwriting the local edit; the rest of the source kept syncing. `+ + `Whoever edits that file (an agent writing to the checkout) should commit it; once git status is clean for it, run gbrain sources retry-held ${source} and gbrain sync --source ${source} --no-pull. `+ + `A later commit that changes the file re-screens the hold on its own. Do not discard or normalize the local bytes.`,+ then: { argv: ['gbrain', 'sources', 'retry-held', source], consent: [], actor: 'agent', requires_exclusive: false, verify,+ why: `Schedules ${record.path} for a re-screen on the next sync, once its edit is committed (gbrain sync unblock --source ${source} --apply does this check and scheduling for every such hold).` },+ verify };+ }case 'concurrent_write': {const slug = record.slug ?? '<slug>';+ const by = record.meta.competing_request_id ? `${record.meta.competing_operation ?? 'a database'} request ${record.meta.competing_request_id} wrote page ${slug} straight to the database`+ : `page ${slug} changed in the database${record.meta.page_revision ? ` (revision ${record.meta.page_revision})` : ''} after the sync enumerated it`;return { argv: ['gbrain', 'sources', 'reconcile', source, slug, '--preview'], consent: [], actor: 'agent', requires_exclusive: false,- why: `${record.path} changed in Git while ${record.meta.competing_operation ?? 'a database'} request ${record.meta.competing_request_id ?? '(unknown)'} wrote page ${slug} straight to the database, so the two versions diverge and neither was overwritten. `+ why: `${record.path} changed in Git while ${by}, so the two versions diverge and neither was overwritten. `+ `The reconcile preview shows both and writes nothing; resolve it with the user, apply it, then re-screen the file with gbrain sources retry-held ${source} and gbrain sync --source ${source} --no-pull. The rest of the source is not blocked.`,then: { argv: ['gbrain', 'sources', 'retry-held', source], consent: [], actor: 'agent', requires_exclusive: false,why: `Schedules ${record.path} for a re-screen on the next sync, after the page is reconciled.`, verify: { argv: ['gbrain', 'sources', 'status', source, '--json'] } },@@ -458,6 +485,7 @@ export function gitHoldDocs(code: GitHoldCode, reason?: GitHoldReason): string {// #6188: fence reasons carry their own anchors (`#fence-<reason>`).if (code === 'invalid_fence') return reason && reason in FENCE_REASONS ? FENCE_REASONS[reason as FenceReason].docs : 'docs/guides/write-refusals.md#invalid_fence';if (code === 'preparation_stalled') return 'docs/guides/write-refusals.md#preparation_stalled';+ if (code === 'worktree_dirty') return 'docs/guides/write-refusals.md#worktree_dirty';return `docs/guides/write-refusals.md#${reason ? `${code}-${reason}` : code}`;}@@ -667,8 +695,9 @@ export function fencesNormalizedReport(sourceId: string, tally: FencesTally | unexport async function buildHoldReport(engine: Exec, input: { sourceId: string; incarnation: string; runId: string; remote: boolean;policy: SyncHoldPolicy; screened: number; pendingScreen?: boolean }): Promise<Pick<import('../../commands/sync.ts').SyncResult,'held' | 'held_count' | 'holds_outstanding' | 'holds_escalated' | 'holds_truncated' | 'holds_pending_screen' | 'holds_fix'>> {- const [summary] = await engine.executeRaw<{ count: number | string; images: number | string; fences: number | string; stalled: number | string }>(`SELECT COALESCE((completed_keys->0->>'count')::int,0) AS count,- COALESCE((completed_keys->0->>'images')::int,0) AS images, COALESCE((completed_keys->0->>'fences')::int,0) AS fences, COALESCE((completed_keys->0->>'stalled')::int,0) AS stalled+ const [summary] = await engine.executeRaw<{ count: number | string; images: number | string; fences: number | string; stalled: number | string; concurrent: number | string; dirty: number | string }>(`SELECT COALESCE((completed_keys->0->>'count')::int,0) AS count,+ COALESCE((completed_keys->0->>'images')::int,0) AS images, COALESCE((completed_keys->0->>'fences')::int,0) AS fences, COALESCE((completed_keys->0->>'stalled')::int,0) AS stalled,+ COALESCE((completed_keys->0->>'concurrent')::int,0) AS concurrent, COALESCE((completed_keys->0->>'dirty')::int,0) AS dirtyFROM op_checkpoints WHERE op=$1 AND fingerprint=$2`,[GIT_HOLD_SUMMARY_OP, summaryFingerprint(input.sourceId, input.incarnation)]);const outstanding = Number(summary?.count ?? 0);@@ -678,8 +707,11 @@ export async function buildHoldReport(engine: Exec, input: { sourceId: string; i{ held: runHolds.filter(hold => !imageWeight(hold)).length, screened: input.screened });const fences = Math.max(Number(summary?.fences ?? 0), runHolds.filter(hold => fenceWeight(hold)).length);const stalled = Math.max(Number(summary?.stalled ?? 0), runHolds.filter(hold => stalledWeight(hold)).length);+ const concurrent = Math.max(Number(summary?.concurrent ?? 0), runHolds.filter(hold => concurrentWeight(hold)).length);+ const dirty = Math.max(Number(summary?.dirty ?? 0), runHolds.filter(hold => dirtyWeight(hold)).length);const auto = fences ? await readFenceAutoRepair(engine) : undefined;- const steps = holdRepairSteps(input.sourceId, { fences, others: Math.max(0, outstanding - fences - stalled), ...(stalled ? { stalled } : {}) }, auto);+ const steps = holdRepairSteps(input.sourceId, { fences, others: Math.max(0, outstanding - fences - stalled - concurrent - dirty), ...(stalled ? { stalled } : {}),+ ...(concurrent ? { concurrent } : {}), ...(dirty ? { dirty } : {}) }, auto);// #6278: the escalation text is routed by code: stalled holds point at the writer, not at a generator.const runStalled = runHolds.filter(hold => stalledWeight(hold)).length;const escalation = runStalled * 2 > runHolds.length@@ -691,7 +723,7 @@ export async function buildHoldReport(engine: Exec, input: { sourceId: string; iuser_message: `Some files in source ${input.sourceId} could not be imported. Please run 'gbrain sources status ${input.sourceId}' on the brain host, then: ${steps.text}.` } };const fix: Action = { argv: steps.argv, consent: [], actor: 'agent', requires_exclusive: false, verify,why: `${runHolds.length} file(s) held this run, ${outstanding} held in source ${input.sourceId}; they do not block sync. Inspect them with 'gbrain sources status ${input.sourceId}'; `- + (fences || stalled ? `then ${steps.text}.` : 'the repair preview proposes each fix and writes nothing.')+ + (fences || stalled || concurrent || dirty ? `then ${steps.text}.` : 'the repair preview proposes each fix and writes nothing.')+ (escalated ? escalation : '') };return { held: runHolds.slice(0, input.policy.cap).map(hold => gitHoldItem(hold, auto)), held_count: runHolds.length, holds_outstanding: outstanding,...(escalated ? { holds_escalated: true } : {}), ...(runHolds.length > input.policy.cap ? { holds_truncated: true } : {}),diff --git a/src/core/persistence/sync-page-fault.ts b/src/core/persistence/sync-page-fault.tsnew file mode 100644index 0000000000..96b26fe7b8--- /dev/null+++ b/src/core/persistence/sync-page-fault.ts@@ -0,0 +1,144 @@+/**+ * #6340: a page that moved under a managed catch-up holds the page, not the run.+ *+ * On a live checkout (agents commit to the brain repo every few minutes while a+ * multi-hour catch-up drains a frozen manifest) four codes used to end the whole+ * run, each recoverable with a plain retry: `revision_conflict` and+ * `page_identity_changed` at freeze time (the database page changed after the+ * manifest was enumerated), and `source_changed [pinned_git_worktree_conflict]`+ * at publication (the working tree holds other bytes than the pinned commit).+ * Each relaunch then re-froze the manifest. This module is the one place that+ * decides what such an entry becomes instead:+ *+ * - bytes committed at HEAD past the pinned target are imported as HEAD has them+ * (`headCommittedBytes`): a commit is not an uncoordinated local edit, and the+ * later pin..HEAD diff re-imports the same bytes as a no-op (idea and first+ * test from PR #6323 by @garrytan-agents);+ * - a database page that changed after enumeration but still holds what the+ * entry would import is re-bound to its current revision (the caller's waiver+ * screen then passes it as unchanged);+ * - anything else is a hold: `concurrent_write` when the database side moved+ * (#6194's code and reconcile route, with the competing request when the+ * proof finds one, else the observed revision alone), `worktree_dirty` when+ * the file side moved (uncommitted bytes that match neither the pin nor the+ * page). The cursor advances past the hold and the receipt lists it.+ *+ * Holds carry `meta.attempts`, incremented each time the same path is held+ * again (`writeGitHold` on update), so an operator contract can say+ * `needs_human` for a page that keeps moving. Only a systemic failure (the+ * preparation breaker, authority or binding loss) still ends a run.+ */+import { createHash } from 'node:crypto';+import type { BrainEngine } from '../engine.ts';+import { RECOVERY_VERSION } from '../markdown.ts';+import { sha256 } from './digest.ts';+import type { WriteRequest } from './model.ts';+import { readSyncFile, syncGitPath, type SyncDiscovery, type SyncEntry, type SyncRename } from './sync-discovery.ts';+import { readTreeBlobs } from './sync-blobs.ts';+import type { SyncIntent } from './sync-prepare.ts';+import type { HeldEntry } from './sync-screen.ts';+import type { GitHoldMeta } from './sync-holds.ts';++export { HOLD_ATTEMPTS_NEEDS_HUMAN } from './sync-fault-class.ts';++type HoldEntry = Pick<SyncEntry, 'path' | 'sourcePath' | 'working' | 'renameFrom' | 'renameHeld' | 'action'>;++/** Git's blob id of `bytes` in the object format HEAD uses (sha1, or sha256 when HEAD's ids are 64 hex digits). */+function blobOid(bytes: Buffer, format: 'sha1' | 'sha256'): string {+ return createHash(format).update(`blob ${bytes.length}\0`).update(bytes).digest('hex');+}++/**+ * The working-tree bytes of `path` when they are exactly what HEAD commits for it (their blob id equals+ * `HEAD:<path>`), with that blob id; null when the file is absent, differs from HEAD, or Git cannot answer.+ * A read failure is the caller's ordinary refusal path, never a substitution.+ */+export function headCommittedBytes(context: Pick<SyncDiscovery, 'root' | 'gitRoot'>, path: string): { content: string; oid: string; rawHash: string } | null {+ let bytes: Buffer | null;+ try { bytes = readSyncFile(context.root, path); } catch { return null; }+ if (!bytes) return null;+ const gitPath = syncGitPath(context, path);+ let head: { oid: string } | undefined;+ try { head = readTreeBlobs(context.gitRoot, 'HEAD', [gitPath]).get(gitPath); } catch { return null; }+ if (!head) return null;+ const oid = blobOid(bytes, head.oid.length === 64 ? 'sha256' : 'sha1');+ return oid === head.oid ? { content: bytes.toString('utf8'), oid, rawHash: sha256(bytes) } : null;+}++export interface PageChangeProof { request_id: string; operation: string; revision: string }++/**+ * #6194's proof, usable at freeze time as well as from a receipt: the page's live revision differs from the one the entry+ * was frozen against, and `pages.revision_write_request_id` names a committed non-sync request of the same source+ * incarnation and page id. Null when the race is not proven (the page may still have changed).+ */+export async function pageChangeProof(engine: Pick<BrainEngine, 'executeRaw'>, input: { sourceId: string; incarnation: string; pageId: number | null; expectedRevision: string | null }): Promise<PageChangeProof | null> {+ if (input.pageId === null) return null;+ const [page] = await engine.executeRaw<{ revision: string | null; writer: string | null }>(+ 'SELECT knowledge_revision::text AS revision, revision_write_request_id::text AS writer FROM pages WHERE id=$1 AND source_id=$2', [input.pageId, input.sourceId]);+ if (!page?.revision || !page.writer || page.revision === String(input.expectedRevision ?? '')) return null;+ const [writer] = await engine.executeRaw<{ request_id: string; operation: string; kind: string | null; state: string; incarnation: string; page_id: number | null }>(+ `SELECT request_id::text, operation, intent->>'kind' AS kind, state, source_incarnation::text AS incarnation, page_id FROM persistence_requests WHERE id=$1::uuid`, [page.writer]);+ if (!writer || writer.state !== 'committed' || String(writer.kind ?? '').startsWith('managed_sync_')+ || writer.incarnation !== input.incarnation || Number(writer.page_id) !== input.pageId) return null;+ return { request_id: writer.request_id, operation: writer.operation, revision: page.revision };+}++/** The page's live revision (null when it no longer exists), for a hold that records what it observed. */+export async function liveRevision(engine: Pick<BrainEngine, 'executeRaw'>, sourceId: string, page: { pageId: number | null; slug: string }): Promise<string | null> {+ const [row] = page.pageId === null+ ? await engine.executeRaw<{ revision: string | null }>('SELECT knowledge_revision::text AS revision FROM pages WHERE source_id=$1 AND slug=$2 AND deleted_at IS NULL', [sourceId, page.slug])+ : await engine.executeRaw<{ revision: string | null }>('SELECT knowledge_revision::text AS revision FROM pages WHERE id=$1 AND source_id=$2 AND deleted_at IS NULL', [page.pageId, sourceId]);+ return row?.revision ?? null;+}++function base(entry: HoldEntry, slug: string, pageId: number | null, code: 'concurrent_write' | 'worktree_dirty',+ message: string, content: string | null, blobOid: string | null | undefined, meta: Partial<GitHoldMeta>): HeldEntry {+ const rename: SyncRename | undefined = entry.renameFrom ?? entry.renameHeld;+ return { path: entry.path, source_path: entry.sourcePath, slug, page_id: pageId, code, message, upstream_version: content === null ? null : sha256(content),+ meta: { recovery_version: RECOVERY_VERSION, ...(blobOid ? { blob_oid: blobOid } : {}), ...(entry.working ? { working: true } : {}),+ ...(rename ? { rename_from: rename } : {}), ...(entry.action === 'delete' ? { deleted: true as const } : {}), ...meta } };+}++/**+ * The `concurrent_write` hold for a page that changed in the database after this entry was enumerated (or after its+ * import was admitted). `why` names the change as the caller saw it; identifiers and revisions only, never content.+ */+export function pageChangedHold(entry: HoldEntry, slug: string, pageId: number | null, intent: Pick<SyncIntent, 'content' | 'blobOid' | 'expected_revision'>,+ observed: { proof: PageChangeProof | null; revision: string | null; why: string }): HeldEntry {+ const what = entry.action === 'delete' ? 'deletion' : 'import';+ const by = observed.proof ? `${observed.proof.operation} request ${observed.proof.request_id} wrote page ${slug} straight to the database` : observed.why;+ return base(entry, slug, pageId, 'concurrent_write',+ `${entry.path}: ${by} after this sync enumerated it, so its ${what} is held and the rest of the source synced; neither version was overwritten.`,+ typeof intent.content === 'string' ? intent.content : null, typeof intent.blobOid === 'string' ? intent.blobOid : null,+ { ...(observed.proof ? { competing_request_id: observed.proof.request_id, competing_operation: observed.proof.operation } : {}),+ ...(observed.revision ?? observed.proof?.revision ? { page_revision: observed.revision ?? observed.proof!.revision } : {}),+ ...(intent.expected_revision ? { expected_revision: String(intent.expected_revision) } : {}) });+}++/**+ * The `worktree_dirty` hold for a file whose working-tree bytes match neither the pinned commit nor the current page+ * and are not committed at HEAD: an uncoordinated local edit sync must not overwrite. `blobOid` is the pinned blob,+ * so discovery re-screens the hold when a later commit changes the file, and `sources retry-held` re-screens it once+ * the edit is committed.+ */+export function worktreeDirtyHold(entry: HoldEntry, slug: string, pageId: number | null, intent: Pick<SyncIntent, 'content' | 'blobOid' | 'rawHash'>): HeldEntry {+ return base(entry, slug, pageId, 'worktree_dirty',+ `${entry.path} has uncommitted working-tree bytes that match neither the pinned commit nor the current page, so its import is held and the rest of the source synced; the local edit was not overwritten. Commit the file (or restore it) and the next sync imports it.`,+ typeof intent.content === 'string' ? intent.content : null, typeof intent.blobOid === 'string' ? intent.blobOid : null,+ { ...(intent.rawHash ? { working_hash: intent.rawHash } : {}) });+}++/** The receipt of a `managed_sync_import` that publication refused as `pinned_git_worktree_conflict` (sync-prepare.ts `newerWorkingTree`). */+export function pinnedWorktreeConflict(done: Pick<WriteRequest, 'state' | 'error_code' | 'error_message'>): boolean {+ return done.state !== 'committed' && done.error_code === 'source_changed'+ && ['Newer working-tree bytes and the current page disagree with this pinned Git import.', 'Newer code file bytes disagree with the pinned import.'].includes(done.error_message ?? '');+}++/** A `revision_conflict` receipt whose page really moved (its live revision differs from the frozen one); run-level conflicts stay blocking. */+export async function pageMovedSinceAdmission(engine: Pick<BrainEngine, 'executeRaw'>, sourceId: string, pending: { slug: string; pageId: number | null; intent: Pick<SyncIntent, 'expected_revision'> },+ done: Pick<WriteRequest, 'state' | 'error_code'>): Promise<{ revision: string | null } | null> {+ if (done.state === 'committed' || done.error_code !== 'revision_conflict') return null;+ const revision = await liveRevision(engine, sourceId, pending);+ return revision === (pending.intent.expected_revision === null || pending.intent.expected_revision === undefined ? null : String(pending.intent.expected_revision)) ? null : { revision };+}diff --git a/src/core/persistence/sync-run.ts b/src/core/persistence/sync-run.tsindex 68f7835a9f..f4e7fcdf59 100644--- a/src/core/persistence/sync-run.ts+++ b/src/core/persistence/sync-run.ts@@ -39,10 +39,12 @@ import { cancelRows, cancelWindow } from './sync-window.ts';import { managedSyncResumeArgs } from '../sync-reconcile.ts';import { laneApplyMsPerMember, lanePolicy, openLanes } from './sync-lanes.ts';import { isContentRefusal } from '../import-screen.ts';+import { isRetryableConnError, isStatementTimeoutError } from '../retry-matcher.ts';import { SYNC_READ_BOUND, type TreeBlob } from './sync-blobs.ts';import { dryRunScreen, isSyncReadBound, loadSyncScreenRun, managedImageHold, pinnedBlob, preparationStalledHold, prepareTimeFenceHold, screenFrozenImport, type HeldEntry, type SyncScreenRun } from './sync-screen.ts';import { fenceReceiptLocation } from '../fence-repair/refusal.ts';import { concurrentWriteHold, concurrentWriteProof } from './sync-concurrent-write.ts';+import { headCommittedBytes, pageChangeProof, pageChangedHold, pageMovedSinceAdmission, pinnedWorktreeConflict, worktreeDirtyHold } from './sync-page-fault.ts';import { faultPoint } from './fault-points.ts';import { pipelined } from '../page-state/transactions.ts';import { withCoordinatedWrite } from './context.ts';@@ -371,27 +373,53 @@ async function freezeEntry(engine: BrainEngine, cursor: Cursor, key: string, asscontent = (await readCommittedBlob(cursor.companyPlan.revision!, blob, cursor.companyPlan.limits)).toString('utf8');assertActive();} else content = entry.action === 'import' && !oversize ? readSyncContent(cursor, entry) : null;+ // #6340: working-tree bytes that differ from the pinned blob but are committed at HEAD (a commit past the pin on a+ // live checkout) are imported as HEAD has them; the pin..HEAD diff later re-imports the same bytes as a no-op.+ // Uncommitted bytes keep the pinned content and reach the publication screen (idea from PR #6323).+ if (entry.action === 'import' && !cursor.companyPlan && !entry.working && content !== null && rawHash !== null && rawHash !== sha256(content)) {+ const head = headCommittedBytes(cursor, entry.path);+ if (head && head.rawHash === rawHash) { content = head.content; blob = { oid: head.oid, size: bytes!.length }; }+ }lineEndingOnly = bytes !== null && content !== null && bytes.equals(Buffer.from(bytes.toString('utf8'))) &&bytes.toString('utf8').replace(/\r\n/g, '\n') === content.replace(/\r\n/g, '\n');slug = entry.slug!; pageId = occupant?.page.id ?? entry.pageId ?? null; revision = occupant ? occupant.revision : entry.revision ?? null;frozenSnapshot = snapshot;+ // #6340: a page that moved under the manifest holds the page, not the run (sync-page-fault.ts); `sync.holds=fail`+ // and company-brain cursors keep the refusal. The hold's intent shape is what the entry would have imported.+ const frozenIntent = { content, blobOid: blob?.oid, expected_revision: revision, rawHash };+ const moved = entry.renameFrom;+ const pageHold = async (why: string, observedPageId: number | null, observedRevision: string | null): Promise<Held> => {+ const proof = await pageChangeProof(engine, { sourceId: cursor.sourceId, incarnation: cursor.incarnation, pageId, expectedRevision: revision });+ assertActive();+ return { hold: pageChangedHold(entry, slug, observedPageId ?? pageId, frozenIntent, { proof, revision: observedRevision, why }) };+ };if (occupant && (content === null || !await sameContentAtOrigin(engine, cursor, entry, key, snapshot, content, rawHash, lineEndingOnly, run.signal))) {+ if (screening) return pageHold(`another run of this source imported page ${slug} from ${entry.path} with different content`, occupant.page.id, occupant.revision);throw syncRunRefusal('page_identity_changed', 'The imported origin no longer identifies exactly the accepted page.', retry,`Page ${slug} was imported from ${entry.path} by another run of source ${cursor.sourceId} with different content after this run enumerated it, so the run stopped before admitting it.`);}occupantRebound = occupant !== null;- const moved = entry.renameFrom;const recorded = moved?.slug === slug ? moved.sourcePath : entry.sourcePath;const foreignOrigin = snapshot?.page.source_path != null && !sameSyncOrigin(snapshot.page.source_path, recorded, originScope, snapshot.page.slug);if ((snapshot?.page.id ?? null) !== pageId || (snapshot?.revision ?? null) !== revision || (entry.unownedDeletion ? !foreignOrigin : foreignOrigin)) {- throw syncRunRefusal('revision_conflict', 'A page changed after this sync cursor was enumerated.', retry,+ if (!screening) throw syncRunRefusal('revision_conflict', 'A page changed after this sync cursor was enumerated.', retry,`Page ${slug} in source ${cursor.sourceId} was edited, deleted or re-bound after this sync enumerated ${entry.path}, so the run stopped before admitting it.`);+ // The page moved but still holds exactly what this import carries: re-bind the entry to it (the waiver screen passes it).+ const rebind = entry.action === 'import' && !moved && !foreignOrigin && snapshot !== null && snapshot.page.deleted_at == null+ && (snapshot.page.id === pageId || pageId === null) && content !== null+ && await sameContentAtOrigin(engine, cursor, entry, key, snapshot, content, rawHash, lineEndingOnly, run.signal);+ assertActive();+ if (!rebind) return pageHold(`page ${slug} was ${snapshot === null || snapshot.page.deleted_at != null ? 'deleted' : foreignOrigin ? 're-bound to another file' : 'edited'} in the database`,+ snapshot?.page.id ?? null, snapshot?.revision ?? null);+ pageId = snapshot!.page.id; revision = snapshot!.revision;}if (moved && moved.slug !== slug) {const previous = await engine.readPageSnapshot(moved.slug, { sourceId: cursor.sourceId, includeDeleted: true });assertActive();if (previous?.page.id !== moved.pageId || previous.revision !== moved.revision || previous.page.deleted_at != null ||previous.page.source_path == null || !sameSyncOrigin(previous.page.source_path, moved.sourcePath, originScope, previous.page.slug)) {+ if (screening) return { hold: pageChangedHold(entry, slug, pageId, frozenIntent, { proof: null, revision: previous?.revision ?? null,+ why: `page ${moved.slug}, which ${entry.path} was renamed from, changed or was deleted in the database` }) };throw syncRunRefusal('revision_conflict', 'A renamed page changed after this sync cursor was enumerated.', retry,`Page ${moved.slug}, which ${entry.path} was renamed from, changed or was deleted after this sync enumerated it, so the run stopped before admitting the rename.`);}@@ -591,6 +619,32 @@ async function convertBlockedCursor(engine: BrainEngine, blocked: Cursor, key: s}const fence = fenceReceiptLocation(failed);const compacted = !fence && failed.compacted === true && failed.error_message == null && ['invalid_params', 'take_row_collision'].includes(failed.error_code ?? '');+ // #6340: a cursor an older run left blocked on a page that moved under it converts the same way the run now does.+ if (!fence && !compacted && entry && entry.path === previous.intent.path && previous.intent.kind !== 'managed_sync_checkpoint' && !blocked.companyPlan) {+ const proof = previous.intent.kind === 'managed_sync_import' ? await concurrentWriteProof(engine, { sourceId: blocked.sourceId, incarnation: blocked.incarnation, pending: previous, done: failed }) : null;+ const moved = proof ? null : await pageMovedSinceAdmission(engine, blocked.sourceId, previous, failed);+ const dirty = !proof && !moved && previous.intent.kind === 'managed_sync_import' && pinnedWorktreeConflict(failed);+ assertActive();+ if (proof || moved || dirty) {+ // The file may have been committed meanwhile: a re-freeze then imports HEAD's bytes instead of holding the stale conflict.+ if (dirty && headCommittedBytes(blocked, entry.path)?.rawHash !== undefined) {+ const base: Cursor = { ...blocked }; delete base.pending;+ const again = await freezeEntry(engine, base, key, assertActive, run);+ const converted = [...(blocked.convertedFromFailed ?? []), previous.requestId];+ if ('hold' in again) {+ const held = await holdUnderGate(engine, { cursor: blocked, key, pending: previous, hold: again.hold, assertActive, observedAt: run.observedAt!, waitMs: 5000, failedId: failed.id });+ return held === 'pending' ? blocked : held;+ }+ return saveCursor(engine, key, blocked, { ...blocked, convertedFromFailed: converted, pending: { ...again, converted: true } }, false, assertActive,+ tx => recordSyncConversion(tx, blocked.sourceId, blocked.incarnation, { request_id: previous.requestId, path: previous.intent.path ?? null, slug: previous.slug, run_id: blocked.runId, outcome: 'refrozen' }));+ }+ const hold = proof ? concurrentWriteHold(entry, previous.slug, previous.pageId!, previous.intent, proof)+ : moved ? pageChangedHold(entry, previous.slug, previous.pageId, previous.intent, { proof: null, revision: moved.revision, why: `page ${previous.slug} changed in the database` })+ : worktreeDirtyHold(entry, previous.slug, previous.pageId, previous.intent);+ const held = await holdUnderGate(engine, { cursor: blocked, key, pending: previous, hold, assertActive, observedAt: run.observedAt!, waitMs: 5000, failedId: failed.id });+ return held === 'pending' ? blocked : held;+ }+ }if (!fence && !compacted && !isContentRefusal(failed.error_code, failed.error_message)) return blocked;const base: Cursor = { ...blocked }; delete base.pending;const again = await freezeEntry(engine, base, key, assertActive, run);@@ -631,7 +685,8 @@ async function holdFailedFenceRequest(engine: BrainEngine, cursor: Cursor, key:const entry = cursor.entries[cursor.index];if (!entry || entry.path !== pending.intent.path) return null;const stalled = preparationStalled(done);- if (!stalled && (pending.intent.kind !== 'managed_sync_import' || typeof pending.intent.content !== 'string')) return null;+ const page = pending.intent.kind === 'managed_sync_import' && typeof pending.intent.content === 'string';+ if (!stalled && !page && pending.intent.kind !== 'managed_sync_delete') return null;let base: Cursor | undefined;if (stalled) {// #6278 (1.5): the breaker counts the receipt first; at the trip the run stops and converts neither this receipt nor a later one.@@ -640,13 +695,19 @@ async function holdFailedFenceRequest(engine: BrainEngine, cursor: Cursor, key:if (breaker.tripped) return { tripped: await saveCursor(engine, key, cursor, { ...cursor, breaker }, false, assertActive) };base = { ...cursor, breaker }; delete base.pending; delete base.group; delete base.window;}- const fence = stalled ? null : fenceReceiptLocation(done);+ const fence = stalled || !page ? null : fenceReceiptLocation(done);// #6194 (D4): a revision conflict proven to come from a concurrent database-only write is held the same way (sync-concurrent-write.ts).- const proof = stalled || fence ? null : await concurrentWriteProof(engine, { sourceId: cursor.sourceId, incarnation: cursor.incarnation, pending, done });- if (!stalled && !fence && !proof) return null;+ const proof = stalled || fence || !page ? null : await concurrentWriteProof(engine, { sourceId: cursor.sourceId, incarnation: cursor.incarnation, pending, done });+ // #6340: a revision conflict whose page really moved (no proof of who moved it) and a pinned-worktree conflict (uncommitted+ // local bytes) hold the page too (sync-page-fault.ts); a run-level revision conflict (the page is where it was) still blocks.+ const moved = stalled || fence || proof ? null : await pageMovedSinceAdmission(engine, cursor.sourceId, pending, done);+ const dirty = !stalled && !fence && !proof && !moved && page && pinnedWorktreeConflict(done);+ if (!stalled && !fence && !proof && !moved && !dirty) return null;const hold = stalled ? preparationStalledHold(entry, pending.slug, pending.pageId, done, pending.intent.content ?? null, pending.intent.blobOid, resumeArgsOf(cursor, run)): fence ? prepareTimeFenceHold(entry, pending.slug, pending.pageId, fence, pending.intent.content!, pending.intent.blobOid)- : concurrentWriteHold(entry, pending.slug, pending.pageId!, pending.intent, proof!);+ : proof ? concurrentWriteHold(entry, pending.slug, pending.pageId!, pending.intent, proof)+ : moved ? pageChangedHold(entry, pending.slug, pending.pageId, pending.intent, { proof: null, revision: moved.revision, why: `page ${pending.slug} changed in the database` })+ : worktreeDirtyHold(entry, pending.slug, pending.pageId, pending.intent);return holdUnderGate(engine, { cursor, key, pending, hold, assertActive, observedAt: run.observedAt!, waitMs, failedId: done.id, base });}@@ -1189,6 +1250,7 @@ async function runManagedSync(engine: BrainEngine, opts: SyncOpts, slice: { maxPcursor = await saveCursor(engine, key, cursor, { ...retry, pending: await freezeEntry(engine, retry, key, assertActive, frozenRun) as Pending }, true, assertActive);}}+ const startupConfig = await preparationConfigView(engine); // #5984 G3: one config read answers the startup's config readsif (cursor && opts.retryFailed && !opts.dryRun && !company && !cursor.done) {const unfinished = await engine.executeRaw(`SELECT id FROM persistence_requests WHERE source_id=$1AND (state IN ('queued','running','recovering') OR recovery IS NOT NULL) LIMIT 1`, [cursor.sourceId]);@@ -1198,11 +1260,19 @@ async function runManagedSync(engine: BrainEngine, opts: SyncOpts, slice: { maxPconst recorded = await engine.executeRaw("SELECT 1 FROM op_checkpoints WHERE op='managed-sync-failure' AND fingerprint=$1 AND completed_keys->0->>'run_id'=$2", [key, cursor.runId]);assertActive();if ((failed && ['failed', 'conflict', 'cancelled'].includes(failed.state)) || (recorded.length && (failed?.state === 'committed' || !failed))) {- phase = 'discovery';- discoveryTarget = syncGit(context.gitRoot, ['rev-parse', 'HEAD']).trim();- const discovery = await discoverManagedSync(engine, opts, context);+ // #6340: a pending request the run would now hold (a page that moved, a dirty file, a fence) converts in place with+ // the frozen manifest instead of rediscovering it; only a failure no hold covers still rediscovers.+ const screen = failed && cursor.pending ? await loadSyncScreenRun(startupConfig, cursor.sourceId, cursor.processingOptions ?? processingOptions, authority.writer.remote) : null;+ const converted = screen ? await convertBlockedCursor(engine, cursor, key, assertActive, { ...frozenRun, screen, observedAt: cursor.discoveredAt ?? runStartedAt }) : cursor;assertActive();- cursor = await replaceCursor(engine, key, header(cursor), { ...discovery, authority, processingOptions, syncOptions, runId: discoveryRun, index: 0, counts: { added: 0, modified: 0, deleted: 0, chunks: 0 } }, assertActive);+ if (converted !== cursor) cursor = converted;+ else {+ phase = 'discovery';+ discoveryTarget = syncGit(context.gitRoot, ['rev-parse', 'HEAD']).trim();+ const discovery = await discoverManagedSync(engine, opts, context);+ assertActive();+ cursor = await replaceCursor(engine, key, header(cursor), { ...discovery, authority, processingOptions, syncOptions, runId: discoveryRun, index: 0, counts: { added: 0, modified: 0, deleted: 0, chunks: 0 } }, assertActive);+ }}}}@@ -1215,7 +1285,6 @@ async function runManagedSync(engine: BrainEngine, opts: SyncOpts, slice: { maxPreturn result(cursor, cursor.from === null ? 'first_sync' : 'synced');}if (cursor?.done) cursor = await retireCompletedCursor(engine, key, cursor, assertActive);- const startupConfig = await preparationConfigView(engine); // #5984 G3: one config read answers the startup's config readsif (!cursor) {assertActive();phase = 'discovery';@@ -1403,8 +1472,10 @@ async function runManagedSync(engine: BrainEngine, opts: SyncOpts, slice: { maxPif (!opts.dryRun) {const code = error instanceof OperationError ? error.code : 'storage_error';// A refresh fence, or an admission refused while other requests hold the writer's outstanding cap (#6278: the drain- // waits for them), is transient admission back-pressure, not a sync failure to record.- if (!['permission_denied', 'worktree_refreshing', 'refresh_recovery_required'].includes(code) && !isWriteCapacityWait(error)) {+ // waits for them), is transient admission back-pressure, not a sync failure to record. #6340: neither is a lost+ // database connection or a statement timeout: the cursor and its frozen manifest stay, and the next pass resumes them.+ if (!['permission_denied', 'worktree_refreshing', 'refresh_recovery_required'].includes(code) && !isWriteCapacityWait(error)+ && !isRetryableConnError(error) && !isStatementTimeoutError(error)) {const [stored] = cursor ? [] : await engine.executeRaw<{ completed_keys: [CursorHeader] }>('SELECT completed_keys FROM op_checkpoints WHERE op=$1 AND fingerprint=$2', [OP, key]);const failedCursor = cursor ?? stored?.completed_keys?.[0];const { failure } = await recordManagedSyncFailure(engine, { source_id: context.sourceId, source_incarnation: context.incarnation, path: cursor?.entries[cursor.index]?.path ?? failedCursor?.pending?.intent.path ?? `<${phase}>`, code,diff --git a/src/core/persistence/sync-status.ts b/src/core/persistence/sync-status.tsnew file mode 100644index 0000000000..9d0efe814d--- /dev/null+++ b/src/core/persistence/sync-status.ts@@ -0,0 +1,174 @@+/**+ * #6340: the machine-readable unblock contract for a managed catch-up, so an+ * operator agent can run the recovery loop without a person:+ *+ * status every N minutes → if committed_last_10m == 0 and nothing needs a+ * human → unblock --apply → rerun the sync it names → else page a person with+ * the slug.+ *+ * `readSyncStatus` joins the unfinished cursor (position, pinned target, last+ * advance, rate), the pages committed in the last ten minutes, every hold and+ * the last recorded failure, each with the `class` / `safe_actions` /+ * `needs_human` triple from `sync-fault-class.ts`, and one `next` action.+ * `unblockSync` performs the safe action for every hold that has one (a+ * `worktree_dirty` hold whose file is now committed and a `preparation_stalled`+ * hold are scheduled for a re-screen) and refuses the rest by name: refusing is+ * the only way it leaves a page out, and it never drops content. Both are+ * trusted-local readers (the CLI); paths are source-root relative.+ */+import type { BrainEngine } from '../engine.ts';+import type { Action } from '../agent-output.ts';+import { managedSyncResumeArgs } from '../sync-reconcile.ts';+import { readManagedSyncFailures, type ManagedSyncFailure } from './sync-failures.ts';+import { gitHoldFix, readGitSourceHolds, requestGitHoldRetry, type GitHoldRecord } from './sync-holds.ts';+import { classifySyncFault, HOLD_ATTEMPTS_NEEDS_HUMAN, type SyncFaultVerdict } from './sync-fault-class.ts';+import { headCommittedBytes } from './sync-page-fault.ts';+import { drainEstimate } from './sync-drain.ts';+import { resolveManagedSyncContext } from './sync-discovery.ts';++export interface SyncStatusHold extends SyncFaultVerdict {+ code: string;+ slug: string | null;+ path: string;+ attempts: number;+ held_since: string;+ /** When the hold can be retried on its own: now (`null`), or never without the named step. */+ retry_after: string | null;+ fix: Action;+}++export interface SyncStatusError extends SyncFaultVerdict {+ code: string;+ message: string;+ slug?: string;+ path?: string;+ request_id?: string;+ phase: ManagedSyncFailure['phase'];+ first_seen: string;+ attempts: number;+}++export interface SyncStatus {+ source_id: string;+ run_id: string | null;+ cursor: { index: number; total: number; pinned_target: string | null; last_advance_at: string | null; done: boolean } | null;+ /** Managed sync page requests of the source committed in the last ten minutes (waived entries are not requests). */+ committed_last_10m: number;+ rate_pages_per_min: number | null;+ eta_seconds: number | null;+ holds: SyncStatusHold[];+ last_error: SyncStatusError | null;+ /** Whether anything (a hold or the last error) waits on a person; the first such reason. */+ needs_human: boolean;+ human_reason?: string;+ /** The resume arguments after `gbrain sync` for this source's cursor (its stored options when one exists). */+ resume_argv: string[];+ next: Action | null;+}++interface CursorHeader { runId: string; index: number; total: number; target: string | null; done?: boolean;+ progress?: { startedAt: number; startIndex: number; lastAt: number; lastIndex: number };+ processingOptions?: { noEmbed?: boolean; noExtract?: boolean; noSchemaPack?: boolean }; syncOptions?: Parameters<typeof managedSyncResumeArgs>[0]['syncOptions'] }++async function cursorHeader(engine: BrainEngine, sourceId: string): Promise<CursorHeader | null> {+ const rows = await engine.executeRaw<{ header: CursorHeader }>(+ `SELECT completed_keys->0 AS header FROM op_checkpoints WHERE op='managed-sync' AND completed_keys->0->>'sourceId'=$1 ORDER BY updated_at DESC LIMIT 1`, [sourceId]);+ return rows[0]?.header ?? null;+}++function holdStatus(record: GitHoldRecord): SyncStatusHold {+ const attempts = record.meta.attempts ?? 1;+ const verdict = classifySyncFault({ code: record.code, attempts });+ return { code: record.code, slug: record.slug, path: record.path, attempts, held_since: record.held_at, ...verdict,+ retry_after: verdict.safe_actions[0] === 'retry' || verdict.safe_actions[0] === 'retry_when_clean' ? null : 'after the named step', fix: gitHoldFix(record) };+}++export async function readSyncStatus(engine: BrainEngine, sourceId: string): Promise<SyncStatus> {+ const [source] = await engine.executeRaw<{ incarnation: string }>('SELECT incarnation::text AS incarnation FROM sources WHERE id=$1 AND archived IS NOT TRUE', [sourceId]);+ if (!source) throw Object.assign(new Error(`Source ${sourceId} does not exist.`), { code: 'not_found' });+ const header = await cursorHeader(engine, sourceId);+ const [committed] = await engine.executeRaw<{ n: number | string }>(`SELECT count(*) AS n FROM persistence_requests WHERE source_id=$1 AND state='committed'+ AND intent->>'kind' IN ('managed_sync_import','managed_sync_delete') AND completed_at > now() - interval '10 minutes'`, [sourceId]);+ const holds = ((await readGitSourceHolds(engine, { sourceIds: [sourceId] }))[0]?.holds ?? []).filter(hold => hold.incarnation === source.incarnation).map(holdStatus);+ const failures = (await readManagedSyncFailures(engine, [sourceId])).filter(failure => failure.code !== 'sync_incomplete');+ const failure = failures[0];+ const lastError: SyncStatusError | null = failure ? { code: failure.code, message: failure.message, path: failure.path, phase: failure.phase, first_seen: failure.first_seen, attempts: failure.attempts,+ ...(failure.request_id ? { request_id: failure.request_id } : {}), ...classifySyncFault({ code: failure.code, message: failure.message }) } : null;+ const unfinished = !!header && !header.done;+ const remaining = header ? Math.max(0, Number(header.total) - Number(header.index)) : null;+ const p = header?.progress;+ const estimate = unfinished && p ? drainEstimate(remaining, p.lastIndex - p.startIndex, p.lastAt - p.startedAt) : { rate_pages_per_min: null, eta_seconds: null };+ const resume = managedSyncResumeArgs({ sourceId, processingOptions: header?.processingOptions, syncOptions: header?.syncOptions });+ const human = holds.find(hold => hold.needs_human) ?? (lastError?.needs_human ? lastError : undefined);+ const actionable = holds.filter(hold => !hold.needs_human && hold.safe_actions[0] !== 'none');+ const verify = { argv: ['gbrain', 'sync', 'status', '--source', sourceId, '--json'] };+ const next: Action | null = human+ ? { ...('fix' in human ? human.fix : { argv: ['gbrain', 'sources', 'status', sourceId, '--json'], consent: [], actor: 'host_admin' as const, requires_exclusive: false, why: human.human_reason ?? '' }),+ user_message: `Sync of source ${sourceId} needs a decision: ${'slug' in human && human.slug ? `page ${human.slug} (${('path' in human ? human.path : undefined) ?? ''})` : `code ${human.code}`}: ${human.human_reason ?? 'see the hold'}` }+ : actionable.length+ ? { argv: ['gbrain', 'sync', 'unblock', '--source', sourceId, '--apply', '--json'], consent: [], actor: 'agent', requires_exclusive: false, verify,+ why: `${actionable.length} held file(s) have a safe action: unblock schedules each one whose condition holds (a committed edit, a stalled preparation) for a re-screen and names the sync to run; it refuses the rest by name and drops nothing.` }+ : unfinished || lastError+ ? { argv: ['gbrain', 'sync', ...resume, ...(lastError ? ['--retry-failed'] : [])], consent: [], actor: 'agent', requires_exclusive: false, verify,+ why: lastError ? `The last run recorded ${lastError.code} (${lastError.class}); this release holds or retries it, and --retry-failed converts the stopped entry in place without re-freezing the manifest.`+ : `The cursor stands at ${header!.index}/${header!.total}; the same command resumes it against the frozen manifest.` }+ : null;+ return { source_id: sourceId, run_id: header?.runId ?? null,+ cursor: header ? { index: Number(header.index), total: Number(header.total), pinned_target: header.target ?? null, last_advance_at: p ? new Date(p.lastAt).toISOString() : null, done: !!header.done } : null,+ committed_last_10m: Number(committed?.n ?? 0), ...estimate, holds, last_error: lastError, needs_human: !!human, ...(human ? { human_reason: human.human_reason } : {}),+ resume_argv: resume, next };+}++export interface UnblockOutcome {+ source_id: string;+ apply: boolean;+ /** Holds whose safe action ran (or, without --apply, would run). */+ applied: Array<{ path: string; slug: string | null; code: string; action: 'retry_when_clean' | 'retry'; detail: string }>;+ /** Holds unblock leaves in place, each with why and the step that clears it. */+ refused: Array<{ path: string; slug: string | null; code: string; reason: string; needs_human: boolean; fix: Action }>;+ /** The sync to run after an apply (the cursor's stored options), or the first refusal's fix when nothing applied. */+ next: Action | null;+}++/**+ * Performs the safe action for every hold that has one. `retry_when_clean` (`worktree_dirty`): the file is re-screened only+ * when its working-tree bytes are committed at HEAD now; still-dirty files are refused `still_dirty`. `retry`+ * (`preparation_stalled`): scheduled for a re-screen. A hold whose attempts reached `HOLD_ATTEMPTS_NEEDS_HUMAN`, a+ * `concurrent_write` hold and every repair-class hold are refused by name with their fix. Idempotent: scheduling twice is+ * one re-screen, and nothing here writes a page or clears a hold.+ */+export async function unblockSync(engine: BrainEngine, sourceId: string, opts: { apply: boolean }): Promise<UnblockOutcome> {+ const [source] = await engine.executeRaw<{ incarnation: string }>('SELECT incarnation::text AS incarnation FROM sources WHERE id=$1 AND archived IS NOT TRUE', [sourceId]);+ if (!source) throw Object.assign(new Error(`Source ${sourceId} does not exist.`), { code: 'not_found' });+ const holds = ((await readGitSourceHolds(engine, { sourceIds: [sourceId] }))[0]?.holds ?? []).filter(hold => hold.incarnation === source.incarnation);+ const header = await cursorHeader(engine, sourceId);+ const resume = managedSyncResumeArgs({ sourceId, processingOptions: header?.processingOptions, syncOptions: header?.syncOptions });+ const context = holds.some(hold => hold.code === 'worktree_dirty') ? await resolveManagedSyncContext(engine, { sourceId, noPull: true }).catch(() => null) : null;+ const applied: UnblockOutcome['applied'] = [], refused: UnblockOutcome['refused'] = [];+ for (const hold of holds) {+ const status = holdStatus(hold);+ const refuse = (reason: string) => refused.push({ path: hold.path, slug: hold.slug, code: hold.code, reason, needs_human: status.needs_human, fix: status.fix });+ if (status.needs_human) { refuse(status.human_reason ?? 'needs a person'); continue; }+ if (hold.code === 'worktree_dirty') {+ const committed = context ? headCommittedBytes(context, hold.path) : null;+ if (!committed) { refuse(context ? 'still_dirty: the working-tree bytes are not committed at HEAD yet' : 'checkout_unreadable: the source checkout could not be resolved'); continue; }+ applied.push({ path: hold.path, slug: hold.slug, code: hold.code, action: 'retry_when_clean', detail: `committed at HEAD as blob ${committed.oid.slice(0, 12)}; scheduled for a re-screen` });+ continue;+ }+ if (hold.code === 'preparation_stalled') {+ applied.push({ path: hold.path, slug: hold.slug, code: hold.code, action: 'retry', detail: `attempt ${(hold.meta.attempts ?? 1) + 1} of ${HOLD_ATTEMPTS_NEEDS_HUMAN}; scheduled for a re-screen` });+ continue;+ }+ refuse(`${status.safe_actions[0]}: not something unblock performs; run the fix it names`);+ }+ if (opts.apply && applied.length) await requestGitHoldRetry(engine, sourceId, source.incarnation, applied.map(entry => entry.path));+ const verify = { argv: ['gbrain', 'sync', 'status', '--source', sourceId, '--json'] };+ const next: Action | null = applied.length+ ? opts.apply+ ? { argv: ['gbrain', 'sync', ...resume], consent: [], actor: 'agent', requires_exclusive: false, verify,+ why: `${applied.length} held file(s) are scheduled for a re-screen; the sync imports each one that now passes and holds again what still fails, without blocking the rest.` }+ : { argv: ['gbrain', 'sync', 'unblock', '--source', sourceId, '--apply', '--json'], consent: [], actor: 'agent', requires_exclusive: false, verify,+ why: `${applied.length} held file(s) would be scheduled for a re-screen; nothing was written. --apply schedules them and prints the sync to run.` }+ : refused[0]?.fix ?? null;+ return { source_id: sourceId, apply: opts.apply, applied, refused, next };+}diff --git a/src/core/retry-matcher.ts b/src/core/retry-matcher.tsindex 87699cb789..56489be257 100644--- a/src/core/retry-matcher.ts+++ b/src/core/retry-matcher.ts@@ -48,6 +48,12 @@ const CONN_PATTERNS = [// retry, the checkpoint write (and every other pool-contending write) is// dropped during the exact spike #1794's resumable sync must survive./EMAXCONNSESSION/i,+ // #6340: the socket errnos postgres.js surfaces as "write <ERRNO> host:port" when a+ // session-mode pooler drops the connection mid-statement (ECONNABORTED was the one+ // that ended four managed catch-up runs in one afternoon). Same class as ECONNRESET.+ /ECONNABORTED/i,+ /ETIMEDOUT/i,+ /EPIPE/i,/too many clients already/i,/max.*clients?.*in session mode/i,/remaining connection slots are reserved/i,diff --git a/test/managed-sync-concurrent-write-hold.test.ts b/test/managed-sync-concurrent-write-hold.test.tsindex d0fe9a87a3..53ed92bcfd 100644--- a/test/managed-sync-concurrent-write-hold.test.ts+++ b/test/managed-sync-concurrent-write-hold.test.ts@@ -102,12 +102,16 @@ for (const databaseUrl of process.env.DATABASE_URL ? [undefined, process.env.DATexpect(await engine.getPage(SLUG, { sourceId: 'default' })).toBeNull();}, { databaseUrl, setup }), 120_000);- test('a revision conflict no journal request explains keeps blocking', () => managedBrain(async ({ engine, root }) => {+ // #6340: a page that moved with no journal request to name is held too (the revision alone is the proof the page moved); the fix stays the reconcile preview.+ test('a revision conflict no journal request explains is held by its revision, not left blocking', () => managedBrain(async ({ engine, root }) => {const { first } = await raced(engine, root, () => engine.transaction(tx => withCoordinatedWrite(tx, ['default'], () => tx.putPage(SLUG, {type: 'person', title: 'Alice Example', compiled_truth: 'An unattributed database edit.', timeline: '', frontmatter: {}, content_hash: 'unattributed',}, { sourceId: 'default' }), TEST_WRITE_ATTRIBUTION)));- expect(first).toMatchObject({ status: 'blocked_by_failures', failureCodes: [{ code: 'revision_conflict', count: 1 }] });- expect(first.held ?? []).toEqual([]);- expect(first.managedWrite?.suggestion).toContain(`gbrain sources reconcile default ${SLUG} --preview`);+ expect(first.status).not.toBe('blocked_by_failures');+ expect(first.managedWrite).toBeUndefined();+ expect(first.held?.map(hold => hold.code)).toEqual(['concurrent_write']);+ expect(first.held![0]!.fix.why).toContain(`changed in the database`);+ expect(first.held![0]!.fix.argv).toEqual(['gbrain', 'sources', 'reconcile', 'default', SLUG, '--preview']);+ expect((await engine.getPage(SLUG, { sourceId: 'default' }))?.compiled_truth).toContain('An unattributed database edit.');}, { databaseUrl, setup }), 120_000);});diff --git a/test/managed-sync-page-fault-holds.test.ts b/test/managed-sync-page-fault-holds.test.tsnew file mode 100644index 0000000000..59722144ba--- /dev/null+++ b/test/managed-sync-page-fault-holds.test.ts@@ -0,0 +1,287 @@+/**+ * #6340: a page that moves under a managed catch-up holds the page, not the run.+ *+ * On a live checkout (agents commit to the brain repo every few minutes while a+ * multi-hour catch-up drains a frozen manifest) four recoverable faults ended+ * the whole run and every relaunch re-froze the manifest: `revision_conflict`+ * and `page_identity_changed` at freeze time, `pinned_git_worktree_conflict`+ * at publication, and a pooler drop (`write ECONNABORTED`) that the retry+ * classifier did not know. Each probe here fails on master (the run throws or+ * returns `blocked_by_failures`, or the next run rediscovers from index 0) and+ * passes with the resolver (`sync-page-fault.ts`), the receipt conversions and+ * the ledger skip. Synthetic content only.+ */+import { afterAll, beforeAll, expect, test } from 'bun:test';+import { randomUUID } from 'node:crypto';+import { mkdtempSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { execFileSync } from 'node:child_process';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';+import type { BrainEngine } from '../src/core/engine.ts';+import { claimWorktree } from '../src/core/persistence/ownership.ts';+import { performManagedSync } from '../src/core/persistence/sync-run.ts';+import { readGitHold, readGitSourceHolds } from '../src/core/persistence/sync-holds.ts';+import { readManagedSyncFailures } from '../src/core/persistence/sync-failures.ts';+import { headCommittedBytes, HOLD_ATTEMPTS_NEEDS_HUMAN, pinnedWorktreeConflict } from '../src/core/persistence/sync-page-fault.ts';+import { withCoordinatedWrite } from '../src/core/persistence/context.ts';+import { TEST_WRITE_ATTRIBUTION } from './helpers/write-attribution.ts';+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';+import { withEnv } from './helpers/with-env.ts';+import { loadSyncFailures } from '../src/core/sync-failure-ledger.ts';+import { parseMarkdown } from '../src/core/markdown.ts';+import { contentHash } from '../src/core/utils.ts';++const home = mkdtempSync(join(tmpdir(), 'gbrain-page-fault-holds-'));+const engines: BrainEngine[] = [];+const sources: string[] = [];+let closePostgres: (() => Promise<void>) | undefined;+function git(root: string, ...args: string[]): string { return execFileSync('git', ['-C', root, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim(); }+function commit(root: string, message = 'synthetic content'): string { git(root, 'add', '.'); git(root, '-c', 'user.name=Example', '-c', '[email protected]', 'commit', '-qm', message); return git(root, 'rev-parse', 'HEAD'); }+const note = (body: string) => `---\ntitle: Example\n---\n${body}\n`;+async function fixture(engine: BrainEngine, files: Record<string, string>) {+ const id = `fault-${randomUUID().replace(/-/g, '').slice(0, 20)}`; sources.push(id);+ const root = join(home, id); mkdirSync(root); git(root, 'init', '-q');+ for (const [path, body] of Object.entries(files)) { const full = join(root, path); mkdirSync(join(full, '..'), { recursive: true }); writeFileSync(full, body); }+ const head = commit(root);+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');+ await engine.executeRaw("INSERT INTO sources(id,name,local_path,config) VALUES($1,$1,$2,'{}')", [id, root]);+ await claimWorktree(engine, id, root);+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');+ return { id, root, head, opts: { sourceId: id, noPull: true, noEmbed: true, noExtract: true } };+}+/** Counts the manifest identity freeze (`discoverManagedSync`'s one-statement page snapshot) for `sourceId`: zero means no rediscovery. */+function countDiscoveries(engine: BrainEngine, sourceId: string): { count: () => number; restore: () => void } {+ const executeRaw = engine.executeRaw;+ let reads = 0;+ engine.executeRaw = async function (this: BrainEngine, sql: string, params?: unknown[]) {+ if (params?.[0] === sourceId && sql.includes('SELECT id,slug,source_path,knowledge_revision FROM pages')) reads++;+ return executeRaw.call(this, sql, params);+ } as BrainEngine['executeRaw'];+ return { count: () => reads, restore: () => { engine.executeRaw = executeRaw; } };+}+const cursorOf = (engine: BrainEngine, sourceId: string) => engine.executeRaw<{ run_id: string; index: number; total: number; target: string; done: boolean | null }>(+ `SELECT completed_keys->0->>'runId' AS run_id,(completed_keys->0->>'index')::int AS index,(completed_keys->0->>'total')::int AS total,completed_keys->0->>'target' AS target,+ (completed_keys->0->>'done')::boolean AS done FROM op_checkpoints WHERE op='managed-sync' AND completed_keys->0->>'sourceId'=$1`, [sourceId]).then(rows => rows[0]);+const dbWrite = (engine: BrainEngine, sourceId: string, slug: string, body: string) => engine.transaction(tx => withCoordinatedWrite(tx, [sourceId], () => tx.putPage(slug, {+ type: 'note', title: 'Example', compiled_truth: body, timeline: '', frontmatter: {}, content_hash: `h-${body.length}` }, { sourceId }), TEST_WRITE_ATTRIBUTION));+/** Interrupts the first sync after `pages` committed pages, so the cursor's pinned target trails the commits the test makes next. */+async function interruptedAfter(engine: BrainEngine, opts: { sourceId: string; noPull: boolean }, pages: number) {+ const abort = new AbortController();+ const partial = await performManagedSync(engine, { ...opts, signal: abort.signal, onProgress: p => { if (p.bankedFiles === pages) abort.abort(); } });+ expect(partial).toMatchObject({ status: 'partial', filesImported: pages });+ return partial;+}++beforeAll(async () => {+ const lite = new PGLiteEngine(); await lite.connect({}); await lite.initSchema(); engines.push(lite);+ if (process.env.DATABASE_URL) { const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL); engines.push(pg.engine); closePostgres = pg.close; }+}, 120_000);+afterAll(async () => {+ await withEnv({ GBRAIN_HOME: home }, async () => {+ for (const engine of engines) { await disposePersistenceConsumer(engine); await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');+ for (const id of sources) await engine.executeRaw('DELETE FROM sources WHERE id=$1', [id]); await engine.disconnect(); }+ });+ await closePostgres?.();+ rmSync(home, { recursive: true, force: true });+});++test('a resumed cursor imports a page committed past its pinned target instead of refusing it (#6320, from PR #6323)', async () => withEnv({ GBRAIN_HOME: home }, async () => {+ for (const engine of engines) {+ const f = await fixture(engine, { 'a.md': note('First observation, version one.'), 'b.md': note('Second observation, version one.') });+ expect((await performManagedSync(engine, f.opts)).status).toBe('first_sync');+ writeFileSync(join(f.root, 'a.md'), note('First observation, version two.')); writeFileSync(join(f.root, 'b.md'), note('Second observation, version two.'));+ const pin = commit(f.root, 'version two of both');+ await interruptedAfter(engine, f.opts, 1);+ // A live checkout keeps committing while the cursor drains: b.md moves past the pin.+ writeFileSync(join(f.root, 'b.md'), note('Second observation, version three.')); const head = commit(f.root, 'version three of b, past the pin');+ expect(headCommittedBytes({ root: f.root, gitRoot: f.root }, 'b.md')).toMatchObject({ oid: git(f.root, 'rev-parse', 'HEAD:b.md') });+ const resumed = await performManagedSync(engine, f.opts);+ expect(resumed).toMatchObject({ status: 'synced', toCommit: pin }); expect(resumed.held_count ?? 0).toBe(0); expect(resumed.managedWrite).toBeUndefined();+ expect((await engine.getPage('b', { sourceId: f.id }))?.compiled_truth).toContain('version three');+ expect(readFileSync(join(f.root, 'b.md'), 'utf8')).toBe(note('Second observation, version three.'));+ expect(git(f.root, 'status', '--porcelain')).toBe('');+ const next = await performManagedSync(engine, f.opts);+ expect(next).toMatchObject({ toCommit: head, status: 'synced', modified: 0, waived: { imports: 1, deletes: 0 } });+ expect(loadSyncFailures().filter(row => row.source_id === f.id)).toHaveLength(0);+ expect(await readManagedSyncFailures(engine, [f.id])).toEqual([]);+ }+}), 120_000);++test('an uncommitted edit under the catch-up is held worktree_dirty with the pinned blob; committing it imports on the next sync and clears the hold', async () => withEnv({ GBRAIN_HOME: home }, async () => {+ for (const engine of engines) {+ const f = await fixture(engine, { 'a.md': note('Alpha, version one.'), 'b.md': note('Beta, version one.'), 'c.md': note('Gamma, version one.') });+ expect((await performManagedSync(engine, f.opts)).status).toBe('first_sync');+ for (const name of ['a', 'b', 'c']) writeFileSync(join(f.root, `${name}.md`), note(`${name} version two.`));+ const pin = commit(f.root, 'version two');+ await interruptedAfter(engine, f.opts, 1);+ // Another agent is mid-edit on b.md (the iMessage monitor case): the bytes match neither the pin nor the page and are not committed.+ const edit = note('Beta, a private edit still in progress.');+ writeFileSync(join(f.root, 'b.md'), edit);+ const resumed = await performManagedSync(engine, f.opts);+ expect(resumed).toMatchObject({ status: 'synced', toCommit: pin, held_count: 1, held: [{ path: 'b.md', code: 'worktree_dirty' }] });+ expect(resumed.managedWrite).toBeUndefined();+ expect(JSON.stringify(resumed)).not.toContain('private edit');+ expect((await engine.getPage('b', { sourceId: f.id }))?.compiled_truth).toContain('version one');+ expect((await engine.getPage('c', { sourceId: f.id }))?.compiled_truth).toContain('version two');+ expect(readFileSync(join(f.root, 'b.md'), 'utf8')).toBe(edit);+ const [source] = await engine.executeRaw<{ incarnation: string }>('SELECT incarnation::text AS incarnation FROM sources WHERE id=$1', [f.id]);+ const hold = (await readGitHold(engine, f.id, source.incarnation, 'b.md'))!;+ expect(hold).toMatchObject({ code: 'worktree_dirty', slug: 'b', meta: { blob_oid: git(f.root, 'rev-parse', `${pin}:b.md`), attempts: 1 } });+ expect(hold.meta.working_hash).toBeDefined();+ expect(resumed.held![0]!.fix.why).toContain('commit');+ expect(await readManagedSyncFailures(engine, [f.id])).toEqual([]);+ // Still dirty on the next run: nothing to re-screen (the pinned blob is unchanged), the hold stays, the run is up to date.+ expect((await performManagedSync(engine, f.opts)).status).toBe('up_to_date');+ expect((await readGitHold(engine, f.id, source.incarnation, 'b.md'))?.meta.attempts).toBe(1);+ // The agent commits its edit: the blob at the new target differs from the hold's, so discovery re-screens and imports it.+ const head = commit(f.root, 'the agent commits its edit');+ const after = await performManagedSync(engine, f.opts);+ expect(after).toMatchObject({ status: 'synced', toCommit: head, modified: 1 });+ expect((await engine.getPage('b', { sourceId: f.id }))?.compiled_truth).toContain('private edit still in progress');+ expect(await readGitHold(engine, f.id, source.incarnation, 'b.md')).toBeNull();+ }+}), 120_000);++test('a page edited in the database after the manifest froze is held concurrent_write with its revisions; one that already holds the import is re-bound and waived', async () => withEnv({ GBRAIN_HOME: home }, async () => {+ for (const engine of engines) {+ const f = await fixture(engine, { 'a.md': note('Alpha one.'), 'b.md': note('Beta one.'), 'c.md': note('Gamma one.'), 'd.md': note('Delta one.') });+ expect((await performManagedSync(engine, f.opts)).status).toBe('first_sync');+ for (const name of ['a', 'b', 'c', 'd']) writeFileSync(join(f.root, `${name}.md`), note(`${name} two.`));+ const pin = commit(f.root, 'version two');+ await interruptedAfter(engine, f.opts, 1);+ const frozen = await cursorOf(engine, f.id);+ // b: a database-only edit that diverges from the file; c: a database write that already carries exactly what the file would import.+ await dbWrite(engine, f.id, 'b', 'Beta, edited straight in the database.');+ const parsed = parseMarkdown(note('c two.'), 'c.md');+ const page = { type: parsed.type, title: parsed.title, compiled_truth: parsed.compiled_truth, timeline: parsed.timeline ?? '', frontmatter: parsed.frontmatter };+ await engine.transaction(tx => withCoordinatedWrite(tx, [f.id], () => tx.putPage('c', { ...page, content_hash: contentHash(page) }, { sourceId: f.id }), TEST_WRITE_ATTRIBUTION));+ const resumed = await performManagedSync(engine, f.opts);+ expect(resumed).toMatchObject({ status: 'synced', toCommit: pin, held_count: 1, held: [{ path: 'b.md', code: 'concurrent_write' }] });+ expect(resumed.managedWrite).toBeUndefined();+ expect((await cursorOf(engine, f.id))?.run_id).toBe(frozen.run_id);+ expect((await engine.getPage('b', { sourceId: f.id }))?.compiled_truth).toBe('Beta, edited straight in the database.');+ expect((await engine.getPage('c', { sourceId: f.id }))?.compiled_truth).toBe(parsed.compiled_truth);+ expect((await engine.getPage('d', { sourceId: f.id }))?.compiled_truth).toContain('d two.');+ const [source] = await engine.executeRaw<{ incarnation: string }>('SELECT incarnation::text AS incarnation FROM sources WHERE id=$1', [f.id]);+ const hold = (await readGitHold(engine, f.id, source.incarnation, 'b.md'))!;+ expect(hold.meta.page_revision).toBeDefined(); expect(hold.meta.expected_revision).toBeDefined();+ expect(hold.meta.page_revision).not.toBe(hold.meta.expected_revision);+ expect(resumed.held![0]!.fix.argv).toEqual(['gbrain', 'sources', 'reconcile', f.id, 'b', '--preview']);+ expect(await readGitHold(engine, f.id, source.incarnation, 'c.md')).toBeNull();+ expect(await readManagedSyncFailures(engine, [f.id])).toEqual([]);+ // A page deleted in the database after the freeze holds the same way; the page stays deleted.+ for (const name of ['a', 'b', 'c', 'd']) writeFileSync(join(f.root, `${name}.md`), note(`${name} three.`));+ const pin3 = commit(f.root, 'version three');+ await interruptedAfter(engine, f.opts, 1);+ await engine.transaction(tx => withCoordinatedWrite(tx, [f.id], () => tx.softDeletePage('d', { sourceId: f.id }), TEST_WRITE_ATTRIBUTION));+ const third = await performManagedSync(engine, f.opts);+ expect(third).toMatchObject({ status: 'synced', toCommit: pin3 });+ expect(third.held?.map(hold => [hold.path, hold.code])).toEqual([['d.md', 'concurrent_write']]);+ expect(await engine.getPage('d', { sourceId: f.id })).toBeNull();+ }+}), 120_000);++test('a cursor an older run left blocked on a pinned-worktree conflict converts in place under --retry-failed instead of rediscovering, and counts attempts', async () => withEnv({ GBRAIN_HOME: home, GBRAIN_SYNC_FAILURES_DIR: home }, async () => {+ for (const engine of engines) {+ const f = await fixture(engine, { 'a.md': note('Alpha one.'), 'b.md': note('Beta one.'), 'c.md': note('Gamma one.') });+ expect((await performManagedSync(engine, f.opts)).status).toBe('first_sync');+ for (const name of ['a', 'b', 'c']) writeFileSync(join(f.root, `${name}.md`), note(`${name} two.`));+ commit(f.root, 'version two');+ const edit = note('Beta, an uncommitted edit.');+ writeFileSync(join(f.root, 'b.md'), edit);+ // The brain ran the old release: holds off, so the conflict blocked the run and left the failed request on the cursor.+ await engine.setConfig('sync.holds', 'fail');+ let blocked;+ try { blocked = await performManagedSync(engine, f.opts); } finally { await engine.executeRaw("DELETE FROM config WHERE key='sync.holds'"); }+ expect(blocked).toMatchObject({ status: 'blocked_by_failures', managedWrite: { write_error: 'source_changed', reason: 'pinned_git_worktree_conflict' } });+ expect(pinnedWorktreeConflict({ state: 'conflict', error_code: 'source_changed', error_message: 'Newer working-tree bytes and the current page disagree with this pinned Git import.' })).toBe(true);+ const before = await cursorOf(engine, f.id);+ expect(before).toMatchObject({ index: 1, total: 3 }); expect(before.done).toBeFalsy();+ // Upgraded: the operator's loop reruns with --retry-failed. The cursor converts in place (same run), nothing is rediscovered.+ const discoveries = countDiscoveries(engine, f.id);+ let converted;+ try { converted = await performManagedSync(engine, { ...f.opts, retryFailed: true }); }+ finally { discoveries.restore(); }+ expect(discoveries.count()).toBe(0);+ expect(converted).toMatchObject({ status: 'synced', held_count: 1, held: [{ path: 'b.md', code: 'worktree_dirty' }], converted_from_failed: [blocked.managedWrite!.write_request.request_id] });+ expect((await cursorOf(engine, f.id))?.run_id).toBe(before.run_id);+ expect((await engine.getPage('c', { sourceId: f.id }))?.compiled_truth).toContain('c two.');+ expect(readFileSync(join(f.root, 'b.md'), 'utf8')).toBe(edit);+ expect(await readManagedSyncFailures(engine, [f.id])).toEqual([]);+ // Held again and again with the same code: the attempt count reaches the needs_human threshold.+ const [source] = await engine.executeRaw<{ incarnation: string }>('SELECT incarnation::text AS incarnation FROM sources WHERE id=$1', [f.id]);+ for (let round = 2; round <= HOLD_ATTEMPTS_NEEDS_HUMAN; round++) {+ const { requestGitHoldRetry } = await import('../src/core/persistence/sync-holds.ts');+ await requestGitHoldRetry(engine, f.id, source.incarnation, ['b.md']);+ const again = await performManagedSync(engine, f.opts);+ expect(again.held?.map(hold => hold.code)).toEqual(['worktree_dirty']);+ expect((await readGitHold(engine, f.id, source.incarnation, 'b.md'))?.meta.attempts).toBe(round);+ }+ expect((await readGitSourceHolds(engine, { sourceIds: [f.id] }))[0]?.holds.map(hold => hold.path)).toEqual(['b.md']);+ }+}), 120_000);++test('a dropped database connection mid-run leaves no failure-ledger row, and the relaunch resumes the same run at the stored index without discovery', async () => withEnv({ GBRAIN_HOME: home, GBRAIN_SYNC_FAILURES_DIR: home }, async () => {+ for (const engine of engines) {+ const f = await fixture(engine, { 'a.md': note('Alpha one.'), 'b.md': note('Beta one.'), 'c.md': note('Gamma one.'), 'd.md': note('Delta one.') });+ expect((await performManagedSync(engine, f.opts)).status).toBe('first_sync');+ for (const name of ['a', 'b', 'c', 'd']) writeFileSync(join(f.root, `${name}.md`), note(`${name} two.`));+ const pin = commit(f.root, 'version two');+ // The pooler drops the socket after the second page commits: the pass throws the raw socket error.+ const executeRaw = engine.executeRaw;+ let armed = false;+ engine.executeRaw = async function (this: BrainEngine, sql: string, params?: unknown[]) {+ if (armed && sql.includes("NOT(COALESCE(intent->>'kind','') LIKE 'managed_sync_%')")) { armed = false; throw Object.assign(new Error('write ECONNABORTED db.example.invalid:5432'), { code: 'ECONNABORTED' }); }+ return executeRaw.call(this, sql, params);+ } as BrainEngine['executeRaw'];+ let died: unknown;+ try {+ await performManagedSync(engine, { ...f.opts, onProgress: p => { if (p.phase === 'managed_sync.page_committed' && p.bankedFiles === 2) armed = true; } }).catch(error => { died = error; });+ } finally { engine.executeRaw = executeRaw; await disposePersistenceConsumer(engine); }+ expect(String((died as Error)?.message)).toContain('ECONNABORTED');+ // No failure-ledger row (the read view still reports the unfinished cursor as `sync_incomplete`, which is not a recorded failure).+ expect(await engine.executeRaw("SELECT 1 FROM op_checkpoints WHERE op='managed-sync-failure' AND completed_keys::text LIKE $1", [`%${f.id}%`])).toEqual([]);+ expect((await readManagedSyncFailures(engine, [f.id])).map(row => row.code)).toEqual(['sync_incomplete']);+ const stored = await cursorOf(engine, f.id);+ expect(stored).toMatchObject({ target: pin }); expect(stored.done).toBeFalsy();+ expect(stored.index).toBeGreaterThanOrEqual(2);+ // With or without --retry-failed (the operator's loop passes it), the relaunch resumes the stored run: no rediscovery.+ for (const retryFailed of [true, false]) {+ const discoveries = countDiscoveries(engine, f.id);+ try {+ const resumed = await performManagedSync(engine, { ...f.opts, retryFailed });+ expect(resumed.status).toBe(retryFailed ? 'synced' : 'up_to_date');+ if (retryFailed) { expect(resumed).toMatchObject({ runId: stored.run_id, toCommit: pin }); expect(discoveries.count()).toBe(0); }+ } finally { discoveries.restore(); }+ }+ expect((await engine.getPage('d', { sourceId: f.id }))?.compiled_truth).toContain('d two.');+ }+}), 120_000);++test('when HEAD moves past the pinned target during the run, the drain takes exactly one more pass and ends at HEAD', async () => withEnv({ GBRAIN_HOME: home }, async () => {+ const { drainManagedSync } = await import('../src/core/persistence/sync-drain.ts');+ for (const engine of engines) {+ const f = await fixture(engine, { 'a.md': note('Alpha one.'), 'b.md': note('Beta one.'), 'c.md': note('Gamma one.') });+ expect((await drainManagedSync(engine, f.opts, false)).drain).toMatchObject({ outcome: 'synced', written: 3 });+ for (const name of ['a', 'b', 'c']) writeFileSync(join(f.root, `${name}.md`), note(`${name} two.`));+ const pin = commit(f.root, 'version two');+ // Another agent commits d.md and a third version of c.md while the run drains its pinned manifest.+ let moved: string | null = null;+ const result = await drainManagedSync(engine, { ...f.opts, onProgress: p => {+ if (p.phase === 'managed_sync.page_committed' && p.bankedFiles === 1 && !moved) {+ writeFileSync(join(f.root, 'd.md'), note('Delta, committed during the run.')); writeFileSync(join(f.root, 'c.md'), note('c three, committed during the run.'));+ moved = commit(f.root, 'commits during the run');+ } } }, false);+ expect(moved).not.toBeNull();+ expect(result).toMatchObject({ status: 'synced', toCommit: moved, drain: { outcome: 'synced', extra_pass: { from: pin, to: moved } } });+ expect(result.drain!.passes).toBeGreaterThanOrEqual(2);+ expect((await engine.getPage('d', { sourceId: f.id }))?.compiled_truth).toContain('committed during the run');+ expect((await engine.getPage('c', { sourceId: f.id }))?.compiled_truth).toContain('c three');+ expect((await engine.executeRaw<{ last_commit: string }>('SELECT last_commit FROM sources WHERE id=$1', [f.id]))[0].last_commit).toBe(moved!);+ // Quiet checkout: no extra pass.+ const quiet = await drainManagedSync(engine, f.opts, false);+ expect(quiet.status).toBe('up_to_date'); expect(quiet.drain?.extra_pass).toBeUndefined();+ }+}), 120_000);diff --git a/test/persistence-managed-sync.test.ts b/test/persistence-managed-sync.test.tsindex 3bfc81137f..76869504a2 100644--- a/test/persistence-managed-sync.test.ts+++ b/test/persistence-managed-sync.test.ts@@ -103,13 +103,17 @@ test('a pinned import that trails the current page and its working-tree bytes isexpect(readFileSync(path, 'utf8')).toBe(current);expect((await engine.executeRaw<{ last_commit: string }>('SELECT last_commit FROM sources WHERE id=$1', [f.id]))[0].last_commit).toBe(head);expect(loadSyncFailures().filter(row => row.source_id === f.id)).toHaveLength(0);- // Working-tree bytes that are neither the pinned commit nor the page are still protected.+ // Working-tree bytes that are neither the pinned commit nor the page are still protected: #6340 holds the file+ // (`worktree_dirty`) and the run finishes instead of blocking; nothing overwrites the local edit.const foreign = '---\ntitle: Example note\n---\nA local edit that nothing imported.\n';- writeFileSync(path, pinned.replace('older', 'still older')); commit(f.root, 'another trailing commit'); writeFileSync(path, foreign);- const blocked = await performManagedSync(engine, { sourceId: f.id, noPull: true });- expect(blocked).toMatchObject({ status: 'blocked_by_failures', managedWrite: { write_error: 'source_changed', reason: 'pinned_git_worktree_conflict' } });+ writeFileSync(path, pinned.replace('older', 'still older')); const trailing = commit(f.root, 'another trailing commit'); writeFileSync(path, foreign);+ const held = await performManagedSync(engine, { sourceId: f.id, noPull: true });+ expect(held).toMatchObject({ status: 'synced', toCommit: trailing, held_count: 1, held: [{ path: 'notes/example.md', code: 'worktree_dirty' }] });+ expect(held.managedWrite).toBeUndefined();+ expect(JSON.stringify(held)).not.toContain('local edit that nothing imported');expect(readFileSync(path, 'utf8')).toBe(foreign);expect((await engine.getPage('notes/example', { sourceId: f.id }))?.compiled_truth).toContain('current observation');+ expect(loadSyncFailures().filter(row => row.source_id === f.id)).toHaveLength(0);rmSync(syncFailuresPath(), { force: true });}}),120_000);@@ -215,9 +219,12 @@ test('interrupted cursor resumes its pinned target before a newer HEAD and neverexpect(first).toMatchObject({status:'partial',filesImported:1});expect((await engine.executeRaw<{last_commit:string|null}>('SELECT last_commit FROM sources WHERE id=$1',[f.id]))[0].last_commit).toBeNull();writeFileSync(join(f.root,'b.md'),'Newer second observation about engineering.\n'); const secondHead=commit(f.root,'new content after interruption');+ // The checkpoint stays at the pin; #6340 imports b.md as HEAD commits it (a commit past the pin is not a local edit), and+ // the pin..HEAD diff then re-imports the same bytes as a no-op.const second = await performManagedSync(engine,{sourceId:f.id,noPull:true}); expect(second.toCommit).toBe(f.head); expect(second.status).toBe('first_sync');- expect((await engine.getPage('b',{sourceId:f.id}))?.compiled_truth).toContain('Original second');- expect((await performManagedSync(engine,{sourceId:f.id,noPull:true})).toCommit).toBe(secondHead);+ expect((await engine.getPage('b',{sourceId:f.id}))?.compiled_truth).toContain('Newer second');+ const third = await performManagedSync(engine,{sourceId:f.id,noPull:true});+ expect(third.toCommit).toBe(secondHead); expect(third).toMatchObject({ status: 'synced', modified: 0, waived: { imports: 1, deletes: 0 } });expect((await engine.getPage('b',{sourceId:f.id}))?.compiled_truth).toContain('Newer second');}}),120_000);@@ -237,7 +244,7 @@ test('attached working-tree changes require opt-in and delete retains exact phys}}),120_000);-test('repeated slices reuse one manifest and still reject an intervening page identity change', async () => withEnv({ GBRAIN_HOME: home }, async () => {+test('repeated slices reuse one manifest and hold an intervening page identity change instead of rejecting the run', async () => withEnv({ GBRAIN_HOME: home }, async () => {for (const engine of engines) {const f = await fixture(engine, {'a.md': 'First source observation for a durable sliced import.\n',@@ -264,7 +271,9 @@ test('repeated slices reuse one manifest and still reject an intervening page idawait engine.transaction(tx => withCoordinatedWrite(tx, [f.id], () => tx.putPage('c', {type: 'note', title: 'c', compiled_truth: 'A newer accepted page between sync slices.', timeline: '', frontmatter: {}, content_hash: 'newer',}, { sourceId: f.id }), TEST_WRITE_ATTRIBUTION));- await expect(performManagedSync(engine, options, slice)).rejects.toMatchObject({ code: 'revision_conflict' });+ // #6340: the page that moved under the manifest is held (`concurrent_write`), the run finishes, and the database version stays.+ const held = await performManagedSync(engine, options, slice);+ expect(held).toMatchObject({ status: 'partial', reason: 'writer_yield', held_count: 1, held: [{ path: 'c.md', code: 'concurrent_write' }] });expect(manifestReads).toBe(1);expect(await engine.executeRaw('SELECT completed_keys FROM op_checkpoints WHERE op=$1 AND fingerprint=$2',['managed-sync-manifest', manifest.fingerprint])).toEqual([{ completed_keys: manifest.completed_keys }]);@@ -272,6 +281,9 @@ test('repeated slices reuse one manifest and still reject an intervening page idexpect(await engine.executeRaw('SELECT slug,state FROM persistence_requests WHERE source_id=$1 ORDER BY sequence', [f.id])).toEqual([{ slug: 'a', state: 'committed' }, { slug: 'b', state: 'committed' }]);expect((await engine.executeRaw<{ last_commit: string | null }>('SELECT last_commit FROM sources WHERE id=$1', [f.id]))[0].last_commit).toBeNull();+ expect(await performManagedSync(engine, options, slice)).toMatchObject({ status: 'first_sync', filesImported: 3, held_count: 1 });+ expect((await engine.getPage('c', { sourceId: f.id }))?.compiled_truth).toBe('A newer accepted page between sync slices.');+ expect(loadSyncFailures().filter(row => row.source_id === f.id)).toHaveLength(0);} finally { await disposePersistenceConsumer(engine); engine.executeRaw = executeRaw; }}}),120_000);@@ -325,9 +337,12 @@ test('a write between batches cannot be overwritten by an older enumerated Git p}, TEST_WRITE_ATTRIBUTION)); }}});expect(first.status).toBe('partial'); await changed;- await expect(performManagedSync(engine,{sourceId:f.id,noPull:true})).rejects.toMatchObject({code:'revision_conflict'});+ // #6340: the overtaken page is held, never overwritten, and the run finishes with the hold listed.+ const resumed = await performManagedSync(engine,{sourceId:f.id,noPull:true});+ expect(resumed).toMatchObject({ status: 'first_sync', held_count: 1, held: [{ path: 'b.md', code: 'concurrent_write' }] });expect((await engine.getPage('b',{sourceId:f.id}))?.compiled_truth).toBe('A concurrently accepted newer observation.');- expect((await engine.executeRaw<{last_commit:string|null}>('SELECT last_commit FROM sources WHERE id=$1',[f.id]))[0].last_commit).toBeNull();+ expect((await engine.executeRaw<{last_commit:string|null}>('SELECT last_commit FROM sources WHERE id=$1',[f.id]))[0].last_commit).toBe(f.head);+ expect(loadSyncFailures().filter(row => row.source_id === f.id)).toHaveLength(0);}}),120_000);@@ -379,6 +394,9 @@ test.each([false, true])('raw bytes changing after preparation conflict withouttest.each([false, true])('managed terminal receipts survive a missing ledger and corrected retry uses a new ID (CRLF=%s)', async crlf =>withEnv({ GBRAIN_HOME: home, GBRAIN_SYNC_FAILURES_DIR: home }, async () => {for (const engine of engines) {+ // #6340 holds a pinned-worktree conflict by default; `sync.holds=fail` keeps the blocking receipt this test is about.+ await engine.setConfig('sync.holds', 'fail');+ try {const f = await fixture(engine, { 'notes/example.md': 'An original observation about the example system.\n' });await performManagedSync(engine, { sourceId: f.id, noPull: true });const pinned = 'A newly committed observation about the example system.\n';@@ -447,6 +465,7 @@ test.each([false, true])('managed terminal receipts survive a missing ledger andexpect(requests.at(-1)?.state).toBe('committed');expect(requests.at(-1)?.request_id).not.toBe(id);expect((await engine.executeRaw<{ last_commit: string }>('SELECT last_commit FROM sources WHERE id=$1', [f.id]))[0].last_commit).toBe(target);+ } finally { await engine.executeRaw("DELETE FROM config WHERE key='sync.holds'"); }}}), 120_000);@@ -825,18 +844,19 @@ test('a run of no-op deletes is waived in one transaction, and GBRAIN_SYNC_WAIVE}}), 120_000);-test('a page restored in the middle of a waiver run ends the run there: earlier entries are waived, it is admitted, and nothing after it is passed', async () => withEnv({ GBRAIN_HOME: home, GBRAIN_SYNC_FAILURES_DIR: home }, async () => {+test('a page restored in the middle of a waiver run ends the run there: earlier entries are waived, it is admitted and held, and the rest is passed in a new run', async () => withEnv({ GBRAIN_HOME: home, GBRAIN_SYNC_FAILURES_DIR: home }, async () => {for (const engine of engines) {const f = await deletedFixture(engine, manyNotes(8), manySlugs(8));// n06 is frozen (and screened) after n02 was screened and before the run's waiver transaction.const proxy = onScreen(engine, 'n06', () => engine.transaction(tx => withCoordinatedWrite(tx, [f.id], async () => { await tx.restorePage('n02', { sourceId: f.id }); }, TEST_WRITE_ATTRIBUTION)), 1);try {const result = await performManagedSync(proxy, { sourceId: f.id, ...WAIVER_OPTS });- expect(result.waived).toEqual({ imports: 0, deletes: 2 });+ // #6340: the restored page's delete conflicts and is held (`concurrent_write`, the page stays); the run no longer stops there.+ expect(result).toMatchObject({ status: 'synced', waived: { imports: 0, deletes: 7 }, held_count: 1, held: [{ path: 'n02.md', code: 'concurrent_write' }] });expect((await deleteRequests(engine, f.id)).map(row => row.slug)).toEqual(['n02']);expect(await engine.getPage('n02', { sourceId: f.id })).not.toBeNull();- const [cursor] = await engine.executeRaw<{ index: number }>("SELECT (completed_keys->0->>'index')::int AS index FROM op_checkpoints WHERE op='managed-sync' AND completed_keys->0->>'sourceId'=$1", [f.id]);- expect(cursor!.index).toBe(2);+ const [cursor] = await engine.executeRaw<{ index: number; done: boolean }>("SELECT (completed_keys->0->>'index')::int AS index,(completed_keys->0->>'done')::boolean AS done FROM op_checkpoints WHERE op='managed-sync' AND completed_keys->0->>'sourceId'=$1", [f.id]);+ expect(cursor).toMatchObject({ index: 8, done: true });} finally { await disposePersistenceConsumer(proxy); rmSync(syncFailuresPath(), { force: true }); }}}), 120_000);diff --git a/test/sync-drain-connection.test.ts b/test/sync-drain-connection.test.tsnew file mode 100644index 0000000000..d65517d3ef--- /dev/null+++ b/test/sync-drain-connection.test.ts@@ -0,0 +1,107 @@+/**+ * #6340: a managed drain whose pass dies on a dropped database connection+ * (`write ECONNABORTED host:port`, the session-mode pooler closing the socket+ * mid-statement) resumes instead of exiting. Before this change the drain's+ * transient classifier did not know `ECONNABORTED` (only `ECONNRESET`), so the+ * error escaped `runDrain`, the CLI exited 1 and the operator relaunched by+ * hand; four such deaths cost one brain fifty minutes in an afternoon. Now the+ * drain reconnects, waits 5 / 15 / 45 s and re-enters the pass at the stored+ * cursor; three drops in a row with no page committed between them end the+ * drain `blocked` / `connection_lost` with the same resume command as `next`.+ * `CONNECTION_DESTROYED` / `CONNECTION_CLOSED` stay out of the retry (#6329:+ * this process's own settle of a cancelled statement, the stall path).+ */+import { describe, expect, spyOn, test } from 'bun:test';+import { CONNECTION_RETRY_MS, CONNECTION_STRIKES, drainJsonFields, drainNext, formatDrainSummary, isConnectionDrop, runDrain } from '../src/core/persistence/sync-drain.ts';+import { isRetryableConnError } from '../src/core/retry-matcher.ts';+import { ERROR_CATALOGUE } from '../src/core/error-catalogue.ts';+import { CODES } from '../src/core/error-registry.ts';+import type { SyncResult } from '../src/commands/sync.ts';++const base: SyncResult = { status: 'synced', fromCommit: 'a', toCommit: 'b', added: 0, modified: 0, deleted: 0, renamed: 0, chunksCreated: 0, embedded: 0, pagesAffected: [] };+const RESUME = 'gbrain sync --source s --no-pull --retry-failed';+const dropped = (errno = 'ECONNABORTED') => Object.assign(new Error(`write ${errno} db.example.invalid:5432`), { code: errno });++function captureStderr(): { lines: string[]; restore(): void } {+ const lines: string[] = [];+ const spy = spyOn(console, 'error').mockImplementation((...args: unknown[]) => { lines.push(args.map(String).join(' ')); });+ return { lines, restore: () => spy.mockRestore() };+}++describe('classifying a dropped connection', () => {+ test('the socket errnos a pooler drop surfaces are retryable connection errors; the settle codes and page faults are not', () => {+ for (const errno of ['ECONNABORTED', 'ECONNRESET', 'ETIMEDOUT', 'EPIPE']) {+ expect(isRetryableConnError(dropped(errno))).toBe(true);+ expect(isConnectionDrop(dropped(errno))).toBe(true);+ expect(isConnectionDrop(new Error(`write ${errno} undefined:undefined`))).toBe(true);+ }+ expect(isConnectionDrop(Object.assign(new Error('write CONNECTION_DESTROYED'), { code: 'CONNECTION_DESTROYED' }))).toBe(false);+ expect(isConnectionDrop(Object.assign(new Error('write CONNECTION_CLOSED host:5432'), { code: 'CONNECTION_CLOSED' }))).toBe(false);+ expect(isConnectionDrop(Object.assign(new Error('A page changed after this sync cursor was enumerated.'), { code: 'revision_conflict' }))).toBe(false);+ expect(isConnectionDrop(Object.assign(new Error('canceling statement due to statement timeout'), { code: '57014' }))).toBe(false);+ });++ test('the schedule is 5, 15 and 45 seconds and the strike count matches it', () => {+ expect([...CONNECTION_RETRY_MS]).toEqual([5_000, 15_000, 45_000]);+ expect(CONNECTION_STRIKES).toBe(3);+ });+});++describe('runDrain over a dropping connection', () => {+ test('a drop is reconnected and retried; a pass that then commits resets the strikes and the drain finishes synced', async () => {+ let passes = 0;+ const reconnects: unknown[] = [];+ const err = captureStderr();+ try {+ const result = await runDrain({ announce: true, progressMs: 1, backoffMs: 2, reconnect: async error => { reconnects.push(error); },+ pass: async (_signal, onProgress) => {+ passes++;+ // Drops on passes 1 and 2, a page on pass 3, drops on 4 and 5 (the counter restarted at the commit), done on 6.+ if (passes === 1 || passes === 2 || passes === 4 || passes === 5) throw dropped(passes === 4 ? 'ETIMEDOUT' : 'ECONNABORTED');+ if (passes === 3) { onProgress({ phase: 'managed_sync.page_committed', bankedFiles: 1, total: 2 }); return { ...base, status: 'partial', reason: 'writer_yield', managedCursor: { index: 1, total: 2 } }; }+ onProgress({ phase: 'managed_sync.page_committed', bankedFiles: 2, total: 2 });+ return { ...base, managedCursor: { index: 2, total: 2 } };+ } });+ expect(result.drain).toMatchObject({ outcome: 'synced', passes: 6, written: 2 });+ expect(result.drain!.stop_reason).toBeUndefined();+ expect(reconnects).toHaveLength(4);+ expect(reconnects.every(error => isConnectionDrop(error))).toBe(true);+ const drops = err.lines.filter(line => line.includes('database connection dropped'));+ expect(drops).toHaveLength(4);+ expect(drops[0]).toMatch(/^\[sync\] 0\/\? processed · database connection dropped \(write ECONNABORTED db\.example\.invalid:5432\); reconnecting and retrying in \d+s \(1 of 3\)$/);+ expect(drops[2]).toContain('(1 of 3)');+ } finally { err.restore(); }+ });++ test('three drops with no page between them end the drain blocked / connection_lost with the resume command as next, loopable', async () => {+ let passes = 0;+ const result = await runDrain({ backoffMs: 2, pass: async () => { passes++; throw dropped(); } });+ expect(passes).toBe(3);+ expect(result.drain).toMatchObject({ outcome: 'blocked', stop_reason: 'connection_lost', connection: { drops: 3, last_error: 'write ECONNABORTED db.example.invalid:5432' } });+ const next = drainNext(result, RESUME, 's')!;+ expect(next).toMatchObject({ command: RESUME, safe_to_loop: true, retry_after_ms: 60_000, code: 'connection_lost', docs: ERROR_CATALOGUE.sync_drain_connection_lost.docs });+ expect(next.why).toContain('3 times in a row');+ expect(next.why).toContain('without re-freezing');+ expect(ERROR_CATALOGUE.sync_drain_connection_lost).toEqual({ code: 'connection_lost', docs: 'docs/guides/sync-unblock-runbook.md#connection' });+ expect(CODES.connection_lost).toMatchObject({ class: 'retryable', retryable: true });+ expect(drainJsonFields(result, RESUME, 's')).toMatchObject({ outcome: 'blocked', next: { command: RESUME, safe_to_loop: true } });+ const summary = formatDrainSummary(result, RESUME, 's').join('\n');+ expect(summary).toContain('Database connection dropped 3 times in a row');+ expect(summary).toContain(`Next: ${RESUME} (safe to rerun in a loop)`);+ });++ test('a connection URL in the error text never reaches the report, and a drop after a successful pass keeps that pass\'s counts', async () => {+ let passes = 0;+ const leaky = Object.assign(new Error('write ECONNABORTED postgresql://user:[email protected]:5432/brain'), { code: 'ECONNABORTED' });+ const pending: SyncResult = { ...base, status: 'partial', reason: 'writer_yield', added: 4, managedCursor: { index: 4, total: 9 } };+ const result = await runDrain({ backoffMs: 2, pass: async () => { if (++passes === 1) return pending; throw leaky; } });+ expect(result).toMatchObject({ added: 4, drain: { outcome: 'blocked', stop_reason: 'connection_lost', remaining: 5 } });+ expect(JSON.stringify(result)).not.toContain('secret');+ expect(result.drain!.connection!.last_error).toBe('write ECONNABORTED <url>');+ });++ test('a settle-discard code is not a drop: the drain ends with the error as before', async () => {+ const destroyed = Object.assign(new Error('write CONNECTION_DESTROYED'), { code: 'CONNECTION_DESTROYED' });+ await expect(runDrain({ backoffMs: 2, pass: async () => { throw destroyed; } })).rejects.toBe(destroyed);+ });+});