Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(sync): show the options that own a stuck managed cursor in the retry hint (#5480)

time-attack3f33ef25346d
diff --git a/src/commands/doctor/checks/sync-failures.ts b/src/commands/doctor/checks/sync-failures.ts
index e4e2b962cc..a4564f06eb 100644
--- a/src/commands/doctor/checks/sync-failures.ts
+++ b/src/commands/doctor/checks/sync-failures.ts
@@ -1,7 +1,7 @@
import type { BrainEngine } from '../../../core/engine.ts';
import type { Check } from '../../doctor.ts';
import { loadSyncFailures, unacknowledgedSyncFailures, decideSyncFailureSeverity, type SyncFailure } from '../../../core/sync-failure-ledger.ts';
-import { formatManagedSyncFailure, readManagedSyncFailures } from '../../../core/persistence/sync-failures.ts';
+import { formatManagedSyncFailure, managedSyncRetryCommand, readManagedSyncFailures } from '../../../core/persistence/sync-failures.ts';
import { resolveHoursEnv } from '../../../core/env-number.ts';
import { makeRemediationStep } from '../../../core/remediation-step.ts';
@@ -31,8 +31,9 @@ export async function checkSyncFailures(engine: BrainEngine | null, opts: { sour
oldest_failure: unresolvedLegacy.map(row => row.ts).sort()[0] },
severity: severity.status === 'fail' ? 'high' : 'medium', est_seconds: 30, est_usd_cost: 0,
rationale: `Retry ${severity.unresolved} unresolved sync failure(s)` })];
+ const retries = [...new Set(managed.map(row => managedSyncRetryCommand(row)))];
const recovery = requiresManagedRetry
- ? 'Fix the cause, then run gbrain sync --no-pull --retry-failed with the same source and options. Completed full runs do not resolve a different unfinished cursor.'
+ ? `Fix the cause, then run ${retries.length ? retries.join(' ; ') : 'gbrain sync --no-pull --retry-failed with the same source and options'}. Completed full runs do not resolve a different unfinished cursor.`
: "Fix the file(s) and re-run 'gbrain sync', or use 'gbrain sync --skip-failed' to acknowledge legacy file failures.";
return { name: 'sync_failures', status: severity.status, message: `${summary} ${details.join('; ')} ${recovery}`,
remediation, remediation_status: remediation ? 'remediable' : 'blocked', ...(engine ? {} : { message: `${summary} Durable sync state is unavailable without a database connection; the local ledger is only a compatibility mirror.` }) };
diff --git a/src/commands/sync/report.ts b/src/commands/sync/report.ts
index 2be063560c..95e6768966 100644
--- a/src/commands/sync/report.ts
+++ b/src/commands/sync/report.ts
@@ -1,5 +1,5 @@
/** Post-sync human reporting and best-effort nudges for the sync CLI. */
-import { formatManagedSyncFailure } from '../../core/persistence/sync-failures.ts';
+import { formatManagedSyncFailure, managedSyncRetryCommand } from '../../core/persistence/sync-failures.ts';
import type { BrainEngine } from '../../core/engine.ts';
import { isEmbeddingInfraCode } from '../../core/sync.ts';
import { serr } from '../../core/console-prefix.ts';
@@ -126,7 +126,10 @@ export function printSyncResult(result: SyncResult, sink: NodeJS.WriteStream = p
if (result.runId) {
write(`Sync BLOCKED at ${result.toCommit}: committed counts are cumulative for run ${result.runId}.`);
for (const failure of result.failures ?? []) write(` ${formatManagedSyncFailure(failure)}`);
- write(' Fix the cause, then run gbrain sync --no-pull --retry-failed with the same source and options; this admits a fresh run after active work drains.');
+ const retries = [...new Set((result.failures ?? []).map(failure => managedSyncRetryCommand(failure)))];
+ write(retries.length
+ ? ` Fix the cause, then run: ${retries.join(' ; ')} (this admits a fresh run after active work drains).`
+ : ' Fix the cause, then run gbrain sync --no-pull --retry-failed with the same source and options; this admits a fresh run after active work drains.');
break;
}
write(`Sync BLOCKED at ${result.toCommit.slice(0, 8)}: ${result.failedFiles ?? 0} file(s) failed.`);
diff --git a/src/commands/sync/run.ts b/src/commands/sync/run.ts
index b8bd3372b9..8f5b2523a3 100644
--- a/src/commands/sync/run.ts
+++ b/src/commands/sync/run.ts
@@ -4,7 +4,8 @@ import { getCompanyBrainProfile } from '../../core/company-brain/profile.ts';
import { slog, withSourcePrefix } from '../../core/console-prefix.ts';
import type { BrainEngine } from '../../core/engine.ts';
import { msysToNativePath } from '../../core/path-confine.ts';
-import { syncFailureJsonFields, readManagedSyncFailures } from '../../core/persistence/sync-failures.ts';
+import { syncFailureJsonFields, readManagedSyncFailures, managedSyncRetryCommand } from '../../core/persistence/sync-failures.ts';
+import { managedSyncCursorKey } from '../../core/persistence/sync-run.ts';
import { syncHoldJsonFields } from '../../core/persistence/sync-holds.ts';
import { printHoldNotes } from '../sync-diagnostics.ts';
import { getDefaultSourcePath } from '../../core/source-resolver.ts';
@@ -786,8 +787,19 @@ async function runSingleSourceSync(
// v0.42.42.0 (#2139, D13C): scope the retry count to THIS source — rows
// carry source_id (#1939), so a single-source retry shouldn't report
// another source's failures.
+ // A managed retry resumes only the cursor its own options select; failures under other options are named, not counted.
const [brain] = await engine.executeRaw<{ enabled: boolean }>('SELECT enabled FROM persistence_brain WHERE singleton=1');
- const failures = brain?.enabled ? await readManagedSyncFailures(engine, [sourceId]) : unacknowledgedSyncFailures().filter(f => f.source_id === sourceId);
+ let failures: Array<{ source_id: string }> = unacknowledgedSyncFailures().filter(f => f.source_id === sourceId);
+ if (brain?.enabled) {
+ const managed = await readManagedSyncFailures(engine, [sourceId]);
+ const key = await managedSyncCursorKey(engine, opts).catch(() => null);
+ const other = key ? managed.filter(f => f.cursor_key !== key) : [];
+ failures = key ? managed.filter(f => f.cursor_key === key) : managed;
+ if (other.length) {
+ slog(`${other.length} previously-failed file(s) of this source belong to a run with different sync options and are not retried by this invocation. Retry them with:`);
+ for (const command of new Set(other.map(f => managedSyncRetryCommand(f)))) slog(` ${command}`);
+ }
+ }
if (failures.length === 0) {
slog('No local ledger entries; checking the durable sync cursor for unfinished or failed writes.');
} else {
diff --git a/src/core/persistence/sync-failures.ts b/src/core/persistence/sync-failures.ts
index 9b494707e9..ac7ce46a8f 100644
--- a/src/core/persistence/sync-failures.ts
+++ b/src/core/persistence/sync-failures.ts
@@ -1,6 +1,9 @@
import type { BrainEngine } from '../engine.ts';
import { mirrorManagedSyncFailure, clearManagedSyncFailure } from '../sync-failure-ledger.ts';
import type { WriteRequest } from './model.ts';
+import { checkpointRetryCommand } from './checkpoint-validation.ts';
+import type { SyncProcessingOptions } from './sync-authority.ts';
+import type { SyncCursorOptions } from './sync-prepare.ts';
export interface ManagedSyncFailure {
source_id: string;
@@ -17,6 +20,9 @@ export interface ManagedSyncFailure {
observation_id: string;
first_seen: string;
attempts: number;
+ /** The cursor-selecting options of the failed run; absent on failures recorded before they were kept. */
+ syncOptions?: SyncCursorOptions;
+ processingOptions?: Partial<SyncProcessingOptions>;
}
export async function recordManagedSyncFailure(engine: BrainEngine, value: Omit<ManagedSyncFailure, 'first_seen' | 'attempts'> & { first_seen?: string }): Promise<{ failure: ManagedSyncFailure; ledgerRecorded: boolean }> {
@@ -48,10 +54,12 @@ export async function clearManagedSyncFailureAfterSuccess(engine: BrainEngine, k
}
export async function readManagedSyncFailures(engine: BrainEngine, sourceIds?: string[]): Promise<ManagedSyncFailure[]> {
- const rows = await engine.executeRaw<{ cursor_key: string; value: { sourceId: string; incarnation: string; runId: string; index: number; target: string; pending?: { requestId: string } };
+ const rows = await engine.executeRaw<{ cursor_key: string; value: { sourceId: string; incarnation: string; runId: string; index: number; target: string; pending?: { requestId: string };
+ syncOptions: SyncCursorOptions | null; processingOptions: Partial<SyncProcessingOptions> | null };
receipt: Pick<WriteRequest, 'state' | 'request_id' | 'error_code' | 'error_message'> | null; failure: ManagedSyncFailure | null; path: string | null; updated_at: string }>(`
SELECT c.fingerprint AS cursor_key,jsonb_build_object('sourceId',s.id,'incarnation',s.incarnation,'runId',c.completed_keys->0->>'runId',
'index',c.completed_keys->0->'index','target',c.completed_keys->0->>'target',
+ 'syncOptions',c.completed_keys->0->'syncOptions','processingOptions',c.completed_keys->0->'processingOptions',
'pending',jsonb_build_object('requestId',c.completed_keys->0->'pending'->>'requestId')) AS value,
CASE WHEN r.id IS NULL THEN NULL ELSE jsonb_build_object('state',r.state,'request_id',r.request_id,'error_code',r.error_code,'error_message',r.error_message) END AS receipt,
f.completed_keys->0 AS failure,m.completed_keys->((c.completed_keys->0->>'index')::int)->>'path' AS path,c.updated_at
@@ -66,8 +74,9 @@ export async function readManagedSyncFailures(engine: BrainEngine, sourceIds?: s
AND ($1::text[] IS NULL OR s.id=ANY($1::text[]))`, [sourceIds ?? null]);
const failures: ManagedSyncFailure[] = rows.map(row => {
const c = row.value, r = row.receipt;
- if (row.failure && (!r || !['failed', 'conflict', 'cancelled'].includes(r.state) || row.failure.request_id === r.request_id)) return row.failure;
- return { source_id: c.sourceId, source_incarnation: c.incarnation, path: row.path ?? '<checkpoint>', code: r?.error_code ?? 'sync_incomplete',
+ const options = { ...(c.syncOptions ? { syncOptions: c.syncOptions } : {}), ...(c.processingOptions ? { processingOptions: c.processingOptions } : {}) };
+ if (row.failure && (!r || !['failed', 'conflict', 'cancelled'].includes(r.state) || row.failure.request_id === r.request_id)) return { ...options, ...row.failure };
+ return { ...options, source_id: c.sourceId, source_incarnation: c.incarnation, path: row.path ?? '<checkpoint>', code: r?.error_code ?? 'sync_incomplete',
message: r?.error_message ?? 'The durable sync cursor is unfinished; resume the accepted run.', request_id: c.pending?.requestId ?? null,
run_id: c.runId, target: c.target, cursor_key: row.cursor_key, phase: r ? 'receipt' : 'resume', state: r?.state ?? 'unfinished',
observation_id: c.pending?.requestId ?? `${c.runId}:${c.index}`, first_seen: new Date(row.updated_at).toISOString(), attempts: 1 };
@@ -85,6 +94,11 @@ export function formatManagedSyncFailure(failure: ManagedSyncFailure): string {
return `source=${clean(failure.source_id)} path=${clean(failure.path)} code=${clean(failure.code)}: ${clean(failure.message)} request=${failure.request_id ?? '<not-admitted>'} run=${failure.run_id} target=${failure.target ?? '<undiscovered>'}`;
}
+/** The retry for one managed failure: same source and recorded cursor-selecting options, or an honest note when they were not recorded. */
+export function managedSyncRetryCommand(failure: ManagedSyncFailure, repoPath?: string | null): string {
+ return checkpointRetryCommand({ sourceId: failure.source_id, processingOptions: failure.processingOptions, syncOptions: failure.syncOptions ?? null, repoPath });
+}
+
export function syncFailureJsonFields(result: { failedFiles?: number; failureCodes?: Array<{ code: string; count: number }>; failures?: ManagedSyncFailure[]; runId?: string; fromCommit?: string | null; toCommit?: string; bankedFiles?: number }): Record<string, unknown> {
return { ...(result.failedFiles !== undefined ? { failed_files: result.failedFiles } : {}),
...(result.failureCodes ? { failure_codes: result.failureCodes } : {}), ...(result.failures ? { failures: result.failures } : {}),
diff --git a/src/core/persistence/sync-run.ts b/src/core/persistence/sync-run.ts
index 17cce193f8..d896fc452b 100644
--- a/src/core/persistence/sync-run.ts
+++ b/src/core/persistence/sync-run.ts
@@ -23,7 +23,7 @@ import { currentCompanyBrainSync, getCompanyBrainProfile, readCompanyBrainPlan }
import { readCommittedBlob } from '../company-brain/revision.ts';
import { refreshProjectionStatistics } from '../search/projection-statistics.ts';
import { importAnalyzeEveryPages, maybeRefreshPlannerStats } from '../planner-stats.ts';
-import { recordManagedSyncFailure, clearManagedSyncFailureAfterSuccess, formatManagedSyncFailure, type ManagedSyncFailure } from './sync-failures.ts';
+import { recordManagedSyncFailure, clearManagedSyncFailureAfterSuccess, formatManagedSyncFailure, managedSyncRetryCommand, type ManagedSyncFailure } from './sync-failures.ts';
import { writeFailureDiagnostic } from './verb-errors.ts';
import { extractManagedStaleLinks } from './links-maintenance.ts';
import { CHECKPOINT_VALIDATION_TIMEOUT, checkpointRetryCommand, checkpointTimeoutHint } from './checkpoint-validation.ts';
@@ -221,7 +221,7 @@ function writeDiagnostic(cursor: Cursor, pending: Pending, row: WriteRequest): M
};
const diagnostic: ManagedSyncWriteDiagnostic = { source_id: cursor.sourceId, slug: pending.slug,
path: pending.intent.path, write_error: code, ...detail, write_request: publicWriteReceipt(receiptFor(row)) };
- if (terminal) diagnostic.suggestion += ' After repair, run gbrain sync with the same source/options and --retry-failed to start a new request. Without --retry-failed, the frozen terminal request returns the same outcome. Skipping failures cannot bypass a managed write.';
+ if (terminal) diagnostic.suggestion += ` After repair, run ${checkpointRetryCommand({ sourceId: cursor.sourceId, processingOptions: cursor.processingOptions, syncOptions: cursor.syncOptions ?? null, repoPath: pending.intent.repoPath })} to start a new request. Without --retry-failed, the frozen terminal request returns the same outcome. Skipping failures cannot bypass a managed write.`;
if (diagnostic.reason === 'pinned_git_worktree_conflict' && pending.intent.path && pending.intent.content !== null) {
try {
const bytes = readSyncFile(cursor.root, pending.intent.path);
@@ -614,6 +614,22 @@ interface HoldRunState { sourceId?: string; incarnation?: string; remote?: boole
* One immutable page is admitted at a time; foreground writes can never sit behind a whole scan.
* #5988: every result (resumed, no-change and blocked runs included) carries this run's holds and the source's outstanding total.
*/
+
+/** The cursor-selecting options of a managed run; part of its durable cursor key. */
+function cursorSyncOptions(opts: SyncOpts): SyncCursorOptions {
+ return { full: opts.full ?? false, workingTree: opts.workingTree ?? false, srcSubpath: opts.srcSubpath ?? null,
+ exclude: opts.exclude ?? [], includeHidden: opts.includeHidden ?? [], strategy: opts.strategy ?? null };
+}
+function managedCursorKey(incarnation: string, authority: SyncAuthority, company: ReturnType<typeof currentCompanyBrainSync>, syncOptions: SyncCursorOptions): string {
+ return digest({ source: incarnation, principal: authority.writer.principal, authority, ...(company ? { company: { receiptId: company.receiptId, planDigest: company.plan.plan_digest } } : {}),
+ options: syncOptions });
+}
+/** The durable cursor key performManagedSync would use for these options, so --retry-failed can count only the failures it retries. */
+export async function managedSyncCursorKey(engine: BrainEngine, opts: SyncOpts): Promise<string> {
+ const context = await resolveManagedSyncContext(engine, opts);
+ const authority = await managedSyncAuthority(engine, context.sourceId, context.incarnation, opts.repoPath ?? context.root);
+ return managedCursorKey(context.incarnation, authority, currentCompanyBrainSync(context.sourceId), cursorSyncOptions(opts));
+}
export async function performManagedSync(engine: BrainEngine, opts: SyncOpts, slice?: { maxPages: number; maxMs: number }): Promise<SyncResult> {
const state: HoldRunState = {};
const synced = await runManagedSync(engine, opts, slice, state);
@@ -643,12 +659,10 @@ async function runManagedSync(engine: BrainEngine, opts: SyncOpts, slice: { maxP
const authority = await managedSyncAuthority(engine, context.sourceId, context.incarnation, opts.repoPath ?? context.root);
const company = currentCompanyBrainSync(context.sourceId);
const processingOptions = syncProcessingOptions(opts);
- const syncOptions: SyncCursorOptions = { full: opts.full ?? false, workingTree: opts.workingTree ?? false, srcSubpath: opts.srcSubpath ?? null,
- exclude: opts.exclude ?? [], includeHidden: opts.includeHidden ?? [], strategy: opts.strategy ?? null };
+ const syncOptions = cursorSyncOptions(opts);
const frozenRun: { syncOptions: SyncCursorOptions; repoPath?: string; screen?: SyncScreenRun | null; observedAt?: string } = { syncOptions, ...(opts.repoPath ? { repoPath: resolve(opts.repoPath) } : {}) };
const runStartedAt = new Date().toISOString();
- const key = digest({ source: context.incarnation, principal: authority.writer.principal, authority, ...(company ? { company: { receiptId: company.receiptId, planDigest: company.plan.plan_digest } } : {}),
- options: syncOptions });
+ const key = managedCursorKey(context.incarnation, authority, company, syncOptions);
let cursor: Cursor | null = null;
let missingManifestCursor: CursorHeader | null = null;
if (!company) Object.assign(state, { sourceId: context.sourceId, incarnation: context.incarnation, remote: authority.writer.remote, cursor: () => cursor });
@@ -869,6 +883,7 @@ async function runManagedSync(engine: BrainEngine, opts: SyncOpts, slice: { maxP
const { failure, ledgerRecorded } = await recordManagedSyncFailure(engine, { source_id: cursor.sourceId, source_incarnation: cursor.incarnation, path: pending.intent.path ?? '<checkpoint>',
code: done.error_code ?? (done.state === 'cancelled' ? 'cancelled' : 'storage_error'), message: done.error_message ?? 'The accepted sync request did not commit.',
request_id: pending.requestId, run_id: cursor.runId, target: cursor.target, cursor_key: key,
+ syncOptions: cursor.syncOptions ?? syncOptions, processingOptions: cursor.processingOptions ?? processingOptions,
phase: pending.intent.kind === 'managed_sync_checkpoint' ? 'checkpoint' : 'receipt', state: done.state, observation_id: pending.requestId,
first_seen: new Date(done.completed_at ?? done.updated_at).toISOString() });
// #5762: the hint is built after the failed transaction, from a fresh read of the request indexes.
@@ -923,9 +938,10 @@ async function runManagedSync(engine: BrainEngine, opts: SyncOpts, slice: { maxP
const failedCursor = cursor ?? stored?.completed_keys?.[0];
const { failure } = await recordManagedSyncFailure(engine, { source_id: context.sourceId, source_incarnation: context.incarnation, path: cursor?.entries[cursor.index]?.path ?? failedCursor?.pending?.intent.path ?? `<${phase}>`, code,
message: error instanceof Error ? error.message : String(error), request_id: failedCursor?.pending?.requestId ?? null,
- run_id: failedCursor?.runId ?? discoveryRun, target: failedCursor?.target ?? discoveryTarget, cursor_key: key, phase, state: 'failed',
+ run_id: failedCursor?.runId ?? discoveryRun, target: failedCursor?.target ?? discoveryTarget, cursor_key: key,
+ syncOptions: failedCursor?.syncOptions ?? syncOptions, processingOptions: failedCursor?.processingOptions ?? processingOptions, phase, state: 'failed',
observation_id: failedCursor ? `${failedCursor.runId}:${failedCursor.index}:${phase}:${code}` : `${key}:discovery:${discoveryTarget}:${code}` });
- if (error instanceof Error) error.message = authority.writer.remote ? 'Managed sync is blocked; ask the host operator to inspect doctor.' : formatManagedSyncFailure(failure) + ' Fix the cause, then run gbrain sync --no-pull --retry-failed with the same source and options.';
+ if (error instanceof Error) error.message = authority.writer.remote ? 'Managed sync is blocked; ask the host operator to inspect doctor.' : `${formatManagedSyncFailure(failure)} Fix the cause, then run: ${managedSyncRetryCommand(failure, frozenRun.repoPath)}`;
}
}
throw error;
diff --git a/test/persistence-sync-failures.serial.test.ts b/test/persistence-sync-failures.serial.test.ts
index d0042269af..47942d0968 100644
--- a/test/persistence-sync-failures.serial.test.ts
+++ b/test/persistence-sync-failures.serial.test.ts
@@ -221,6 +221,82 @@ test('full sync cannot hide an older failed incremental cursor or repeat its com
}
}), 120_000);
+const QUOTED_EXCLUDE = "it's a dir/**";
+async function captureCli(fn: () => unknown): Promise<string> {
+ const originalLog = console.log, originalWrite = process.stdout.write, originalErr = process.stderr.write, originalExit = process.exit;
+ let out = '';
+ console.log = (...args: unknown[]) => { out += args.join(' ') + '\n'; };
+ process.stdout.write = ((value: unknown) => { out += String(value); return true; }) as typeof process.stdout.write;
+ process.stderr.write = ((value: unknown) => { out += String(value); return true; }) as typeof process.stderr.write;
+ process.exit = ((code?: number) => { throw new Error(`fixture-cli-exit ${code}`); }) as typeof process.exit;
+ try { await fn(); } catch (error) { if (!String((error as Error).message).startsWith('fixture-cli-exit')) throw error; }
+ finally {
+ console.log = originalLog; process.stdout.write = originalWrite; process.stderr.write = originalErr; process.exit = originalExit;
+ _resetCliExitVerdictForTests(); process.exitCode = 0;
+ }
+ return out;
+}
+
+test('managed failure retry hints name the failed cursor options locally, shell-quoted, and stay redacted remotely', async () => withEnv({ ...env, GBRAIN_BACKUP_CHECK: 'off', GBRAIN_SYNC_NO_EXTRACT_NUDGE: '1' }, async () => {
+ for (const engine of engines) {
+ const f = await fixture(engine, { 'bad.md': '---\ntitle: [broken\n---\nRetry hint fixture.\n' });
+ const blocked = await performManagedSync(engine, { sourceId: f.id, noPull: true, noEmbed: true, full: true, exclude: [QUOTED_EXCLUDE] });
+ expect(blocked.status).toBe('blocked_by_failures');
+ const recorded = { full: true, workingTree: false, srcSubpath: null, exclude: [QUOTED_EXCLUDE], includeHidden: [], strategy: null };
+ expect(blocked.failures).toEqual([expect.objectContaining({ syncOptions: recorded, processingOptions: expect.objectContaining({ noEmbed: true }) })]);
+ expect(await readManagedSyncFailures(engine, [f.id])).toEqual([expect.objectContaining({ syncOptions: recorded })]);
+ const retry = `gbrain sync --source ${f.id} --no-pull --retry-failed --no-embed --full --exclude 'it'\\''s a dir/**'`;
+
+ const local = await checkSyncFailures(engine, { sourceIds: [f.id], remote: false });
+ expect(local?.message).toContain(`Fix the cause, then run ${retry}.`);
+ expect(local?.message).not.toContain('with the same source and options');
+ const remote = await checkSyncFailures(engine, { sourceIds: [f.id], remote: true });
+ expect(remote?.message).not.toContain(QUOTED_EXCLUDE);
+ expect(remote?.message).not.toContain('--exclude');
+
+ const printed = await captureCli(() => printSyncResult(blocked));
+ expect(printed).toContain(`After repair, run ${retry} to start a new request.`);
+ const { managedWrite: _diagnostic, ...bare } = blocked;
+ const printedBare = await captureCli(() => printSyncResult(bare));
+ expect(printedBare).toContain(`Fix the cause, then run: ${retry} (this admits a fresh run after active work drains).`);
+
+ const legacy = { ...blocked.failures![0] };
+ delete legacy.syncOptions; delete legacy.processingOptions;
+ const printedLegacy = await captureCli(() => printSyncResult({ ...bare, failures: [legacy] }));
+ expect(printedLegacy).toContain(`Fix the cause, then run: gbrain sync --source ${f.id} --no-pull --retry-failed with the same options as the failed run (this receipt no longer records them)`);
+
+ const d = await fixture(engine, { 'note.md': 'A stable discovery observation.\n' });
+ const execute = engine.executeRaw;
+ engine.executeRaw = function (this: BrainEngine, sql: string, params?: unknown[]) {
+ if (sql.includes('SELECT id,slug,source_path,knowledge_revision FROM pages') && params?.[0] === d.id) throw new OperationError('storage_error', 'Synthetic discovery failure');
+ return execute.call(this, sql, params);
+ } as BrainEngine['executeRaw'];
+ let thrown: Error | undefined;
+ try { await performManagedSync(engine, { sourceId: d.id, noPull: true, exclude: [QUOTED_EXCLUDE] }); }
+ catch (error) { thrown = error as Error; }
+ finally { engine.executeRaw = execute; }
+ expect(thrown?.message).toContain(`Fix the cause, then run: gbrain sync --source ${d.id} --no-pull --retry-failed --exclude 'it'\\''s a dir/**'`);
+ }
+}), 120_000);
+
+test('--retry-failed counts only the failures of the cursor its own options select and names the others', async () => withEnv({ ...env, GBRAIN_BACKUP_CHECK: 'off', GBRAIN_SYNC_NO_EXTRACT_NUDGE: '1' }, async () => {
+ for (const engine of engines) {
+ const f = await fixture(engine, { 'bad.md': '---\ntitle: [broken\n---\nRetry count fixture.\n' });
+ await engine.executeRaw("UPDATE sources SET config=jsonb_set(config,'{syncEnabled}','false'::jsonb) WHERE id<>$1", [f.id]);
+ const flags = ['--no-pull', '--no-embed', '--no-extract', '--no-auto-embed', '--no-schema-pack', '--source', f.id];
+ await captureCli(() => runSync(engine, [...flags, '--exclude', QUOTED_EXCLUDE]));
+ expect(await readManagedSyncFailures(engine, [f.id])).toHaveLength(1);
+
+ const other = await captureCli(() => runSync(engine, [...flags, '--retry-failed']));
+ expect(other).toContain('1 previously-failed file(s) of this source belong to a run with different sync options and are not retried by this invocation.');
+ expect(other).toContain(`gbrain sync --source ${f.id} --no-pull --retry-failed --no-embed --no-extract --no-schema-pack --exclude 'it'\\''s a dir/**'`);
+ expect(other).not.toContain('Retrying 1 previously-failed file(s)');
+
+ const same = await captureCli(() => runSync(engine, [...flags, '--exclude', QUOTED_EXCLUDE, '--retry-failed']));
+ expect(same).toContain('Retrying 1 previously-failed file(s)...');
+ }
+}), 120_000);
+
test('checkpoint, discovery, and freeze failures remain diagnosable without a file receipt', async () => withEnv(env, async () => {
for (const engine of engines) {
const f = await fixture(engine, { 'note.md': 'A stable observation before checkpoint.\n' });