Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
sync: hold preparation_stalled members and narrow the hold gate (#6278 B1)
garrytan5aa452351e23
diff --git a/src/commands/doctor/checks/git-holds.ts b/src/commands/doctor/checks/git-holds.tsindex b8e95e98aa..1a79b69cc6 100644--- a/src/commands/doctor/checks/git-holds.ts+++ b/src/commands/doctor/checks/git-holds.ts@@ -35,6 +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 } : {}),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('; '),@@ -47,24 +48,30 @@ export async function gitHeldFilesCheck(engine: BrainEngine, sourceIds?: string[const escalated = sources.filter(source => source.escalated);const single = sources.length === 1 ? sources[0]! : undefined;const fenceOnly = sources.every(source => source.fences === source.held);+ // #6278: stalled holds are the writer's, not the files': the fix is writer status, never a file repair.+ const stalledOnly = sources.every(source => source.stalled === source.held);+ const stalled = sources.reduce((sum, source) => sum + (source.stalled ?? 0), 0);const lines = sources.map(source => `${source.source_id}: ${source.held} held (${source.stale} page(s) keep an older revision, ${source.missing} file(s) have no page), `+ `first: ${source.first.map(hold => `${hold.path} [${hold.code}${hold.reason ? `/${hold.reason}` : ''}]`).join(', ')}`);return {name: 'git_held_files', status: escalated.length ? 'fail' : 'warn', details,message: `${held} file(s) in Git sources are held and not imported; the rest of each sync continues. ${lines.join('; ')}. `- + (escalated.length ? `Escalated: ${escalated.map(source => source.source_id).join(', ')} hold more than ${policy.escalateCount} files (sync.hold_escalate_count), so a generator or an upgrade is likely writing or reading them wrong; fix the cause first. ` : '')+ + (escalated.length ? `Escalated: ${escalated.map(source => source.source_id).join(', ')} hold more than ${policy.escalateCount} files (sync.hold_escalate_count), so ${stalled * 2 > held+ ? 'the write owner (not the files) is the likely cause; inspect it with writer status' : 'a generator or an upgrade is likely writing or reading them wrong; fix the cause'} first. ` : '')+ 'A page whose newer file is held is read-only for put_page until the file is repaired, so do not retry a refused write. '+ `Inspect with ${sources.map(source => source.status).join('; ')}; `- + (sources.some(source => source.fences) ? `then ${sources.map(source => `${source.source_id}: ${source.next}`).join('; ')}.` : `preview the fix with ${sources.map(source => source.repair).join('; ')}.`),+ + (sources.some(source => source.fences || source.stalled) ? `then ${sources.map(source => `${source.source_id}: ${source.next}`).join('; ')}.` : `preview the fix with ${sources.map(source => source.repair).join('; ')}.`),fix: single? agentFix(single.argv, fenceOnly ? `Previews the fence repair of each held file of ${single.source_id} (read-only, no model call): ${single.next}.`- : 'Previews the minimal line fix for each held file (or names the line to fix by hand) and prints the hash-bound apply command; it writes nothing.',- 'git_held_files', { docs: fenceOnly ? 'docs/guides/repair.md#fences' : 'docs/guides/repair.md#held-files' })- : agentFix(fenceOnly ? ['gbrain', 'repair', 'fences'] : ['gbrain', 'repair', 'frontmatter'],+ : stalledOnly ? `Shows what the write owner of ${single.source_id} was stuck on (read-only); the held files are fine. ${single.next}.`+ : 'Previews the minimal line fix for each held file (or names the line to fix by hand) and prints the hash-bound apply command; it writes nothing.',+ 'git_held_files', { docs: fenceOnly ? 'docs/guides/repair.md#fences' : stalledOnly ? 'docs/guides/write-refusals.md#preparation_stalled' : 'docs/guides/repair.md#held-files' })+ : agentFix(fenceOnly ? ['gbrain', 'repair', 'fences'] : stalledOnly ? ['gbrain', 'sources', 'writer', 'status', '--json'] : ['gbrain', 'repair', 'frontmatter'],fenceOnly ? `Previews the fence repair of every held file (read-only, no model call) with each one's planned repair or exact edit, and prints the apply command with --expect <hash>. ${fenceAutoSentence(auto)}`- : 'Previews the minimal line fix for each held file (or names the line to fix by hand) and prints the hash-bound apply command; it writes nothing. '- + `Fence holds are previewed by gbrain repair fences instead. ${fenceAutoSentence(auto)}`,- 'git_held_files', { docs: fenceOnly ? 'docs/guides/repair.md#fences' : 'docs/guides/repair.md#held-files' }),+ : stalledOnly ? 'Shows every source\'s write owner and what it was stuck on (read-only); the held files are fine. Fix what it names or upgrade gbrain, then gbrain sources retry-held <id> and the same sync per source.'+ : 'Previews the minimal line fix for each held file (or names the line to fix by hand) and prints the hash-bound apply command; it writes nothing. '+ + `Fence holds are previewed by gbrain repair fences instead${stalled ? ', and preparation-stalled holds need no file repair (see each source\'s next step)' : ''}. ${fenceAutoSentence(auto)}`,+ 'git_held_files', { docs: fenceOnly ? 'docs/guides/repair.md#fences' : stalledOnly ? 'docs/guides/write-refusals.md#preparation_stalled' : 'docs/guides/repair.md#held-files' }),};} catch (error) {return { name: 'git_held_files', status: 'warn', fix_unavailable_reason: 'check_errored',diff --git a/src/commands/sources-retry-held.ts b/src/commands/sources-retry-held.tsindex 7e9a4c96c6..9cfbe3ee07 100644--- a/src/commands/sources-retry-held.ts+++ b/src/commands/sources-retry-held.ts@@ -20,7 +20,8 @@ import type { Action } from '../core/agent-output.ts';import { OperationError } from '../core/ops/contract.ts';import { managedBrain, readAllSourceHolds, readHoldRetryKeys, requestHoldRetry, writeHeldRetryPointer } from '../core/connectors/item-holds-store.ts';import { isConnectorSourceKind } from '../core/persistence/connector-identity.ts';-import { fenceAutoRepairFor, holdRepairSteps, readGitHoldRetryPaths, readGitSourceHolds, requestGitHoldRetry } from '../core/persistence/sync-holds.ts';+import { fenceAutoRepairFor, holdRepairSteps, readGitHoldRetryPaths, readGitSourceHolds, requestGitHoldRetry, type GitHoldRecord } from '../core/persistence/sync-holds.ts';+import { readManagedSyncBacklog } from '../core/persistence/sync-drain.ts';import type { FenceAutoRepair } from '../core/fence-repair/hold-fix.ts';export interface RetryHeldReceipt {@@ -50,10 +51,24 @@ async function scheduleConnectorItems(engine: BrainEngine, sourceId: string, increturn { items: held.map(record => ({ key: record.key, code: record.code, already: already.has(record.key) })), sync };}+/**+ * #6278: the follow-up sync keeps the run's processing options (`--no-embed`+ * and friends) instead of starting a second cursor: the unfinished managed+ * cursor's options when one exists, else the arguments a `preparation_stalled`+ * hold recorded, else the plain command.+ */+async function gitFollowUpSync(engine: BrainEngine, sourceId: string, held: ReadonlyArray<Pick<GitHoldRecord, 'code' | 'meta'>>): Promise<string[]> {+ if (!await managedBrain(engine)) return ['gbrain', 'sync', '--source', sourceId];+ const [backlog] = await readManagedSyncBacklog(engine, [sourceId]).catch(() => []);+ if (backlog) return ['gbrain', 'sync', ...backlog.resume_args];+ const stalled = held.find(record => record.code === 'preparation_stalled' && record.meta.stall?.sync_argv?.length);+ return ['gbrain', 'sync', ...(stalled?.meta.stall?.sync_argv ?? ['--source', sourceId, '--no-pull'])];+}+async function scheduleGitFiles(engine: BrainEngine, sourceId: string, incarnation: string, dryRun: boolean): Promise<Scheduled> {const held = (await readGitSourceHolds(engine, { sourceIds: [sourceId] }))[0]?.holds ?? [];// Managed sync refuses to pull; the plain command is the classic one.- const sync = ['gbrain', 'sync', '--source', sourceId, ...(await managedBrain(engine) ? ['--no-pull'] : [])];+ const sync = await gitFollowUpSync(engine, sourceId, held);if (!held.length) return { items: [], sync };if (!dryRun) await requestGitHoldRetry(engine, sourceId, incarnation, held.map(record => record.path));const already = new Set(dryRun ? await readGitHoldRetryPaths(engine, sourceId, incarnation) : []);@@ -73,8 +88,9 @@ function gitNextStep(sourceId: string, dryRun: boolean, scheduled: Scheduled): {why: `Schedules a re-screen of ${count} held file(s) on the next sync of ${sourceId}; nothing runs now.` } };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;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, concurrent }, scheduled.fenceAuto).text}.`,+ + `A file that still refuses stays held; ${holdRepairSteps(sourceId, { fences, others: count - fences - concurrent - stalled, concurrent, stalled }, 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.` } };}@@ -105,7 +121,8 @@ export async function runRetryHeld(engine: BrainEngine, args: string[]): Promise+ 'Re-attempt every held connector item of a Google or GitHub source on its next sync, or re-screen every\n'+ 'held file of a Git source on its next sync (most held files re-screen by themselves when they change).\n'+ 'Nothing runs now. A file that still refuses stays held: preview frontmatter holds with\n'- + "'gbrain repair frontmatter --source <id>' and fence holds (invalid_fence) with 'gbrain repair fences --source <id>'.\n"+ + "'gbrain repair frontmatter --source <id>' and fence holds (invalid_fence) with 'gbrain repair fences --source <id>';\n"+ + "a preparation_stalled hold needs no file repair: inspect 'gbrain sources writer status --source <id> --json', then rerun the sync it prints.\n"+ ' --dry-run show what would be scheduled; change nothing\n --json print the receipt as JSON');return;}diff --git a/src/core/error-registry.ts b/src/core/error-registry.tsindex 7005abaf87..612152b162 100644--- a/src/core/error-registry.ts+++ b/src/core/error-registry.ts@@ -266,6 +266,12 @@ export const CODES = {plan_output_failed: { class: 'server', summary: "Writing the plan output failed." },plan_stale: { class: 'caller', summary: "The saved plan has no valid repository identity." },port_in_use: { class: 'retryable', summary: "Google connect credential error: port in use.", docs: 'docs/guides/google-connect.md#troubleshooting' },+ // #6278 (Lane B placeholder; Lane A owns the final entry): a write whose preparation never settled within its attempts.+ preparation_stalled: { class: 'server', retryable: false, actor: 'agent', summary: "The write's preparation did not finish within its attempts, so the owner gave it up; a managed sync holds the file and keeps going.",+ why: "A preparation that never settles would hold its worktree root forever; after the attempt limit the request is finished failed and a new sync admits a new request.",+ docs: 'docs/guides/write-refusals.md#preparation_stalled',+ suggestion: 'Inspect the write owner with gbrain sources writer status --source <id> --json (step and wait cause), fix what it names or upgrade gbrain, then gbrain sources retry-held <id> and the same sync.',+ fix: { argv: ['gbrain', 'sources', 'status', '{source_id}', '--json'], consent: [], actor: 'agent', why: 'Lists the held files of the source with the step each stalled on, read-only.', requires_exclusive: false } },preview_changed: { class: 'caller', summary: "The state changed since the approved preview." },profile_incompatible: { class: 'caller', summary: "The stored profile is incompatible with this operation." },projection_owner_resident: { class: 'host_only', summary: "A resident owner holds the projection." },diff --git a/src/core/persistence/held-reads.ts b/src/core/persistence/held-reads.tsindex 6fe74f7947..91c32aea5b 100644--- a/src/core/persistence/held-reads.ts+++ b/src/core/persistence/held-reads.ts@@ -33,7 +33,9 @@ export interface HeldPage { record: GitHoldRecord; revision: string | null; fenc* Held files of the sources in a read scope: new files with no page (`missing`) and pages whose newer file is held (`stale`);* `fences` (present only when some are) counts the #6188 `invalid_fence` holds among them, which route to `gbrain repair fences` instead of frontmatter repair.*/-export interface HeldCoverage { source_id: string; missing: number; stale: number; fences?: number; concurrent?: number }+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 }/** `get_page.file_held`. */export interface FileHeld {@@ -90,9 +92,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 }>(`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 }>(`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->>'fences')::int,0) AS fences, COALESCE((h.completed_keys->0->>'concurrent')::int,0) AS concurrent,+ COALESCE((h.completed_keys->0->>'stalled')::int,0) AS stalledFROM 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@@ -100,15 +103,16 @@ export function readHeldCoverage(engine: Exec, scope: { sourceId?: string; sourcreturn rows.map(row => {const 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);- return { source_id: row.source_id, missing: count - stale, stale, ...(fences ? { fences } : {}), ...(concurrent ? { concurrent } : {}) };+ 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 } : {}) };});});}/** 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;- return { fences, others: Math.max(0, source.missing + source.stale - fences - concurrent), ...(concurrent ? { concurrent } : {}) };+ 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 } : {}) };}/**@@ -123,12 +127,14 @@ export function hostOperatorFix(sources: ReadonlyArray<{ source_id: string; routconst frontmatter = sources.filter(source => !source.route || source.route.others > 0).map(source => `'gbrain repair frontmatter --source ${source.source_id}'`);const 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 first = sources[0]!;const parts = [...(frontmatter.length ? [`Please run ${frontmatter.join(', ')} on the brain host to preview the fixes, then apply them.`] : []),...(fences.length ? [`Some held files have a facts or takes table gbrain could not import. The brain host's maintenance run repairs most of these by itself when it is running; `+ `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.`] : []),];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(' ')}` };@@ -136,7 +142,8 @@ 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 } : { fences: 0, others: 1 };+ 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 };}/**@@ -148,8 +155,9 @@ export function recordRoute(record: Pick<GitHoldRecord, 'code'>): HoldRepairRoutexport function fileHeldField(held: HeldPage, remote: boolean): FileHeld {const { record } = held;const fence = record.code === 'invalid_fence';+ const stalled = record.code === 'preparation_stalled';const why = `The canonical file of this page is held (${record.code}${record.meta.reason ? `, ${record.meta.reason}` : ''}): sync cannot import its newer version, so this page shows its last good revision `- + `and is read-only for put_page until ${fence ? 'the file is repaired' : 'the brain host operator repairs the file'}.`;+ + `and is read-only for put_page until ${fence ? 'the file is repaired' : stalled ? 'the brain host operator fixes the write owner and re-screens the file' : 'the brain host operator repairs the file'}.`;const fix = !remote ? gitHoldFix(record, held.fenceAuto): fence ? fenceHoldRelay(record, held.fenceAuto, why) : hostOperatorFix([{ source_id: record.source_id, route: recordRoute(record) }], why);const location = fence ? fenceHoldLocation(record.meta, held.fenceAuto, remote) : undefined;diff --git a/src/core/persistence/sync-discovery.ts b/src/core/persistence/sync-discovery.tsindex 3191126fe9..f1d2ebbde4 100644--- a/src/core/persistence/sync-discovery.ts+++ b/src/core/persistence/sync-discovery.ts@@ -291,7 +291,8 @@ export async function discoverManagedSync(engine: BrainEngine, opts: SyncOpts, cpresent = bytes !== null || changed;if (!changed) changed = bytes === null || sha256(bytes.toString('utf8')) !== hold!.upstream_version;} else if (!changed) {- changed = !blob || (hold!.meta.blob_oid ? blob.oid !== hold!.meta.blob_oid : sha256(contents.get(blob.oid) ?? '') !== hold!.upstream_version);+ // #6278: a held deletion has no bytes to compare; the file reappearing is the change.+ changed = hold!.meta.deleted ? !!blob : !blob || (hold!.meta.blob_oid ? blob.oid !== hold!.meta.blob_oid : sha256(contents.get(blob.oid) ?? '') !== hold!.upstream_version);}if (!changed) continue;if (retry.has(path)) retryTaken.push(path);diff --git a/src/core/persistence/sync-drain.ts b/src/core/persistence/sync-drain.tsindex 9a1819a03e..dd5fc0bf6e 100644--- a/src/core/persistence/sync-drain.ts+++ b/src/core/persistence/sync-drain.ts@@ -20,6 +20,7 @@ import { getCode, isRetryableConnError, isStatementTimeoutError } from '../retryimport { currentRunDeadline, noteForwardProgress } from '../forward-progress.ts';import { serr } from '../console-prefix.ts';import { ERROR_CATALOGUE, type CatalogueName } from '../error-catalogue.ts';+import { managedSyncResumeArgs, syncResumeCommand } from '../sync-reconcile.ts';export type DrainOutcome = 'synced' | 'resumable' | 'blocked';/** Why a drain ended short of `synced`. Each value has an error-catalogue entry (DX-A4). */@@ -423,6 +424,8 @@ export interface ManagedSyncBacklog {eta_seconds: number | null;last_progress_at: string | null;resume_command: string;+ /** #6278: the arguments after `gbrain sync` that resume this cursor with its stored options. */+ resume_args: string[];}/**@@ -431,16 +434,15 @@ export interface ManagedSyncBacklog {*/export async function readManagedSyncBacklog(engine: BrainEngine, sourceIds?: string[]): Promise<ManagedSyncBacklog[]> {const rows = await engine.executeRaw<{ header: { sourceId: string; index: number; total: number; done?: boolean; progress?: { startedAt: number; startIndex: number; lastAt: number; lastIndex: number };- processingOptions?: { noEmbed?: boolean; noExtract?: boolean; noSchemaPack?: boolean } } }>(+ processingOptions?: { noEmbed?: boolean; noExtract?: boolean; noSchemaPack?: boolean }; syncOptions?: Parameters<typeof managedSyncResumeArgs>[0]['syncOptions'] } }>(`SELECT completed_keys->0 AS header FROM op_checkpoints WHERE op='managed-sync' AND COALESCE(completed_keys->0->>'done','false')<>'true'`);- const flags = { noEmbed: '--no-embed', noExtract: '--no-extract', noSchemaPack: '--no-schema-pack' } as const;return rows.map(({ header }) => header).filter(h => h?.sourceId && (!sourceIds || sourceIds.includes(h.sourceId))).map(h => {const remaining = Math.max(0, Number(h.total) - Number(h.index));const p = h.progress;const estimate = p ? drainEstimate(remaining, p.lastIndex - p.startIndex, p.lastAt - p.startedAt) : { rate_pages_per_min: null, eta_seconds: null };+ const args = managedSyncResumeArgs({ sourceId: h.sourceId, processingOptions: h.processingOptions, syncOptions: h.syncOptions });return { source_id: h.sourceId, index: Number(h.index), total: Number(h.total), remaining, ...estimate,- last_progress_at: p ? new Date(p.lastAt).toISOString() : null,- resume_command: `gbrain sync --source ${h.sourceId} --no-pull${(Object.keys(flags) as (keyof typeof flags)[]).filter(k => h.processingOptions?.[k]).map(k => ` ${flags[k]}`).join('')}` };+ last_progress_at: p ? new Date(p.lastAt).toISOString() : null, resume_command: syncResumeCommand(args), resume_args: args };});}diff --git a/src/core/persistence/sync-holds.ts b/src/core/persistence/sync-holds.tsindex 392b5103ec..2350068ce6 100644--- a/src/core/persistence/sync-holds.ts+++ b/src/core/persistence/sync-holds.ts@@ -35,6 +35,7 @@ import { FENCE_VERSION } from '../fence-repair/refusal.ts';import { fenceHoldFix, fenceHoldLocation, fencePreviewArgv, readFenceAutoRepair, type FenceAutoRepair, type FenceHoldLocation } from '../fence-repair/hold-fix.ts';import { STRUCTURED_WRITE_ADVICE, type FencesNormalized } from '../fence-repair/report.ts';import type { SyncRename } from './sync-discovery.ts';+import { VERSION } from '../../version.ts';export const GIT_HOLD_OP = 'sync-hold';export const GIT_HOLD_SUMMARY_OP = 'sync-hold-summary';@@ -53,7 +54,19 @@ 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';+export type GitHoldCode = ContentRefusal['code'] | 'rename_held' | 'parser_regression' | 'managed_image_sync_unsupported' | 'concurrent_write' | 'preparation_stalled';+/** #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;+ /** The last step the owner stamped (`claim_phase.step`), or null when it recorded none. */+ step: string | null;+ waiting_on: 'git' | 'fs' | 'db' | 'pool' | 'unknown' | null;+ attempts: number | null;+ /** The gbrain that wrote the hold; a different version re-screens it (`holdRescreenDue`). */+ gbrain_version: string;+ /** The `gbrain sync` arguments that resume the cursor with its stored options (after `sources retry-held`). */+ sync_argv: string[];+}export type GitHoldReason = InvalidFrontmatterReason | 'rename_source_changed' | FenceReason;export interface GitHoldMeta {@@ -78,6 +91,10 @@ export interface GitHoldMeta {page_revision?: string;/** #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. */+ stall?: PreparationStallMeta;+ /** #6278: the held entry is a deletion (the file is gone); discovery re-screens it on request or a gbrain change, not on its absence. */+ deleted?: true;}/** #6188: why the last fence repair left a hold in place, and when the maintenance run tries it again (null: it does not). */@@ -154,23 +171,24 @@ 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.+ * `concurrent` the #6194 `concurrent_write` holds; `stalled` the #6278 `preparation_stalled` holds.*/-async function adjustSummary(tx: Exec, sourceId: string, incarnation: string, delta: number, staleDelta: number, imageDelta: number, fenceDelta: number,- concurrentDelta: number): Promise<void> {+const SUMMARY_COUNTERS = ['stale', 'images', 'fences', 'concurrent', 'stalled'] 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(',');await tx.executeRaw(`UPDATE op_checkpoints SET completed_keys=jsonb_build_array((completed_keys->0)||jsonb_build_object(- 'count',GREATEST(0,COALESCE((completed_keys->0->>'count')::int,0)+$3::int),- 'stale',GREATEST(0,COALESCE((completed_keys->0->>'stale')::int,0)+$4::int),- 'images',GREATEST(0,COALESCE((completed_keys->0->>'images')::int,0)+$5::int),- 'fences',GREATEST(0,COALESCE((completed_keys->0->>'fences')::int,0)+$6::int),- 'concurrent',GREATEST(0,COALESCE((completed_keys->0->>'concurrent')::int,0)+$7::int))),updated_at=now() WHERE op=$1 AND fingerprint=$2`,- [GIT_HOLD_SUMMARY_OP, summaryFingerprint(sourceId, incarnation), delta, staleDelta, imageDelta, fenceDelta, concurrentDelta]);+ 'count',GREATEST(0,COALESCE((completed_keys->0->>'count')::int,0)+$3::int),${pairs})),updated_at=now() WHERE op=$1 AND fingerprint=$2`,+ [GIT_HOLD_SUMMARY_OP, summaryFingerprint(sourceId, incarnation), delta, ...SUMMARY_COUNTERS.map(name => weights[name])]);}const staleWeight = (record: Pick<GitHoldRecord, 'page_id'> | null) => record && record.page_id !== null ? 1 : 0;const imageWeight = (record: Pick<GitHoldRecord, 'code'> | null) => record?.code === 'managed_image_sync_unsupported' ? 1 : 0;const 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 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) });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',@@ -194,14 +212,13 @@ export async function writeGitHold(tx: Exec, input: Omit<GitHoldRecord, 'versionON CONFLICT(op,fingerprint) DO UPDATE SET completed_keys=EXCLUDED.completed_keys,updated_at=now()`,[GIT_HOLD_OP, gitHoldFingerprint(input.source_id, input.incarnation, input.path), JSON.stringify([record])]);if (existing) {- if (staleWeight(input) !== staleWeight(existing) || imageWeight(input) !== imageWeight(existing) || fenceWeight(input) !== fenceWeight(existing)- || concurrentWeight(input) !== concurrentWeight(existing)) {- await adjustSummary(tx, input.source_id, input.incarnation, 0, staleWeight(input) - staleWeight(existing), imageWeight(input) - imageWeight(existing),- fenceWeight(input) - fenceWeight(existing), concurrentWeight(input) - concurrentWeight(existing));+ const next = weightsOf(input), prior = weightsOf(existing);+ if (SUMMARY_COUNTERS.some(name => next[name] !== prior[name])) {+ await adjustSummary(tx, input.source_id, input.incarnation, 0, Object.fromEntries(SUMMARY_COUNTERS.map(name => [name, next[name] - prior[name]])) as SummaryWeights);}return 'updated';}- await adjustSummary(tx, input.source_id, input.incarnation, 1, staleWeight(input), imageWeight(input), fenceWeight(input), concurrentWeight(input));+ await adjustSummary(tx, input.source_id, input.incarnation, 1, weightsOf(input));return 'inserted';}@@ -217,7 +234,7 @@ export async function clearGitHold(tx: Exec, input: { sourceId: string; incarnatconst existing = await readRow(tx, input.sourceId, input.incarnation, input.path);if (!existing || existing.observed_at > input.observedAt) return false;await tx.executeRaw('DELETE FROM op_checkpoints WHERE op=$1 AND fingerprint=$2', [GIT_HOLD_OP, gitHoldFingerprint(input.sourceId, input.incarnation, input.path)]);- await adjustSummary(tx, input.sourceId, input.incarnation, -1, -staleWeight(existing), -imageWeight(existing), -fenceWeight(existing), -concurrentWeight(existing));+ await adjustSummary(tx, input.sourceId, input.incarnation, -1, weightsOf(existing, -1));return true;}@@ -309,21 +326,32 @@ export async function readGitHoldListing(engine: Exec, sourceIds: string[], limi* re-screened when `sources retry-held` asked, when its verdict depends on* database state or the working tree (slug conflicts, over-size, renames,* parser regressions), or when the gbrain that wrote it read frontmatter or- * screened fences with an older version than this one.+ * screened fences with an older version than this one. #6278: a+ * `preparation_stalled` hold re-screens when the gbrain version changed (the+ * stall was the owner's, not the file's); otherwise it waits for+ * `sources retry-held`.*/export function holdRescreenDue(record: Pick<GitHoldRecord, 'code' | 'meta'>, retried: boolean): boolean {return retried || ['frontmatter_slug_conflict', 'file_too_large', 'rename_held', 'parser_regression'].includes(record.code)|| record.meta.recovery_version < RECOVERY_VERSION- || (record.code === 'invalid_fence' && (record.meta.fence_version ?? 0) < FENCE_VERSION);+ || (record.code === 'invalid_fence' && (record.meta.fence_version ?? 0) < FENCE_VERSION)+ || (record.code === 'preparation_stalled' && record.meta.stall?.gbrain_version !== VERSION);}/*** D6: which repairs a source's holds need. Fence holds route to the fence* repair preview, #6194 concurrent-write holds to the reconcile preview and a- * re-screen, every other hold to the frontmatter repair preview; a source with- * several kinds names each.+ * re-screen, #6278 preparation-stalled holds to writer status and a re-screen+ * (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 }+export interface HoldRepairRoute { fences: number; others: number; concurrent?: number; stalled?: 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[] } {+ return { status: ['gbrain', 'sources', 'writer', 'status', '--source', sourceId, '--json'], retry: ['gbrain', 'sources', 'retry-held', sourceId],+ sync: ['gbrain', 'sync', ...(syncArgv ?? ['--source', sourceId, '--no-pull'])] };+}/*** The source-level next step every surface prints for `route` (sync results,@@ -341,11 +369,17 @@ export function holdRepairSteps(sourceId: string, route: HoldRepairRoute, auto?:const frontmatterText = `preview the frontmatter and other fixes with ${frontmatter.join(' ')} (writes nothing until a hash-bound apply)`;const concurrentText = `for each concurrent-write hold, preview the reconciliation with gbrain sources reconcile ${sourceId} <slug> --preview `+ `(gbrain sources status ${sourceId} names each slug and the database write that raced the import), resolve and apply it, then run gbrain sources retry-held ${sourceId} and gbrain sync --source ${sourceId} --no-pull`;- if (route.concurrent) {- const parts = [...(route.others ? [frontmatterText] : []), ...(route.fences ? [fenceText] : []), concurrentText];+ 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) {+ 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] : [])];const commands = [...(route.others ? [frontmatter.join(' ')] : []), ...(route.fences ? [fences.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 : ['gbrain', 'sources', 'status', sourceId, '--json'], commands, text: parts.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('; ') };}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}` };@@ -376,6 +410,22 @@ export function gitHoldFix(record: Pick<GitHoldRecord, 'source_id' | 'path' | 'cwhy: `Schedules ${record.path} for a re-screen on the next sync, after the page is reconciled.`, verify: { argv: ['gbrain', 'sources', 'status', source, '--json'] } },verify: { argv: ['gbrain', 'sources', 'status', source, '--json'] } };}+ case 'preparation_stalled': {+ const stall = record.meta.stall;+ const steps = stalledHoldSteps(source, stall?.sync_argv);+ const where = stall?.step ? ` at step ${stall.step}${stall.waiting_on && stall.waiting_on !== 'unknown' ? ` (waiting on ${stall.waiting_on})` : ''}` : '';+ const verify = { argv: ['gbrain', 'sources', 'status', source, '--json'] };+ return { argv: steps.status, consent: [], actor: 'agent', requires_exclusive: false, docs: 'docs/guides/write-refusals.md#preparation_stalled',+ why: `${record.path} is held because its ${record.meta.deleted ? 'deletion' : 'import'} could not finish preparing${where}: the write owner gave up after `+ + `${stall?.attempts ?? 'the allowed'} attempt(s) (request ${stall?.request_id ?? '(unknown)'}) and the rest of the source kept syncing. The file itself is not the problem, so no `+ + `frontmatter or fence repair applies. Writer status (read-only) shows the owner process, its gbrain version and any write still stuck; fix what it names or upgrade `+ + `gbrain, then schedule the re-screen and rerun the same sync.`,+ then: { argv: steps.retry, consent: [], actor: 'agent', requires_exclusive: false, verify,+ why: `Schedules ${record.path} for a re-screen on the next sync of ${source}; nothing runs now.`,+ then: { argv: steps.sync, consent: [], actor: 'agent', requires_exclusive: false, verify,+ why: `Re-imports ${record.path} with the run's own options (a different sync command would start another cursor); a preparation that stalls again is held again without blocking the rest.` } },+ verify };+ }case 'file_too_large':return { argv: ['gbrain', 'config', 'get', 'sync.exclude'], consent: [], actor: 'agent', requires_exclusive: false,why: `The size limit is fixed. Split ${record.path} into smaller files and commit, or leave it out of the source: read the current sync.exclude list, then run gbrain config set sync.exclude '<current list>,${record.path}'. The next gbrain sync --source ${source} --no-pull clears the hold.`,@@ -407,6 +457,7 @@ export function gitHoldFix(record: Pick<GitHoldRecord, 'source_id' | 'path' | 'cexport 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';return `docs/guides/write-refusals.md#${reason ? `${code}-${reason}` : code}`;}@@ -616,8 +667,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 }>(`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 FROM op_checkpoints WHERE op=$1 AND fingerprint=$2`,+ 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+ FROM op_checkpoints WHERE op=$1 AND fingerprint=$2`,[GIT_HOLD_SUMMARY_OP, summaryFingerprint(input.sourceId, input.incarnation)]);const outstanding = Number(summary?.count ?? 0);const runHolds = (await readGitSourceHolds(engine, { sourceIds: [input.sourceId], runId: input.runId }))[0]?.holds ?? [];@@ -625,16 +677,22 @@ export async function buildHoldReport(engine: Exec, input: { sourceId: string; iconst escalated = holdsEscalated(input.policy, outstanding - Number(summary?.images ?? 0),{ 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 auto = fences ? await readFenceAutoRepair(engine) : undefined;- const steps = holdRepairSteps(input.sourceId, { fences, others: Math.max(0, outstanding - fences) }, auto);+ const steps = holdRepairSteps(input.sourceId, { fences, others: Math.max(0, outstanding - fences - stalled), ...(stalled ? { stalled } : {}) }, 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+ ? ' Escalated: more files are held than a source should carry, and most of them stalled while preparing, so the write owner (not the files) is the likely cause; inspect it with writer status before the backlog grows.'+ : ' Escalated: more files are held than a source should carry, so a generator or a gbrain upgrade is likely writing or reading them wrong; fix the cause before the backlog grows.';const verify = { argv: ['gbrain', 'sources', 'status', input.sourceId, '--json'] };if (input.remote) return { held_count: runHolds.length, holds_fix: { argv: steps.argv, consent: [], actor: 'host_admin', requires_exclusive: false, verify,why: `${outstanding} file(s) in source ${input.sourceId} are held and not imported; only the brain host can inspect and repair them.`,user_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 ? `then ${steps.text}.` : 'the repair preview proposes each fix and writes nothing.')- + (escalated ? ' Escalated: more files are held than a source should carry, so a generator or a gbrain upgrade is likely writing or reading them wrong; fix the cause before the backlog grows.' : '') };+ + (fences || stalled ? `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 } : {}),...(input.pendingScreen ? { holds_pending_screen: true } : {}), holds_fix: fix };diff --git a/src/core/persistence/sync-run.ts b/src/core/persistence/sync-run.tsindex 45323cc6ad..81fd676a35 100644--- a/src/core/persistence/sync-run.ts+++ b/src/core/persistence/sync-run.ts@@ -17,7 +17,7 @@ import { assertSyncPageOrigin, sameSyncOrigin, syncOriginScope } from './sync-orimport { assertManagedSyncActive, assertSyncDispatchActive, managedSyncAuthority, validateSyncAuthority, validateManagedSyncOptions, syncProcessingOptions, SYNC_PROCESSING_KEYS, type SyncAuthority, type SyncProcessingOptions } from './sync-authority.ts';import { prepareManagedSyncMutation, type SyncCursorOptions, type SyncIntent } from './sync-prepare.ts';import { screeningRequest } from './noop-kernel.ts';-import { noopWaiversEnabled, screenWaiver, waiveNoopEntry, waiveNoopRun, waiverBatchEnabled, type NoopWaiver, type WaiverRunEntry } from './sync-waivers.ts';+import { noopWaiversEnabled, screenWaiver, unfinishedPageRequestParams, UNFINISHED_PAGE_REQUEST_SQL, waiveNoopEntry, waiveNoopRun, waiverBatchEnabled, type NoopWaiver, type WaiverRunEntry } from './sync-waivers.ts';import { resolve } from 'node:path';import { currentCompanyBrainSync, getCompanyBrainProfile, readCompanyBrainPlan } from '../company-brain/profile.ts';import { readCommittedBlob } from '../company-brain/revision.ts';@@ -33,11 +33,12 @@ import { readJournalLimits } from './limits.ts';import { assertManagedSyncAllowed } from './worktree-refresh.ts';import type { GBrainConfig } from '../config.ts';import { admitGroup, freezeFollowers, groupableIntent, nextGroupSize, type BulkSettings } from './sync-group.ts';-import { cancelWindow } from './sync-window.ts';+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 { SYNC_READ_BOUND, type TreeBlob } from './sync-blobs.ts';-import { dryRunScreen, isSyncReadBound, loadSyncScreenRun, managedImageHold, pinnedBlob, prepareTimeFenceHold, screenFrozenImport, type HeldEntry, type SyncScreenRun } from './sync-screen.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 { faultPoint } from './fault-points.ts';@@ -236,7 +237,8 @@ function writeDiagnostic(cursor: Cursor, pending: Pending, row: WriteRequest): Mconst terminal = isTerminalWriteState(row.state);const code = terminal ? row.error_code ?? (row.state === 'cancelled' ? 'cancelled' : 'storage_error') : 'write_pending';const blockedReason = ['writer_busy', 'writer_pool_capacity', 'owner_unavailable', 'recovery_required', 'writer_lock_unavailable',- 'database_contention', 'consumer_stopping', 'revision_changed_repreparing', 'unexpected_file_bytes', 'unexpected_staging_bytes'].includes(row.blocked_reason ?? '') ? row.blocked_reason! : 'write_pending';+ 'database_contention', 'consumer_stopping', 'revision_changed_repreparing', 'unexpected_file_bytes', 'unexpected_staging_bytes',+ 'preparation_deadline', 'group_member_waiting'].includes(row.blocked_reason ?? '') ? row.blocked_reason! : 'write_pending';const detail = terminal ? writeFailureDiagnostic(code, row.error_message) : {reason: blockedReason, message: 'The write is accepted but not committed; the sync checkpoint has not advanced.',suggestion: 'Re-run the same sync options to resume this request. Do not submit a replacement request or skip the pending write.',@@ -395,80 +397,164 @@ function advanceHeld(held: Cursor, converted?: string[]): Cursor {return next;}+/** #6278: the terminal code an owner stamps on a request whose preparation never settled within its attempts (Lane A, consumer.ts). */+export const PREPARATION_STALLED = 'preparation_stalled';+const preparationStalled = (row: Pick<WriteRequest, 'state' | 'error_code'>) => row.state === 'failed' && row.error_code === PREPARATION_STALLED;+/** The run's page requests, as `persistence_requests_sync_run_open` indexes them. */+const SYNC_PAGE_KINDS_SQL = "intent->>'kind' IN ('managed_sync_import','managed_sync_delete')";+/** The `gbrain sync` arguments a hold or receipt prints to resume this cursor with its own options. */+const resumeArgsOf = (cursor: Cursor, run: { syncOptions: SyncCursorOptions; repoPath?: string }) =>+ managedSyncResumeArgs({ sourceId: cursor.sourceId, processingOptions: cursor.processingOptions, syncOptions: cursor.syncOptions ?? run.syncOptions, repoPath: run.repoPath });++/**+ * #6278 (1.2b): the hold gate. Before this change both converters waited until+ * no request on the whole source was unfinished, so one stuck preparation or a+ * stream of maintenance writes on other pages kept every hold pending forever.+ *+ * Invariant the source-wide wait protected, kept by this narrower one: no entry+ * after the held one publishes a change that depends on the held entry's+ * outcome (the same path or origin, either side of a rename, a delete of the+ * same slug), and the cursor never checkpoints past an entry whose request is+ * still unfinished. It holds because (1) the failed entry's obsolete admitted+ * suffix (its group's later members, the admit-ahead window, this run's lane+ * groups: every queued request of the run admitted after it) is cancelled+ * first, so no successor of this run can publish against the held entry and+ * no queued successor can wait behind a blocked root while this gate waits for+ * it; (2) the gate then waits only for requests that are still active in that+ * suffix (claimed, recovering, or carrying a recovery record) and for any+ * unfinished or recovery-bearing request that names the entry's page by slug,+ * page id, path, origin or rename endpoint (`UNFINISHED_PAGE_REQUEST_SQL`);+ * (3) the predicate is evaluated inside the transaction that writes the hold+ * and swaps the cursor, after taking the page keys and before the cursor row+ * (the lock order every waiver and publication uses), so a same-page write+ * admitted meanwhile either committed before the hold or waits behind it and+ * re-reads the page. The checkpoint's own validation then finds every+ * non-committed receipt of the run superseded (`convertedFromFailed` carries+ * the failed receipt and every earlier uncommitted receipt at the same index)+ * or committed by a later request at its index. A hold never turns a failed+ * predecessor into a committed one; cancelled successors are re-frozen under a+ * fresh dependency chain when the run continues.+ */+async function holdUnderGate(engine: BrainEngine, input: { cursor: Cursor; key: string; pending: Pending; hold: HeldEntry; assertActive: () => void;+ observedAt: string; waitMs: number; failedId: string; base?: Cursor }): Promise<Cursor | 'pending'> {+ const { cursor, key, pending, assertActive } = input;+ const principal = cursor.authority.writer.principal;+ const base: Cursor = input.base ?? { ...cursor }; delete base.group; delete base.window; delete base.pending;+ const [failedRow] = await engine.executeRaw<{ sequence: string | number | null }>('SELECT sequence::text AS sequence FROM persistence_requests WHERE id=$1::uuid', [input.failedId]);+ const after = failedRow?.sequence == null ? null : String(failedRow.sequence);+ const keys = [{ sourceId: cursor.sourceId, slug: pending.slug }, ...(pending.intent.renameFrom && pending.intent.renameFrom.slug !== pending.slug ? [{ sourceId: cursor.sourceId, slug: pending.intent.renameFrom.slug }] : [])];+ const deadline = performance.now() + input.waitMs;+ for (;;) {+ assertActive();+ if (cursor.window?.length) await cancelWindow(engine, cursor.window, principal);+ if (after !== null) {+ const queued = await engine.executeRaw<WriteRequest>(`SELECT * FROM persistence_requests WHERE worktree_id=$1::uuid AND intent->>'runId'=$2 AND state='queued'+ AND ${SYNC_PAGE_KINDS_SQL} AND sequence>$3::bigint ORDER BY sequence`, [cursor.binding.worktree_id, cursor.runId, after]);+ if (queued.length) await cancelRows(engine, queued);+ }+ const saved = await engine.transaction(async tx => {+ assertActive();+ await tx.lockPageKeys(keys);+ const [samePage, suffix] = await Promise.all([+ tx.executeRaw(UNFINISHED_PAGE_REQUEST_SQL, unfinishedPageRequestParams(cursor, pending)),+ after === null ? Promise.resolve([]) : tx.executeRaw(`SELECT 1 FROM persistence_requests WHERE worktree_id=$1::uuid AND intent->>'runId'=$2 AND sequence>$3::bigint+ AND ${SYNC_PAGE_KINDS_SQL} AND (state IN ('queued','running','recovering') OR recovery IS NOT NULL) LIMIT 1`, [cursor.binding.worktree_id, cursor.runId, after]),+ ]);+ if (samePage.length || suffix.length) return null;+ const stale = await tx.executeRaw<{ request_id: string }>(`SELECT request_id::text AS request_id FROM persistence_requests WHERE worktree_id=$1::uuid AND intent->>'runId'=$2+ AND ${SYNC_PAGE_KINDS_SQL} AND intent->>'index'=$3 AND state IN ('failed','cancelled','conflict')`, [cursor.binding.worktree_id, cursor.runId, String(cursor.index)]);+ const converted = [...new Set([...(cursor.convertedFromFailed ?? []), ...stale.map(row => row.request_id), pending.requestId])];+ return writeCursor(tx, key, cursor, advanceHeld(base, converted), async inner => {+ await heldWrite(cursor, input.hold, input.observedAt)(inner);+ await recordSyncConversion(inner, cursor.sourceId, cursor.incarnation, { request_id: pending.requestId, path: pending.intent.path ?? null, slug: pending.slug, run_id: cursor.runId, outcome: 'held' });+ }, true);+ });+ if (saved) { await faultPoint('sync:mid_checkpoint', { sourceId: cursor.sourceId }); return saved; }+ if (performance.now() >= deadline) return 'pending';+ await new Promise(resolve => setTimeout(resolve, 50));+ }+}+/**- * #5988 (E6): a cursor blocked by a failed content refusal converts in place with its stored- * options: held when the screen holds the frozen entry, re-frozen under a new request when it- * passes, but only once for the same bytes, so a refusal the screen misses stays blocked- * without minting a receipt per run.- * #6188: a failed fence refusal (typed, or a message an older gbrain stored) holds the same- * bytes even when the screen admits them (`prepare_time`: the refusal read stored rows). A- * compacted `invalid_params` / `take_row_collision` receipt, whose message is gone, converts- * only when the re-screen of the current bytes holds them; an arbitrary `invalid_params` is+ * #5988 (E6): a cursor blocked by a failed content refusal converts in place+ * with its stored options: held when the screen holds the frozen entry,+ * re-frozen under a new request when it passes, but only once for the same+ * bytes, so a refusal the screen misses stays blocked without minting a+ * receipt per run.+ * #6188: a failed fence refusal (typed, or a message an older gbrain stored)+ * holds the same bytes even when the screen admits them (`prepare_time`: the+ * refusal read stored rows). A compacted `invalid_params` /+ * `take_row_collision` receipt, whose message is gone, converts only when the+ * re-screen of the current bytes holds them; an arbitrary `invalid_params` is* never a fence hold.+ * #6278: a `preparation_stalled` receipt (the owner gave up preparing it)+ * holds the entry as it was frozen: an import by its bytes, a delete as a+ * delete hold; the checkpoint never holds (the run stays blocked). Every hold+ * is written behind the narrowed gate (`holdUnderGate`).*/async function convertBlockedCursor(engine: BrainEngine, blocked: Cursor, key: string, assertActive: () => void,run: Parameters<typeof freezeEntry>[4] & { observedAt?: string }): Promise<Cursor> {const previous = blocked.pending!;const failed = await getWriteRequest(engine, blocked.authority.writer.principal, previous.requestId);if (!failed || !['failed', 'conflict', 'cancelled'].includes(failed.state)) return blocked;+ const entry = blocked.entries[blocked.index];+ if (preparationStalled(failed)) {+ if (blocked.companyPlan || previous.intent.kind === 'managed_sync_checkpoint' || !entry || entry.path !== previous.intent.path) return blocked;+ const hold = preparationStalledHold(entry, previous.slug, previous.pageId, failed, previous.intent.content ?? null, previous.intent.blobOid, resumeArgsOf(blocked, run));+ 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;+ }const fence = fenceReceiptLocation(failed);const compacted = !fence && failed.compacted === true && failed.error_message == null && ['invalid_params', 'take_row_collision'].includes(failed.error_code ?? '');if (!fence && !compacted && !isContentRefusal(failed.error_code, failed.error_message)) return blocked;- const unfinished = await engine.executeRaw("SELECT id FROM persistence_requests WHERE source_id=$1 AND (state IN ('queued','running','recovering') OR recovery IS NOT NULL) LIMIT 1", [blocked.sourceId]);- assertActive();- if (unfinished.length) return blocked;const base: Cursor = { ...blocked }; delete base.pending;const again = await freezeEntry(engine, base, key, assertActive, run);const converted = [...(blocked.convertedFromFailed ?? []), previous.requestId];- const logged = (outcome: 'held' | 'refrozen') => (tx: BrainEngine) => recordSyncConversion(tx, blocked.sourceId, blocked.incarnation,- { request_id: previous.requestId, path: previous.intent.path ?? null, slug: previous.slug, run_id: blocked.runId, outcome });- const holdWith = (hold: HeldEntry) => saveCursor(engine, key, blocked, advanceHeld(base, converted), false, assertActive,- async tx => { await heldWrite(blocked, hold, run.observedAt!)(tx); await logged('held')(tx); });+ const holdWith = async (hold: HeldEntry) => {+ 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 ('hold' in again) return holdWith(again.hold);const sameBytes = again.intent.rawHash === previous.intent.rawHash && again.intent.content === previous.intent.content;- const entry = base.entries[base.index];if (fence && sameBytes && again.intent.kind === 'managed_sync_import' && again.intent.content !== null && entry?.path === again.intent.path) {return holdWith(prepareTimeFenceHold(entry, again.slug, again.pageId, fence, again.intent.content, again.intent.blobOid));}if (compacted || (previous.converted && sameBytes)) return blocked;- return saveCursor(engine, key, blocked, { ...blocked, convertedFromFailed: converted, pending: { ...again, converted: true } }, false, assertActive, logged('refrozen'));+ const unfinished = await engine.executeRaw("SELECT id FROM persistence_requests WHERE source_id=$1 AND (state IN ('queued','running','recovering') OR recovery IS NOT NULL) LIMIT 1", [blocked.sourceId]);+ assertActive();+ if (unfinished.length) return blocked;+ 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' }));}/*** #6188 (E10): a page request of this run that failed with a fence refusal (or, #6194, a- * `revision_conflict` proven to come from a concurrent database-only write) is held in the- * same run instead of blocking it (the single path, and a bulk group's failed member, which- * the group step leaves as the single pending entry). Other requests of the source settle- * first, within the run's wait budget; when they are still running the run returns- * `partial` and the next run's start-of-run conversion holds the entry. The failed request- * is converted once (`convertedFromFailed`, so it no longer blocks the checkpoint), gets no- * failure-ledger row, and is logged as a conversion. Null when it is not a fence refusal or+ * `revision_conflict` proven to come from a concurrent database-only write, or, #6278, a+ * `preparation_stalled` receipt for an import or a delete) is held in the same run instead+ * of blocking it (the single path, and a bulk group's failed member, which the group step+ * leaves as the single pending entry). The hold waits behind the narrowed gate+ * (`holdUnderGate`) within the run's wait budget; when a request that can still change the+ * entry's outcome is running the run returns `partial` and the next run's start-of-run+ * conversion holds the entry. The failed request is converted once (`convertedFromFailed`,+ * so it no longer blocks the checkpoint), gets no failure-ledger row, and is logged as a+ * conversion. Null when it is not such a receipt, when the entry is the checkpoint, or when* the run does not hold files (`sync.holds=fail`, company-brain sources).*/async function holdFailedFenceRequest(engine: BrainEngine, cursor: Cursor, key: string, pending: Pending, done: WriteRequest, assertActive: () => void,- run: { screen?: SyncScreenRun | null; observedAt?: string }, waitMs: number): Promise<Cursor | 'pending' | null> {- if (!run.screen || cursor.companyPlan || pending.intent.kind !== 'managed_sync_import' || typeof pending.intent.content !== 'string') return null;- const fence = fenceReceiptLocation(done);+ run: { screen?: SyncScreenRun | null; observedAt?: string; syncOptions: SyncCursorOptions; repoPath?: string }, waitMs: number): Promise<Cursor | 'pending' | null> {+ if (!run.screen || cursor.companyPlan || pending.intent.kind === 'managed_sync_checkpoint') return null;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 fence = stalled ? 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 = fence ? null : await concurrentWriteProof(engine, { sourceId: cursor.sourceId, incarnation: cursor.incarnation, pending, done });- if (!fence && !proof) return null;- const deadline = performance.now() + waitMs;- for (;;) {- const unfinished = await engine.executeRaw("SELECT id FROM persistence_requests WHERE source_id=$1 AND (state IN ('queued','running','recovering') OR recovery IS NOT NULL) LIMIT 1", [cursor.sourceId]);- assertActive();- if (!unfinished.length) break;- if (performance.now() >= deadline) return 'pending';- await new Promise(resolve => setTimeout(resolve, 50));- }- const hold = fence ? prepareTimeFenceHold(entry, pending.slug, pending.pageId, fence, pending.intent.content, pending.intent.blobOid)- : concurrentWriteHold(entry, pending.slug, pending.pageId!, pending.intent, proof!);- const base: Cursor = { ...cursor }; delete base.group;- return saveCursor(engine, key, cursor, advanceHeld(base, [...(cursor.convertedFromFailed ?? []), pending.requestId]), false, assertActive, async tx => {- await heldWrite(cursor, hold, run.observedAt!)(tx);- await recordSyncConversion(tx, cursor.sourceId, cursor.incarnation, { request_id: pending.requestId, path: pending.intent.path ?? null, slug: pending.slug, run_id: cursor.runId, outcome: 'held' });- });+ const proof = stalled || fence ? null : await concurrentWriteProof(engine, { sourceId: cursor.sourceId, incarnation: cursor.incarnation, pending, done });+ if (!stalled && !fence && !proof) 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!);+ return holdUnderGate(engine, { cursor, key, pending, hold, assertActive, observedAt: run.observedAt!, waitMs, failedId: done.id });}/**@@ -477,7 +563,7 @@ async function holdFailedFenceRequest(engine: BrainEngine, cursor: Cursor, key:* recorded in the failure ledger and blocks the run with its diagnostic.*/async function settleFailedRequest(engine: BrainEngine, input: { cursor: Cursor; key: string; pending: Pending; done: WriteRequest; assertActive: () => void;- run: { screen?: SyncScreenRun | null; observedAt?: string; repoPath?: string }; syncOptions: SyncCursorOptions; processingOptions: SyncProcessingOptions;+ run: { screen?: SyncScreenRun | null; observedAt?: string; repoPath?: string; syncOptions: SyncCursorOptions }; syncOptions: SyncCursorOptions; processingOptions: SyncProcessingOptions;remote: boolean; waitMs: number; signal?: AbortSignal }): Promise<{ cursor: Cursor } | { result: SyncResult }> {const { cursor, key, pending, done, syncOptions, processingOptions, remote } = input;const converted = await holdFailedFenceRequest(engine, cursor, key, pending, done, input.assertActive, input.run, input.waitMs);diff --git a/src/core/persistence/sync-screen.ts b/src/core/persistence/sync-screen.tsindex 28092d188b..88714e1fa3 100644--- a/src/core/persistence/sync-screen.ts+++ b/src/core/persistence/sync-screen.ts@@ -29,7 +29,8 @@ import { readSyncFile, syncGitPath, type SyncDiscovery, type SyncEntry } from '.import { readBlobContents, readTreeBlobs, SYNC_READ_BOUND, type TreeBlob } from './sync-blobs.ts';import { screenSyncImport, type SyncImportScreenInput } from './sync-prepare.ts';import type { SyncProcessingOptions } from './sync-authority.ts';-import { gitHoldItem, readSyncHoldPolicy, readSyncImportProvenance, type GitHoldItem, type GitHoldRecord, type SyncHoldPolicy } from './sync-holds.ts';+import { gitHoldItem, readSyncHoldPolicy, readSyncImportProvenance, type GitHoldItem, type GitHoldRecord, type PreparationStallMeta, type SyncHoldPolicy } from './sync-holds.ts';+import type { WriteRequest } from './model.ts';type Snapshot = Awaited<ReturnType<BrainEngine['readPageSnapshot']>>;export type HeldEntry = Pick<GitHoldRecord, 'path' | 'source_path' | 'slug' | 'page_id' | 'code' | 'message' | 'upstream_version' | 'meta'>;@@ -85,6 +86,34 @@ export function prepareTimeFenceHold(entry: Pick<SyncEntry, 'path' | 'sourcePathreturn heldEntry(entry, slug, pageId, { code: 'invalid_fence', reason: 'prepare_time', fence, message: fenceMessage(fence) }, content, blobOid ? { oid: blobOid } : null);}+/** #6278: the receipt fields a `preparation_stalled` hold keeps (the owner's step vocabulary only, never content). */+export function preparationStallMeta(receipt: Pick<WriteRequest, 'request_id' | 'error_detail'>, syncArgv: string[]): PreparationStallMeta {+ const detail = receipt.error_detail && typeof receipt.error_detail === 'object' ? receipt.error_detail as Record<string, unknown> : {};+ const waiting = detail.waiting_on;+ return { request_id: receipt.request_id, step: typeof detail.step === 'string' ? detail.step.slice(0, 64) : null,+ waiting_on: typeof waiting === 'string' && ['git', 'fs', 'db', 'pool', 'unknown'].includes(waiting) ? waiting as PreparationStallMeta['waiting_on'] : null,+ attempts: typeof detail.attempts === 'number' && Number.isFinite(detail.attempts) ? detail.attempts : null, gbrain_version: VERSION, sync_argv: syncArgv };+}++/**+ * #6278: the hold a `managed_sync_import` or `managed_sync_delete` member earns+ * when its owner finished it `failed` with `preparation_stalled` (the+ * preparation never settled within its attempts). The file is not the+ * problem, so the hold carries the receipt's step and wait cause and routes+ * to writer status, then `sources retry-held` and the same sync. A delete+ * hold has no content (`upstream_version` null) and is marked `deleted`, so+ * discovery leaves it alone until a retry or a gbrain change.+ */+export function preparationStalledHold(entry: Pick<SyncEntry, 'path' | 'sourcePath' | 'working' | 'renameFrom' | 'renameHeld' | 'action'>, slug: string, pageId: number | null,+ receipt: Pick<WriteRequest, 'request_id' | 'error_detail'>, content: string | null, blobOid: string | null | undefined, syncArgv: string[]): HeldEntry {+ const stall = preparationStallMeta(receipt, syncArgv);+ const where = stall.step ? ` at step ${stall.step}` : '';+ const held = heldEntry(entry, slug, pageId, { code: 'preparation_stalled',+ message: `${entry.path}: its ${entry.action === 'delete' ? 'deletion' : 'import'} could not finish preparing${where} (request ${receipt.request_id}), so it is held and the rest of the source synced. `+ + `Inspect the writer with gbrain sources writer status, then gbrain sources retry-held and the same sync.` }, content, blobOid ? { oid: blobOid } : null);+ return { ...held, meta: { ...held.meta, stall, ...(entry.action === 'delete' ? { deleted: true as const } : {}) } };+}+/*** #5493: managed sync has no image importer, so an image import is held as* incomplete coverage instead of refusing the run. The hold names the pinneddiff --git a/src/core/persistence/sync-waivers.ts b/src/core/persistence/sync-waivers.tsindex 6e00186386..e8696976be 100644--- a/src/core/persistence/sync-waivers.ts+++ b/src/core/persistence/sync-waivers.ts@@ -25,11 +25,14 @@ export interface NoopWaiver { kind: 'import' | 'delete'; kernel: NoopKernelWaive/** DX-A15: `GBRAIN_SYNC_WAIVE_NOOP=0` admits every entry, for triage. */export function noopWaiversEnabled(env: NodeJS.ProcessEnv = process.env): boolean { return env.GBRAIN_SYNC_WAIVE_NOOP !== '0'; }-const PAGE_MATCH = "r.source_id=$3 AND (r.slug=$4 OR r.page_id=$5::bigint OR r.intent->'renameFrom'->>'slug'=$4 OR r.intent->'renameFrom'->>'pageId'=$6)";+const PAGE_MATCH = `r.source_id=$3 AND (r.slug=$4 OR r.page_id=$5::bigint OR r.intent->'renameFrom'->>'slug'=$4 OR r.intent->'renameFrom'->>'pageId'=$6+ OR ($7::text IS NOT NULL AND (r.intent->>'path'=$7 OR r.intent->>'sourcePath'=$8 OR r.intent->'renameFrom'->>'sourcePath'=$8)))`;/*** CEO-A12/A34: an unfinished request for the page, by slug, page id or a rename- * from it. Each branch matches one partial request index: worktree pending,- * worktree recovery, and database-only pending by source incarnation.+ * from it; #6278: also by the entry's file path or origin, or a rename from that+ * origin (`$7`, `$8`; null skips the path match). Each branch matches one+ * partial request index: worktree pending, worktree recovery, and+ * database-only pending by source incarnation.*/export const UNFINISHED_PAGE_REQUEST_SQL = `SELECT 1 FROM ((SELECT r.id FROM persistence_requests r WHERE r.worktree_id=$1::uuid AND r.state IN ('queued','running','recovering') AND ${PAGE_MATCH} LIMIT 1)@@ -37,6 +40,12 @@ export const UNFINISHED_PAGE_REQUEST_SQL = `SELECT 1 FROM (UNION ALL (SELECT r.id FROM persistence_requests r WHERE r.source_incarnation=$2::uuid AND r.worktree_id IS NULLAND r.state IN ('queued','running','recovering') AND ${PAGE_MATCH} LIMIT 1)) unfinished LIMIT 1`;+/** The parameters of `UNFINISHED_PAGE_REQUEST_SQL` for one frozen entry (slug, page id, file path and origin). */+export function unfinishedPageRequestParams(cursor: Pick<WaiverCursor, 'sourceId' | 'incarnation' | 'binding'>, pending: Pick<WaiverEntry, 'slug' | 'pageId' | 'intent'>): unknown[] {+ return [cursor.binding.worktree_id, cursor.incarnation, cursor.sourceId, pending.slug, pending.pageId, String(pending.pageId),+ pending.intent.path ?? null, pending.intent.sourcePath ?? pending.intent.path ?? null];+}+/*** Screens a frozen, unadmitted entry. Returns null to admit, or the cursor that* `advance` (the waiver won) or `reread` (the cursor moved meanwhile) returns@@ -59,7 +68,7 @@ export async function waiveNoopEntry<C extends WaiverCursor>(engine: BrainEnginetry { await assertSyncPageOrigin(tx, cursor.sourceId, intent.sourcePath!, pending.pageId, true, syncOriginScope(cursor)); }catch { return null; }} else if (snapshot?.page.id !== pending.pageId || snapshot.page.deleted_at != null || snapshot.revision !== intent.expected_revision) return null;- const unfinished = await tx.executeRaw(UNFINISHED_PAGE_REQUEST_SQL, [cursor.binding.worktree_id, cursor.incarnation, cursor.sourceId, pending.slug, pending.pageId, String(pending.pageId)]);+ const unfinished = await tx.executeRaw(UNFINISHED_PAGE_REQUEST_SQL, unfinishedPageRequestParams(cursor, pending));if (unfinished.length) return null;return advance(tx, waived);});@@ -122,7 +131,7 @@ export async function waiveNoopRun<C extends WaiverCursor>(engine: BrainEngine,const bySlug = new Map(pages.map(page => [page.slug, page]));const scope = syncOriginScope(cursor);const checks = await pipelined(tx, run.flatMap(({ pending, waived }) => [- () => tx.executeRaw(UNFINISHED_PAGE_REQUEST_SQL, [cursor.binding.worktree_id, cursor.incarnation, cursor.sourceId, pending.slug, pending.pageId, String(pending.pageId)]),+ () => tx.executeRaw(UNFINISHED_PAGE_REQUEST_SQL, unfinishedPageRequestParams(cursor, pending)),() => waived.kind === 'delete'? assertSyncPageOrigin(tx, cursor.sourceId, pending.intent.sourcePath!, pending.pageId, true, scope).then(() => true, () => false): Promise.resolve(true),diff --git a/src/core/persistence/types.ts b/src/core/persistence/types.tsindex 7378d7435b..9de644e4dd 100644--- a/src/core/persistence/types.ts+++ b/src/core/persistence/types.ts@@ -18,7 +18,7 @@ export const WRITE_ERROR_CODES = ['connector_account_changed', 'connector_intent_outdated', 'checkpoint_validation_timeout','invalid_connector_text', 'connector_holds_exhausted', 'connector_fence_below_timeline','core_budget_exceeded', 'core_mark_owner_only', 'core_remote_edit_refused', 'core_delete_owner_only',- 'timeline_rows_would_be_removed',+ 'timeline_rows_would_be_removed', 'preparation_stalled',] as const;export type WriteErrorCode = typeof WRITE_ERROR_CODES[number];diff --git a/src/core/sync-reconcile.ts b/src/core/sync-reconcile.tsindex 056c8feb02..61b983765c 100644--- a/src/core/sync-reconcile.ts+++ b/src/core/sync-reconcile.ts@@ -226,6 +226,21 @@ export function syncWatchdogPlan(args: string[], res: HardDeadlineResolution): {};}+/**+ * #6278: the `gbrain sync` arguments (after `sync`) that resume a managed cursor+ * with its stored processing and cursor options, so a follow-up printed by a+ * hold, `sources retry-held` or doctor keeps `--no-embed` and friends instead+ * of starting a second cursor. `syncResumeCommand` quotes them.+ */+export function managedSyncResumeArgs(input: { sourceId: string; processingOptions?: { noEmbed?: boolean; noExtract?: boolean; noSchemaPack?: boolean } | null;+ syncOptions?: { full?: boolean; workingTree?: boolean; srcSubpath?: string | null; exclude?: string[]; includeHidden?: string[]; strategy?: string | null } | null;+ repoPath?: string | null }): string[] {+ const p = input.processingOptions ?? {}, c = input.syncOptions ?? {};+ return ['--source', input.sourceId, '--no-pull', ...(input.repoPath ? ['--repo', input.repoPath] : []), ...(p.noEmbed ? ['--no-embed'] : []), ...(p.noExtract ? ['--no-extract'] : []),+ ...(p.noSchemaPack ? ['--no-schema-pack'] : []), ...(c.full ? ['--full'] : []), ...(c.workingTree ? ['--working-tree'] : []), ...(c.srcSubpath ? ['--src-subpath', c.srcSubpath] : []),+ ...(c.exclude ?? []).flatMap(pattern => ['--exclude', pattern]), ...(c.includeHidden ?? []).flatMap(pattern => ['--include-hidden', pattern]), ...(c.strategy ? ['--strategy', c.strategy] : [])];+}+/*** #5984: the shell-quoted `gbrain sync` command that resumes this run with the* same brain, source and cursor-defining options (`args` are the sync argv).diff --git a/test/managed-sync-preparation-stalled-holds.test.ts b/test/managed-sync-preparation-stalled-holds.test.tsnew file mode 100644index 0000000000..e5cc9a7e44--- /dev/null+++ b/test/managed-sync-preparation-stalled-holds.test.ts@@ -0,0 +1,314 @@+/**+ * #6278 (B1): a managed sync member whose owner gave up preparing it+ * (`preparation_stalled`) is held, never re-entered: an import by its bytes, a+ * delete as a delete hold, a rename with its endpoints; the checkpoint never+ * holds; `sync.holds=fail` keeps blocking. The hold lands behind the narrowed+ * gate: an unrelated maintenance write on the same source no longer blocks+ * it, a write on the same page still does, and a run killed before the cursor+ * consumed the failure holds the entry at the start of the next run. Every+ * surface routes the hold to writer status, then `sources retry-held` and the+ * same sync with its options, never to frontmatter repair. The forced probe+ * throws the terminal code from the consumer's `consumer:prepared` seam (the+ * single path) or the `publication:before_commit` seam inside the group transaction, so+ * the receipt is exactly what Lane A's consumer writes. Synthetic content only.+ */+import { afterAll, beforeAll, expect, test } from 'bun:test';+import { execFileSync } from 'node:child_process';+import { randomUUID } from 'node:crypto';+import { mkdirSync, mkdtempSync, rmSync, writeFileSync, unlinkSync, renameSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import type { BrainEngine } from '../src/core/engine.ts';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { OperationError } from '../src/core/ops/contract.ts';+import { claimWorktree } from '../src/core/persistence/ownership.ts';+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';+import { performManagedSync } from '../src/core/persistence/sync-run.ts';+import { installFaultHook, type FaultPoint } from '../src/core/persistence/fault-points.ts';+import { readGitSourceHolds, holdRescreenDue, GIT_HOLD_SUMMARY_OP } from '../src/core/persistence/sync-holds.ts';+import { preparationStallMeta } from '../src/core/persistence/sync-screen.ts';+import { readHeldCoverage, coverageRoute } from '../src/core/persistence/held-reads.ts';+import { retryHeld } from '../src/commands/sources-retry-held.ts';+import { gitHeldFilesCheck } from '../src/commands/doctor/checks/git-holds.ts';+import { printSyncResult, type SyncOpts, type SyncResult } from '../src/commands/sync.ts';+import { VERSION } from '../src/version.ts';+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';+import { testBackends } from './helpers/test-backends.ts';+import { withEnv } from './helpers/with-env.ts';++const backends = testBackends();+const home = mkdtempSync(join(tmpdir(), 'gbrain-stalled-holds-'));+const engines: BrainEngine[] = [];+let closePostgres: (() => Promise<void>) | undefined;+const env = { GBRAIN_HOME: home, GBRAIN_SYNC_FAILURES_DIR: home };+const git = (root: string, ...args: string[]) => execFileSync('git', ['-C', root, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim();+const commit = (root: string, message = 'content') => { git(root, 'add', '-A'); git(root, '-c', 'user.name=Example', '-c', '[email protected]', 'commit', '-qm', message); return git(root, 'rev-parse', 'HEAD'); };+const note = (title: string) => `---\ntitle: ${title}\n---\nA synthetic observation about ${title}.\n`;++beforeAll(async () => {+ if (backends.includes('pglite')) { const engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema(); engines.push(engine); }+ if (backends.includes('postgres')) { const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL!); engines.push(pg.engine); closePostgres = pg.close; }+}, 120_000);++afterAll(async () => {+ installFaultHook(undefined);+ for (const engine of engines) { await disposePersistenceConsumer(engine); await engine.disconnect(); }+ await closePostgres?.(); rmSync(home, { recursive: true, force: true });+});++/** The forced probe: the owner finishes the request for one of `paths` `failed` with `preparation_stalled` at `point`. */+function stallPaths(engine: BrainEngine, sourceId: string, paths: Set<string>, point: FaultPoint = 'consumer:prepared'): { fired: string[] } {+ const fired: string[] = [];+ installFaultHook(async (at, detail) => {+ if (at !== point || detail.sourceId !== sourceId || !detail.requestId) return;+ const [row] = await engine.executeRaw<{ path: string | null }>("SELECT intent->>'path' AS path FROM persistence_requests WHERE request_id=$1::uuid", [detail.requestId]);+ if (!row?.path || !paths.has(row.path)) return;+ fired.push(row.path);+ throw new OperationError('preparation_stalled', `Preparation of ${row.path} did not finish within its attempts (forced probe).`, 'Inspect the writer with gbrain sources writer status.');+ });+ return { fired };+}++async function source(engine: BrainEngine, files: Record<string, string>) {+ const id = `stall-${randomUUID().replace(/-/g, '').slice(0, 20)}`, root = join(home, id);+ const write = (path: string, content: string) => { mkdirSync(join(root, path, '..'), { recursive: true }); writeFileSync(join(root, path), content); };+ mkdirSync(root, { recursive: true }); git(root, 'init', '-q');+ git(root, 'config', 'user.name', 'Example'); git(root, 'config', 'user.email', '[email protected]');+ for (const [path, content] of Object.entries(files)) write(path, content);+ commit(root, 'fixture');+ 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,$3::text::jsonb)', [id, root, '{}']);+ await claimWorktree(engine, id, root);+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');+ const sync = (extra: Partial<SyncOpts> = {}) => performManagedSync(engine, { sourceId: id, noPull: true, noEmbed: true, noExtract: true, ...extra });+ const holds = async () => (await readGitSourceHolds(engine, { sourceIds: [id] }))[0]?.holds ?? [];+ const lastCommit = async () => (await engine.executeRaw<{ last_commit: string }>('SELECT last_commit FROM sources WHERE id=$1', [id]))[0]!.last_commit;+ const failedRequests = () => engine.executeRaw<{ request_id: string; error_code: string; state: string; path: string | null }>(+ "SELECT request_id::text AS request_id,error_code,state,intent->>'path' AS path FROM persistence_requests WHERE source_id=$1 AND state IN ('failed','conflict','cancelled') ORDER BY sequence", [id]);+ const ledger = () => engine.executeRaw("SELECT 1 FROM op_checkpoints WHERE op='managed-sync-failure' AND completed_keys::text LIKE $1", [`%${id}%`]);+ const summary = async () => (await engine.executeRaw<{ s: Record<string, number> }>('SELECT completed_keys->0 AS s FROM op_checkpoints WHERE op=$1 AND fingerprint LIKE $2', [GIT_HOLD_SUMMARY_OP, `${id}:%`]))[0]?.s;+ const incarnation = async () => (await engine.executeRaw<{ incarnation: string }>('SELECT incarnation::text AS incarnation FROM sources WHERE id=$1', [id]))[0]!.incarnation;+ /** A maintenance write another process left unfinished on this source (a live claim nobody here sweeps), on `slug`; database-only, so it never sits in the worktree FIFO. */+ const unfinishedWrite = async (slug: string, pageId: number | null, path: string | null = null) => {+ const requestId = randomUUID();+ await engine.executeRaw(`INSERT INTO persistence_requests(principal_kind,principal_id,request_id,operation,source_id,source_incarnation,page_id,slug,digest,authority,intent,intent_bytes,terminal_reservation,+ state,execution_token,claim_expires_at)+ SELECT 'local_cli','cli:example',$2::uuid,'submit_job',$1,incarnation,$3,$4,'d','{}'::jsonb,$5::text::jsonb,1,16384,'running',gen_random_uuid(),now()+interval '1 hour' FROM sources WHERE id=$1`,+ [id, requestId, pageId, slug, JSON.stringify({ kind: 'managed_maintenance_adopt_fact_fence', ...(path ? { path } : {}) })]);+ return { requestId, finish: () => engine.executeRaw("UPDATE persistence_requests SET state='committed',execution_token=NULL,claim_expires_at=NULL,completed_at=now() WHERE request_id=$1::uuid", [requestId]) };+ };+ return { id, root, write, sync, holds, lastCommit, failedRequests, ledger, summary, incarnation, unfinishedWrite };+}++async function each(run: (engine: BrainEngine) => Promise<void>) {+ await withEnv(env, async () => {+ for (const engine of engines) {+ try { await run(engine); }+ finally { installFaultHook(undefined); await disposePersistenceConsumer(engine); await engine.unsetConfig('sync.holds'); }+ }+ });+}++const printed = (result: SyncResult) => { let out = ''; printSyncResult(result, { write: (text: string) => { out += text; return true; } } as NodeJS.WriteStream); return out; };+const expectRoutedToWriter = (fix: NonNullable<SyncResult['held']>[number]['fix'], id: string) => {+ expect(fix.argv).toEqual(['gbrain', 'sources', 'writer', 'status', '--source', id, '--json']);+ expect(fix.then?.argv).toEqual(['gbrain', 'sources', 'retry-held', id]);+ expect(fix.then?.then?.argv).toEqual(['gbrain', 'sync', '--source', id, '--no-pull', '--no-embed', '--no-extract']);+ expect(fix.docs).toBe('docs/guides/write-refusals.md#preparation_stalled');+ expect(JSON.stringify(fix)).not.toContain('repair frontmatter');+};++test('an import whose preparation stalls is held in the same run, the run finishes, and every surface routes it to writer status then retry-held and the same sync', () => each(async engine => {+ const s = await source(engine, { 'notes/a.md': note('A'), 'notes/stuck.md': note('Stuck'), 'notes/z.md': note('Z') });+ const probe = stallPaths(engine, s.id, new Set(['notes/stuck.md']));+ const head = git(s.root, 'rev-parse', 'HEAD');+ const result = await s.sync();+ expect(probe.fired).toEqual(['notes/stuck.md']);+ expect(result).toMatchObject({ status: 'first_sync', added: 2, held_count: 1, holds_outstanding: 1 });+ expect(await s.lastCommit()).toBe(head);+ expect(await engine.getPage('notes/stuck', { sourceId: s.id })).toBeNull();+ expect(await engine.getPage('notes/z', { sourceId: s.id })).not.toBeNull();+ const failed = await s.failedRequests();+ expect(failed).toEqual([expect.objectContaining({ error_code: 'preparation_stalled', state: 'failed', path: 'notes/stuck.md' })]);+ expect(result.converted_from_failed).toEqual([failed[0]!.request_id]);+ expect(await s.ledger()).toEqual([]);+ const [hold] = result.held!;+ expect(hold).toMatchObject({ path: 'notes/stuck.md', code: 'preparation_stalled', stale: false, docs: 'docs/guides/write-refusals.md#preparation_stalled' });+ expect(hold!.message).toContain(failed[0]!.request_id);+ expectRoutedToWriter(hold!.fix, s.id);+ expect(result.holds_fix!.argv).toEqual(['gbrain', 'sources', 'writer', 'status', '--source', s.id, '--json']);+ expect(result.holds_fix!.why).toContain('not file problems');+ for (const blob of [JSON.stringify(result), printed(result)]) expect(blob).not.toContain('repair frontmatter');+ // The stored record: the receipt, this gbrain's version, the resume arguments; the summary counts it under `stalled`.+ const [record] = await s.holds();+ expect(record).toMatchObject({ code: 'preparation_stalled', upstream_version: expect.any(String), meta: { stall: { request_id: failed[0]!.request_id, gbrain_version: VERSION,+ sync_argv: ['--source', s.id, '--no-pull', '--no-embed', '--no-extract'] } } });+ expect(record!.meta.deleted).toBeUndefined();+ expect(await s.summary()).toMatchObject({ count: 1, stalled: 1, fences: 0 });+ expect(coverageRoute((await readHeldCoverage(engine, { sourceId: s.id }))[0]!)).toEqual({ fences: 0, others: 0, stalled: 1 });+ // It waits: the next run neither re-screens the held bytes nor mints another receipt...+ expect(holdRescreenDue(record!, false)).toBe(false);+ expect(await s.sync()).toMatchObject({ status: 'up_to_date', holds_outstanding: 1 });+ expect(await s.failedRequests()).toHaveLength(1);+ // ...a different gbrain version would re-screen it...+ expect(holdRescreenDue({ code: 'preparation_stalled', meta: { ...record!.meta, stall: { ...record!.meta.stall!, gbrain_version: '0.0.1' } } }, false)).toBe(true);+ // ...doctor and retry-held route it the same way, and the retry's sync keeps the run's options.+ const check = await gitHeldFilesCheck(engine, [s.id]);+ expect(check.status).toBe('warn');+ expect(check.message).toContain('gbrain sources writer status --source ' + s.id);+ expect(check.message).not.toContain('repair frontmatter');+ const retry = await retryHeld(engine, s.id);+ expect(retry).toMatchObject({ scheduled: 1, items: [{ key: 'notes/stuck.md', code: 'preparation_stalled' }] });+ expect(retry.fix!.argv).toEqual(['gbrain', 'sync', '--source', s.id, '--no-pull', '--no-embed', '--no-extract']);+ expect(retry.next_action).not.toContain('repair frontmatter');+ // With the cause gone, the scheduled re-screen imports the file and clears the hold.+ installFaultHook(undefined);+ expect(await s.sync()).toMatchObject({ status: 'synced', added: 1 });+ expect(await engine.getPage('notes/stuck', { sourceId: s.id })).not.toBeNull();+ expect(await s.holds()).toEqual([]);+ expect(await s.summary()).toMatchObject({ count: 0, stalled: 0 });+}), 180_000);++test('a stalled delete becomes a delete hold (no bytes); the page stays until retry-held and the same sync delete it', () => each(async engine => {+ const s = await source(engine, { 'notes/keep.md': note('Keep'), 'notes/gone.md': note('Gone') });+ expect((await s.sync()).status).toBe('first_sync');+ unlinkSync(join(s.root, 'notes/gone.md')); s.write('notes/new.md', note('New'));+ const head = commit(s.root, 'delete one, add one');+ stallPaths(engine, s.id, new Set(['notes/gone.md']));+ const result = await s.sync();+ expect(result).toMatchObject({ status: 'synced', added: 1, deleted: 0, held_count: 1 });+ expect(await s.lastCommit()).toBe(head);+ expect(await engine.getPage('notes/gone', { sourceId: s.id })).not.toBeNull();+ const [record] = await s.holds();+ expect(record).toMatchObject({ path: 'notes/gone.md', code: 'preparation_stalled', upstream_version: null, page_id: expect.any(Number), meta: { deleted: true } });+ expect(result.held![0]!.fix.why).toContain('its deletion could not finish preparing');+ expectRoutedToWriter(result.held![0]!.fix, s.id);+ // The absent file is not "a change": the hold waits instead of re-admitting the delete every run.+ expect(await s.sync()).toMatchObject({ status: 'up_to_date', holds_outstanding: 1 });+ expect(await s.failedRequests()).toHaveLength(1);+ installFaultHook(undefined);+ await retryHeld(engine, s.id);+ expect(await s.sync()).toMatchObject({ status: 'synced', deleted: 1 });+ expect(await engine.getPage('notes/gone', { sourceId: s.id })).toBeNull();+ expect(await s.holds()).toEqual([]);+}), 180_000);++test('a stalled rename holds the destination with its origin; the hold gate locks both endpoints; a stalled checkpoint never holds', () => each(async engine => {+ const s = await source(engine, { 'notes/old.md': note('Old'), 'notes/other.md': note('Other') });+ expect((await s.sync()).status).toBe('first_sync');+ renameSync(join(s.root, 'notes/old.md'), join(s.root, 'notes/new.md'));+ commit(s.root, 'rename');+ stallPaths(engine, s.id, new Set(['notes/new.md']));+ const result = await s.sync();+ expect(result).toMatchObject({ status: 'synced', renamed: 0, held_count: 1 });+ const [record] = await s.holds();+ expect(record).toMatchObject({ path: 'notes/new.md', code: 'preparation_stalled', meta: { rename_from: { slug: 'notes/old' } } });+ expect(await engine.getPage('notes/old', { sourceId: s.id })).not.toBeNull();+ expect(await engine.getPage('notes/new', { sourceId: s.id })).toBeNull();+ // The checkpoint request is never held: a stall there blocks the run with the typed failure.+ installFaultHook(undefined);+ s.write('notes/more.md', note('More')); commit(s.root, 'more');+ installFaultHook(async (at, detail) => {+ if (at !== 'consumer:prepared' || detail.sourceId !== s.id || !detail.requestId) return;+ const [row] = await engine.executeRaw<{ kind: string }>("SELECT intent->>'kind' AS kind FROM persistence_requests WHERE request_id=$1::uuid", [detail.requestId]);+ if (row?.kind === 'managed_sync_checkpoint') throw new OperationError('preparation_stalled', 'The checkpoint did not finish preparing (forced probe).', 'Inspect the writer.');+ });+ const blocked = await s.sync();+ expect(blocked).toMatchObject({ status: 'blocked_by_failures', failureCodes: [{ code: 'preparation_stalled', count: 1 }] });+ expect(blocked.managedWrite).toMatchObject({ write_error: 'preparation_stalled' });+ expect(await s.holds()).toHaveLength(1);+}), 180_000);++test('sync.holds=fail keeps blocking with the typed receipt; the next run after holds are on converts it at its start (a kill before the cursor consumed the failure)', () => each(async engine => {+ await engine.setConfig('sync.holds', 'fail');+ const s = await source(engine, { 'notes/a.md': note('A'), 'notes/stuck.md': note('Stuck') });+ stallPaths(engine, s.id, new Set(['notes/stuck.md']));+ const blocked = await s.sync();+ expect(blocked).toMatchObject({ status: 'blocked_by_failures', failureCodes: [{ code: 'preparation_stalled', count: 1 }] });+ expect(blocked.managedWrite?.write_error).toBe('preparation_stalled');+ expect(await s.holds()).toEqual([]);+ expect(await s.ledger()).toHaveLength(1);+ const [failed] = await s.failedRequests();+ // The cursor is still pending on the failed receipt (as after a watchdog kill): the next run with holds on converts it before admitting anything.+ await engine.unsetConfig('sync.holds');+ installFaultHook(undefined);+ const converted = await s.sync();+ expect(converted).toMatchObject({ status: 'first_sync', held_count: 1, converted_from_failed: [failed!.request_id] });+ expect(converted.held![0]).toMatchObject({ path: 'notes/stuck.md', code: 'preparation_stalled' });+ expect(await engine.getPage('notes/a', { sourceId: s.id })).not.toBeNull();+ expect(await s.failedRequests()).toHaveLength(1);+}), 180_000);++test('narrowed gate: an unfinished maintenance write on another page of the same source no longer blocks the hold; one on the same page still does', () => each(async engine => {+ const s = await source(engine, { 'notes/a.md': note('A'), 'notes/stuck.md': note('Stuck'), 'notes/other.md': note('Other') });+ expect((await s.sync()).status).toBe('first_sync');+ const other = (await engine.readPageSnapshot('notes/other', { sourceId: s.id }))!.page.id;+ const stuck = (await engine.readPageSnapshot('notes/stuck', { sourceId: s.id }))!.page.id;+ s.write('notes/stuck.md', note('Stuck v2')); s.write('notes/a.md', note('A v2'));+ commit(s.root, 'edit two');+ // Before this change the source-wide gate returned writer_pending for as long as any request on the source was unfinished.+ const unrelated = await s.unfinishedWrite('notes/other', other);+ stallPaths(engine, s.id, new Set(['notes/stuck.md']));+ const started = performance.now();+ const result = await s.sync();+ expect(performance.now() - started).toBeLessThan(4000);+ expect(result).toMatchObject({ status: 'synced', modified: 1, held_count: 1 });+ expect(result.held![0]).toMatchObject({ path: 'notes/stuck.md', code: 'preparation_stalled', stale: true });+ await unrelated.finish();+ // Same page, by page id: the hold waits for it, and the run yields writer_pending within its wait budget.+ installFaultHook(undefined);+ await retryHeld(engine, s.id);+ s.write('notes/stuck.md', note('Stuck v3')); commit(s.root, 'edit again');+ const samePage = await s.unfinishedWrite('notes/stuck', stuck);+ stallPaths(engine, s.id, new Set(['notes/stuck.md']));+ const pending = await s.sync();+ expect(pending).toMatchObject({ status: 'partial', reason: 'writer_pending' });+ expect(await s.holds()).toHaveLength(1);+ expect((await s.holds())[0]!.meta.stall!.request_id).not.toBe((await s.failedRequests()).at(-1)!.request_id);+ // Once it settles, the next pass holds the entry from the same failed receipt without a new request.+ await samePage.finish();+ const before = (await s.failedRequests()).length;+ const held = await s.sync();+ expect(held).toMatchObject({ status: 'synced', held_count: 1 });+ expect((await s.failedRequests()).length).toBe(before);+ expect((await s.holds())[0]!.meta.stall!.request_id).toBe((await s.failedRequests()).at(-1)!.request_id);+ // The same-path match also works for a write that names the file rather than the slug.+ installFaultHook(undefined);+ await retryHeld(engine, s.id);+ s.write('notes/stuck.md', note('Stuck v4')); commit(s.root, 'edit once more');+ const byPath = await s.unfinishedWrite('elsewhere/slug', null, 'notes/stuck.md');+ stallPaths(engine, s.id, new Set(['notes/stuck.md']));+ expect(await s.sync()).toMatchObject({ status: 'partial', reason: 'writer_pending' });+ await byPath.finish();+ expect(await s.sync()).toMatchObject({ status: 'synced', held_count: 1 });+}), 240_000);++test('bulk groups: a stalled first, middle or last member is held, the committed prefix stays, the rest is re-frozen and the run finishes in one invocation', () => each(async engine => {+ if (engine.kind !== 'postgres') return;+ for (const position of ['first', 'middle', 'last'] as const) {+ const files: Record<string, string> = {};+ for (let i = 0; i < 7; i++) files[`notes/n${i}.md`] = note(`N${i}`);+ const s = await source(engine, files);+ const target = position === 'first' ? 'notes/n0.md' : position === 'middle' ? 'notes/n3.md' : 'notes/n6.md';+ stallPaths(engine, s.id, new Set([target]), 'publication:before_commit');+ const head = git(s.root, 'rev-parse', 'HEAD');+ const result = await s.sync({ bulk: { enabled: true, reason: null, size: 8, maxTxnMs: 15_000 } });+ expect(result).toMatchObject({ status: 'first_sync', added: 6, held_count: 1 });+ expect(result.held![0]).toMatchObject({ path: target, code: 'preparation_stalled' });+ expect(await s.lastCommit()).toBe(head);+ expect(await s.ledger()).toEqual([]);+ const [grouped] = await engine.executeRaw<{ n: number }>("SELECT count(*)::int AS n FROM persistence_requests WHERE source_id=$1 AND intent->>'path'=$2 AND intent ? 'group'", [s.id, target]);+ expect(grouped!.n).toBeGreaterThan(0);+ // Every other member committed (cancelled followers were re-frozen under new requests) and the checkpoint found none incomplete.+ for (let i = 0; i < 7; i++) expect(await engine.getPage(`notes/n${i}`, { sourceId: s.id }) === null).toBe(`notes/n${i}.md` === target);+ installFaultHook(undefined);+ await disposePersistenceConsumer(engine);+ }+}), 300_000);++test('preparationStallMeta keeps the receipt step vocabulary only and tolerates receipts without detail', () => {+ const full = preparationStallMeta({ request_id: 'r1', error_detail: { step: 'origin_check', waiting_on: 'db', attempts: 2, message: 'never stored' } }, ['--source', 'x', '--no-pull']);+ expect(full).toEqual({ request_id: 'r1', step: 'origin_check', waiting_on: 'db', attempts: 2, gbrain_version: VERSION, sync_argv: ['--source', 'x', '--no-pull'] });+ expect(preparationStallMeta({ request_id: 'r2', error_detail: null }, [])).toMatchObject({ step: null, waiting_on: null, attempts: null });+ expect(preparationStallMeta({ request_id: 'r3', error_detail: { waiting_on: 'lock', step: 42 } }, [])).toMatchObject({ step: null, waiting_on: null });+});diff --git a/test/persistence-managed-sync.test.ts b/test/persistence-managed-sync.test.tsindex 6a90cc7ed8..ac2ce6af25 100644--- a/test/persistence-managed-sync.test.ts+++ b/test/persistence-managed-sync.test.ts@@ -736,7 +736,7 @@ test.each(['restore', 'rename', 'database-only'] as const)('an unfinished %s reqslug: kind === 'rename' ? 'a-renamed' : 'a', pageId: kind === 'rename' ? null : page.id,worktreeId: kind === 'database-only' ? null : binding.worktree_id, topologyGeneration: kind === 'database-only' ? null : binding.topology_generation,principal: authority.writer.principal, authority: authority.writer, callerIntent: intent, intent });- expect(await engine.executeRaw(UNFINISHED_PAGE_REQUEST_SQL, [binding.worktree_id, binding.source_incarnation, f.id, 'a', page.id, String(page.id)])).toHaveLength(1);+ expect(await engine.executeRaw(UNFINISHED_PAGE_REQUEST_SQL, [binding.worktree_id, binding.source_incarnation, f.id, 'a', page.id, String(page.id), 'a.md', 'a.md'])).toHaveLength(1);const abort = new AbortController();const admitted = waitFor(async () => (await deleteRequests(engine, f.id)).length > 0, { timeoutMs: 30_000 }).then(() => abort.abort());const result = await performManagedSync(engine, { sourceId: f.id, ...WAIVER_OPTS, signal: abort.signal });@@ -864,7 +864,7 @@ test('the waiver lookup for unfinished page requests is served by the request inconst plan = await engine.transaction(async tx => {await tx.executeRaw('SET LOCAL enable_seqscan=off');return tx.executeRaw<Record<string, string>>(`EXPLAIN ${UNFINISHED_PAGE_REQUEST_SQL}`,- [randomUUID(), randomUUID(), 'example-source', 'notes/example', 1, '1']);+ [randomUUID(), randomUUID(), 'example-source', 'notes/example', 1, '1', 'notes/example.md', 'notes/example.md']);});const text = plan.map(row => Object.values(row)[0]).join('\n');// Every branch (worktree pending, worktree recovery, database-only pending) is an index scan; the planner may